<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Nathan Sebhastian - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Nathan Sebhastian - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 09 May 2026 16:24:43 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/nathansebhastian/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Learn React – A Handbook for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ The goal of this handbook is to provide gentle step-by-step instructions that will help you learn the key concepts of React. Instead of covering all the theories and concepts of React in their entirety, I'll be teaching you important building blocks ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-for-beginners-handbook/</link>
                <guid isPermaLink="false">66bd919d1bb54b9103c678c0</guid>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Fri, 01 Mar 2024 00:34:46 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/Learn-React-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The goal of this handbook is to provide gentle step-by-step instructions that will help you learn the key concepts of React.</p>
<p>Instead of covering all the theories and concepts of React in their entirety, I'll be teaching you important building blocks of the library. You'll learn about JSX, components, props, states, event handlers, creating forms, and running network requests.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-requirements">Requirements</a></li>
<li><a class="post-section-overview" href="#heading-chapter-1-introduction">Chapter 1: Introduction</a><ul>
<li><a class="post-section-overview" href="#heading-computer-setup">Computer Setup</a></li>
<li><a class="post-section-overview" href="#heading-your-first-react-application">Your First React Application</a></li>
<li><a class="post-section-overview" href="#heading-explaining-the-source-code">Explaining the Source Code</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-2-how-to-create-react-components">Chapter 2: How to Create React Components</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-return-multiple-elements-with-fragments">How to Return Multiple Elements With Fragments</a></li>
<li><a class="post-section-overview" href="#heading-how-to-render-to-the-screen">How to Render to the Screen</a></li>
<li><a class="post-section-overview" href="#heading-how-to-write-comments-in-react">How to Write Comments in React</a></li>
<li><a class="post-section-overview" href="#heading-how-to-compose-multiple-components-as-one">How to Compose Multiple Components as One</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-3-making-sense-of-jsx">Chapter 3: Making Sense of JSX</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-render-a-list-using-jsx">How to Render a List Using JSX</a></li>
<li><a class="post-section-overview" href="#heading-how-to-add-the-class-attribute">How to Add the Class Attribute</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-4-props-and-states">Chapter 4: Props and States</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-pass-down-multiple-props">How to Pass Down Multiple Props</a></li>
<li><a class="post-section-overview" href="#heading-props-are-immutable">Props are Immutable</a></li>
<li><a class="post-section-overview" href="#heading-state-in-react">State in React</a></li>
<li><a class="post-section-overview" href="#heading-how-to-pass-state-to-a-child-component">How to Pass State to a Child Component</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-react-devtools-to-inspect-states-and-props">How to Use React DevTools to Inspect States and Props</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-5-react-conditional-rendering">Chapter 5: React Conditional Rendering</a><ul>
<li><a class="post-section-overview" href="#heading-partial-rendering-with-a-regular-variable">Partial Rendering with a Regular Variable</a></li>
<li><a class="post-section-overview" href="#heading-inline-rendering-with-the-ampamp-operator">Inline Rendering with the &amp;&amp; Operator</a></li>
<li><a class="post-section-overview" href="#heading-inline-rendering-with-the-conditional-ternary-operator">Inline Rendering with the Conditional (Ternary) Operator</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-6-how-to-handle-user-events">Chapter 6: How to Handle User Events</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-change-the-ui-by-handling-events">How to Change the UI by Handling Events</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-7-css-in-react">Chapter 7: CSS in React</a><ul>
<li><a class="post-section-overview" href="#heading-react-inline-styling">React Inline Styling</a></li>
<li><a class="post-section-overview" href="#heading-css-files">CSS Files</a></li>
<li><a class="post-section-overview" href="#heading-css-modules">CSS Modules</a></li>
<li><a class="post-section-overview" href="#heading-tailwind-css">Tailwind CSS</a></li>
<li><a class="post-section-overview" href="#heading-which-one-should-you-use">Which One Should You Use?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-8-how-to-build-forms-in-react">Chapter 8: How to Build Forms in React</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-handle-form-input">How to Handle Form Input</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-form-submission">How to Handle Form Submission</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-form-validation">How to Handle Form Validation</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-chapter-9-network-requests-in-react">Chapter 9: Network Requests in React</a><ul>
<li><a class="post-section-overview" href="#heading-the-useeffect-hook">The useEffect Hook</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></li>
</ul>
<p>By covering these concepts, you'll be equipped to dive further into advanced React topics.</p>
<h2 id="heading-requirements">Requirements</h2>
<p>To get the full benefit of this handbook, you should have basic knowledge of HTML, CSS, and JavaScript. No previous knowledge about React is needed, as we will start from the very basics.</p>
<p>If you need a JavaScript refresher, you can <a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript">get my JavaScript book here</a>.</p>
<h2 id="heading-chapter-1-introduction">Chapter 1: Introduction</h2>
<p>React is a very popular JavaScript front-end library. It's received lots of love from developers around the world for its <strong>simplicity</strong> and <strong>fast performance</strong>.</p>
<p>React was initially developed by Facebook as a solution to front end problems they were facing:</p>
<ul>
<li>DOM manipulation is an expensive operation and should be minimized</li>
<li>No library specialized in handling front-end development at the time (there is Angular, but it's an ENTIRE framework.)</li>
<li>Using a lot of vanilla JavaScript can turn a web application into a mess that's hard to maintain.</li>
</ul>
<p>Why do developers love React? As a software developer myself, I can think of a few reasons why I love it:</p>
<ul>
<li><strong>It's minimalist</strong>. React takes care of only ONE thing: the user interface and how it changes according to the data you feed into it. React makes your interface dynamic with minimal code.</li>
<li><strong>It has a low learning curve</strong>. The core concepts of React are relatively easy to learn, and you don't need months or 40 hours of video lectures to learn the basics.</li>
<li><strong>It's unopinionated</strong>. React can be integrated with lots of different technologies. On the front-end, you can use different libraries to handle Ajax calls (Axios, Superagent, or just plain Fetch.) On the back-end, you can use PHP/ Ruby/ Go/ Python or whatever language you prefer.</li>
<li><strong>It has strong community support</strong>. To enhance React's capabilities, open source contributors have built an amazing ecosystem of libraries that enables you to make even more powerful applications. But most open source libraries for React are optional. You don't need to learn them until you've mastered React fundamentals.</li>
</ul>
<p>The bottom line is that with a low learning curve, React gives you incredible power in making your UI flexible, reusable, and spaghetti-free.</p>
<p>Learning React opens tremendous opportunities if you want to work as a web developer.</p>
<h3 id="heading-computer-setup">Computer Setup</h3>
<p>To start programming with React, you'll need to have three things:</p>
<ol>
<li>A web browser</li>
<li>A code editor</li>
<li>Node.js</li>
</ol>
<p>We're going to use the Chrome browser to run our JavaScript code, so if you don't have it, <a target="_blank" href="https://www.google.com/chrome/">you can download it here</a>.</p>
<p>The browser is available for all major operating systems. Once the download is complete, install the browser on your computer.</p>
<p>Next, you'll need to install a code editor if you don't already have one. There are several free code editors available on the Internet, such as Sublime Text, Visual Studio Code, and Notepad++.</p>
<p>Out of these editors, my favorite is Visual Studio Code, because it's fast and easy to use.</p>
<h4 id="heading-how-to-install-visual-studio-code">How to install Visual Studio Code</h4>
<p>Visual Studio Code, or VSCode for short, is an application created for the purpose of writing code. Aside from being free, VSCode is fast and available on all major operating systems.</p>
<p>You can <a target="_blank" href="https://code.visualstudio.com/">download Visual Studio Code here</a>.</p>
<p>When you open the link above, there should be a button showing the version compatible with your operating system as shown below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/1-installvscode-2.png" alt="Image" width="600" height="400" loading="lazy">
<em>Downloading Visual Studio Code</em></p>
<p>Click the button to download VSCode, and install it on your computer.</p>
<p>Now that you have a code editor installed, the next step is to install Node.js</p>
<h4 id="heading-how-to-install-nodejs">How to install Node.js</h4>
<p>Node.js is a JavaScript runtime application that enables you to run JavaScript outside of the browser. You need to install this application on your computer to install packages required in React development.</p>
<p>You can download and install Node.js from <a target="_blank" href="https://nodejs.org/">https://nodejs.org</a>. Pick the recommended LTS version because it has long-term support. The installation process is pretty straightforward.</p>
<p>To check if Node has been properly installed, type the command below on your command line (Command Prompt on Windows or Terminal on Mac):</p>
<pre><code class="lang-sh">node -v
</code></pre>
<p>The command line should respond with the version of the Node.js you have on your computer.</p>
<h3 id="heading-your-first-react-application">Your First React Application</h3>
<p>It's time to run your first React application. First, create a folder on your computer that will be used to store all files related to this book. You can name the folder 'beginning_react'.</p>
<p>The next step is to open your terminal and run the npm command to create a new React application using Vite.</p>
<p>Vite (pronounced 'veet') is a build tool that you can use to bootstrap a new React project. Inside the 'beginning_react' folder, you need to run the following command to create a new React project with Vite:</p>
<pre><code class="lang-sh">npm create vite@5.1.0 my-react-app -- --template react
</code></pre>
<p>You should see npm asking to install a new package (create-vite) as shown below. Proceed by typing 'y' and pressing Enter:</p>
<pre><code class="lang-txt">Need to install the following packages:
  create-vite@5.1.0
Ok to proceed? (y) y
</code></pre>
<p>Then Vite will create a new React project named 'my-react-app' as follows:</p>
<pre><code class="lang-txt">Scaffolding project in /dev/beginning_react/my-react-app...

Done. Now run:

  cd my-react-app
  npm install
  npm run dev
</code></pre>
<p>When you're done, follow the next steps you see in the output above. Use the <code>cd</code> command to change the working directory to the application you've just created, and then run <code>npm install</code> to install the packages required by the application.</p>
<p>Then, you need to run the <code>npm run dev</code> command to start your application:</p>
<pre><code class="lang-txt">$ npm run dev

&gt; my-react-app@0.0.0 dev
&gt; vite


  VITE v5.0.10  ready in 509 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h + enter to show help
</code></pre>
<p>Now you can view the running application from the browser, at the designated localhost address:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/1-vite-react-demo.png" alt="Image" width="600" height="400" loading="lazy">
<em>Vite-React Home Page</em></p>
<p>This means you have successfully created your first React app. Congratulations!</p>
<h3 id="heading-explaining-the-source-code">Explaining the Source Code</h3>
<p>Now that you've successfully run a React application, let's take a look at the source code generated by Vite to understand how things work.</p>
<p>Run the Visual Studio Code you've installed in the previous section, and open the 'my-react-app' folder inside VSCode.</p>
<p>Here, you should see several folders and files that make up the React application as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/1-vite-react-app.png" alt="Image" width="600" height="400" loading="lazy">
<em>Vite-React Application Structure</em></p>
<p>The <code>vite.config.js</code> is a configuration file that instructs Vite on how to run the application. Because we have a React application, you'll see the React plugin imported inside:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { defineConfig } <span class="hljs-keyword">from</span> <span class="hljs-string">'vite'</span>
<span class="hljs-keyword">import</span> react <span class="hljs-keyword">from</span> <span class="hljs-string">'@vitejs/plugin-react'</span>

<span class="hljs-comment">// https://vitejs.dev/config/</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> defineConfig({
  <span class="hljs-attr">plugins</span>: [react()],
})
</code></pre>
<p>When you run the <code>npm run dev</code> command, Vite will look into this file to know how to run the program.</p>
<p>The <code>package.json</code> file stores the information about the project, including the packages required to run the project without any issues. The <code>package-lock.json</code> file keeps track of the installed package versions.</p>
<p>The <code>.eslintrc.cjs</code> file contains ESLint rules. ESLint is a code analysis tool that can identify problematic code in your project without needing to run the project. It will report any errors and warnings in VSCode.</p>
<p>The <code>index.html</code> file is a static HTML document that's going to be used when running the React application, and the <code>README.md</code> file contains an introduction to the project.</p>
<p>You don't need to modify any of these files. Instead, let's go to the <code>src/</code> folder where the React application code is written.</p>
<pre><code class="lang-txt">src
├── App.css
├── App.jsx
├── assets
│   └── react.svg
├── index.css
└── main.jsx
</code></pre>
<p>First, the <code>App.css</code> file contains the CSS rules applied to the <code>App.jsx</code> file, which is the main React application code.</p>
<p>The <code>assets/</code> folder contains the assets required for this project. In this case, it's the React icon, which you had seen in the browser.</p>
<p>The <code>index.css</code> file is the root CSS file applied globally to the application, and the <code>main.jsx</code> file is the root file that access the <code>index.html</code> file to render the React application. Here's the content of <code>main.jsx</code> file:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/client'</span>
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App.jsx'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./index.css'</span>

ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>)).render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">React.StrictMode</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">React.StrictMode</span>&gt;</span></span>,
)
</code></pre>
<p>Here, you can see that the ReactDOM library creates a root at the <code>&lt;div&gt;</code> element that contains the <code>root</code> ID, then renders the whole React application to that element.</p>
<p>You can open the <code>App.jsx</code> file to view the React code:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> reactLogo <span class="hljs-keyword">from</span> <span class="hljs-string">'./assets/react.svg'</span>
<span class="hljs-keyword">import</span> viteLogo <span class="hljs-keyword">from</span> <span class="hljs-string">'/vite.svg'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>)

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://vitejs.dev"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{viteLogo}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"logo"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Vite logo"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://react.dev"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{reactLogo}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"logo react"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"React logo"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Vite + React<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"card"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount((count) =&gt; count + 1)}&gt;
          count is {count}
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          Edit <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>src/App.jsx<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span> and save to test HMR
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"read-the-docs"</span>&gt;</span>
        Click on the Vite and React logos to learn more
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>In this file, a single component named <code>App</code> is defined. The Vite and React logos are rendered with a link to the respective library, and there's a counter button that will increment the counter by 1 when you click on it.</p>
<p>This file is where we will be exploring the fundamentals of React. Let's delete everything in this file, and write a simple <code>App</code> component that renders a <code>&lt;h1&gt;</code> element:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>Next, delete the <code>index.css</code>, <code>app.css</code>, and <code>assets/</code> folder. You also need to delete the <code>import './index.css'</code> statement in your <code>main.jsx</code> file.</p>
<p>If you open the browser again, you should see a single heading rendered as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/1-react-hello-world.png" alt="Image" width="600" height="400" loading="lazy">
<em>React Output From Code Changes</em></p>
<p>Alright! Now you're ready to learn the fundamentals of React. We'll start your first lesson in the next chapter.</p>
<h2 id="heading-chapter-2-how-to-create-react-components">Chapter 2: How to Create React Components</h2>
<p>In React, a component is a single independent unit of a user interface (UI). What you write inside a component will determine what should appear on the browser screen at a given time.</p>
<p>In the previous chapter, we created an <code>App</code> component that returns a heading element:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>A component is made up of a function that returns a single UI element.</p>
<p>When you want a component to render nothing, you can return a <code>null</code> or <code>false</code> instead of an element.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>
}
</code></pre>
<p>All React components are saved under the <code>.jsx</code> file extension. As you can see in this project, you have <code>main.jsx</code> and <code>App.jsx</code>.</p>
<p>What is JSX? It's an extension of JavaScript that produces JavaScript-powered HTML elements. We're going to learn about it later.</p>
<h3 id="heading-how-to-return-multiple-elements-with-fragments">How to Return Multiple Elements With Fragments</h3>
<p>A component must always return a single element. When you need to return multiple elements, you need to wrap all of them in a single element like a <code>&lt;div&gt;</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>But this will make your application render one extra <code>&lt;div&gt;</code> element in the browser. To avoid cluttering your application, you can render an empty tag <code>&lt;&gt;</code> like this:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>The empty tag above is a React feature called a Fragment. By using a Fragment, your component won't render an extra element to the screen.</p>
<p>You can also import the <code>Fragment</code> module from React to make it explicit as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { Fragment } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Fragment</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Fragment</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>But you don't need to explicitly state the <code>Fragment</code> tag. Using an empty tag <code>&lt;&gt;</code> is enough.</p>
<h3 id="heading-how-to-render-to-the-screen">How to Render to the Screen</h3>
<p>To render a React component into the browser, you need to create a root React component using the ReactDOM library, which you've seen previously when viewing the <code>main.jsx</code> file.</p>
<p>You need to have an HTML file as the source from which your React component is rendered. </p>
<p>Usually, a very basic HTML document with a <code>&lt;div&gt;</code> is enough, as you can see in the <code>index.html</code> file:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"root"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/src/main.jsx"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>Next, you render the component into the <code>&lt;div&gt;</code> element. </p>
<p>Notice how ReactDOM is imported from <code>react-dom</code> package, and the <code>document.getElementById('root')</code> is used to select the <code>&lt;div&gt;</code> element below:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/client'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}

ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>)).render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">React.StrictMode</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">React.StrictMode</span>&gt;</span></span>,
)
</code></pre>
<p>Here, you can see that the <code>App</code> component is placed in the same file as the ReactDOM library. You can do this if you want to remove the <code>App.jsx</code> file, so you have only a single <code>main.jsx</code> file as the source for your React application.</p>
<p>But it's confusing to have multiple components in one file, so let's not do this.</p>
<h3 id="heading-how-to-write-comments-in-react">How to Write Comments in React</h3>
<p>Writing comments in React components is similar to how you comment in regular JavaScript code. You can use the double forward slash syntax <code>//</code> to comment any code.</p>
<p>The following example shows how to comment the <code>export</code> statement:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}

<span class="hljs-comment">// export default App</span>
</code></pre>
<p>When you want to comment the code inside the <code>return</code> statement, you need to use the curly brackets, forward slash, and asterisk format <code>{/* comment here */}</code> as shown below:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {/* <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learning to code with React<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span> */}
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>It may seem very annoying that you need to remember two different ways of commenting when writing React applications. But don't worry, because a modern tool like VSCode knows how to generate the right comment syntax.</p>
<p>You only need to press the comment shortcut, which is <code>CTRL + /</code> for Windows/ Linux or <code>Command + /</code> for macOS.</p>
<h3 id="heading-how-to-compose-multiple-components-as-one">How to Compose Multiple Components as One</h3>
<p>Up until this point, you've only rendered a single <code>App</code> component to the browser. But applications built using React can be composed of tens or hundreds of components.</p>
<p><strong>Composing components</strong> is the process of forming the user interface by using loosely coupled components. It's kind of like making a house out of Lego blocks, as I will show you in the following example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">UserComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ProfileComponent</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">FeedComponent</span> /&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> User Component <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ProfileComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> Profile Component <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">FeedComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span> Feed Component<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}
</code></pre>
<p>From the example above, you can see how the <code>&lt;ParentComponent&gt;</code> renders three children components:</p>
<ul>
<li><code>&lt;UserComponent&gt;</code></li>
<li><code>&lt;ProfileComponent&gt;</code></li>
<li><code>&lt;FeedComponent&gt;</code></li>
</ul>
<p>The composition of many components will form a single tree of React components in a top-down approach.</p>
<p>The tree will then be rendered into the DOM through the <code>ReactDOM.render()</code> method:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/2-react-tree.png" alt="Image" width="600" height="400" loading="lazy">
<em>React Component Tree Illustrated</em></p>
<p>By composing multiple components, you can split the user interface into independent, reusable pieces, and develop each piece in isolation.</p>
<h2 id="heading-chapter-3-making-sense-of-jsx">Chapter 3: Making Sense of JSX</h2>
<p>In the previous chapter, you learned that a component must always have a <code>return</code> statement that contains elements to render on the screen:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre>
<p>The tag <code>&lt;h1&gt;</code> looks like a regular HTML tag, but it's actually a special template language included in React called JSX.</p>
<p>JSX is a syntax extension that produces JavaScript powered HTML elements. It can be assigned to JavaScript variables and can be returned from function calls. For example:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> myElement = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
  <span class="hljs-keyword">return</span> myElement
}
</code></pre>
<p>Because of JSX, you can also embed JavaScript expressions inside an element by using curly brackets <code>{}</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> lowercaseClass = <span class="hljs-string">'text-lowercase'</span>;
<span class="hljs-keyword">const</span> text = <span class="hljs-string">'Hello World!'</span>;
<span class="hljs-keyword">const</span> App = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{lowercaseClass}</span>&gt;</span>{text}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
</code></pre>
<p>This is what makes React elements different from HTML elements. You can't embed JavaScript directly by using curly braces in HTML.</p>
<p>Instead of creating a whole new templating language, you just need to use JavaScript functions to control what is being displayed on the screen.</p>
<h3 id="heading-how-to-render-a-list-using-jsx">How to Render a List Using JSX</h3>
<p>For example, let's say you have an array of users that you'd like to show:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> users = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Nathan'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Web Developer'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Web Designer'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Jane'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Team Leader'</span> },
]
</code></pre>
<p>You can use the <code>map()</code> function to loop over the array:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> users = [
    { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Nathan'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Web Developer'</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Web Designer'</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Jane'</span>, <span class="hljs-attr">role</span>: <span class="hljs-string">'Team Leader'</span> },
  ]

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The currently active users list:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      {
        users.map(function(user){
          // returns Nathan, then John, then Jane
          return (
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span> {user.name} as the {user.role} <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
          )
        })
      }
      <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>Inside React, you don't need to store the return value of the <code>map()</code> function in a variable. The example above will return a <code>&lt;li&gt;</code> element for each array value into the component.</p>
<p>While the above code is already complete, React will trigger an error in the console, saying that you need to put a "key" prop in each child of a list (the element that you return from <code>map()</code> function):</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/3-react-array-warning.png" alt="Image" width="600" height="400" loading="lazy">
<em>React 'key' Warning on Browser Console</em></p>
<p>A prop (short for property) is an input that you can pass to a component when rendering that component. The <code>key</code> prop is a special prop that React will use to determine which child element has been changed, added, or removed from the list.</p>
<p>You won't use it actively in any part of your array rendering code, but React will ask for one when you render a list.</p>
<p>It is recommended that you put the unique identifier of your data as the key value. In the example above, you can use the <code>user.id</code> data. Here's how you pass a <code>key</code> prop for each <code>&lt;li&gt;</code> element:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">return</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{user.id}</span>&gt;</span> 
    {user.name} as the {user.role} 
  <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
)
</code></pre>
<p>When you don't have any unique identifiers for your list, you can use the array <code>index</code> value as the last resort:</p>
<pre><code class="lang-jsx">users.map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">user, index</span>)</span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{index}</span>&gt;</span>
      {user.name} as the {user.role}
    <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
  )
})
</code></pre>
<p>Props are one of the ingredients that make a React component powerful. You're going to learn more about it in the next chapter.</p>
<h3 id="heading-how-to-add-the-class-attribute">How to Add the Class Attribute</h3>
<p>You can add the <code>class</code> attribute to your elements by using the <code>className</code> keyword:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'text-lowercase'</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre>
<p>The keyword <code>class</code> is reserved for JavaScript classes, so you need to use <code>className</code> instead.</p>
<h2 id="heading-chapter-4-props-and-states">Chapter 4: Props and States</h2>
<p>Props and states are used to pass data inside React components. Props (or properties) are inputs passed down from a parent component to its child component.</p>
<p>On the other hand, states are variables defined and managed inside the components.</p>
<p>Let's start by understanding props. Suppose you have a <code>ParentComponent</code> that renders a <code>ChildComponent</code> like this:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> /&gt;</span></span>
}
</code></pre>
<p>You can pass a prop from <code>ParentComponent</code> into <code>ChildComponent</code> by adding a new attribute after the component name.</p>
<p>In the code below, the <code>name</code> prop with the value 'John' is passed to the <code>ChildComponent</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">name</span>=<span class="hljs-string">'John'</span> /&gt;</span></span>
}
</code></pre>
<p>When the component is rendered on the browser, the <code>ChildComponent</code> will receive the name prop into the component.</p>
<p>You can access the <code>props</code> object by defining it in the function component's argument:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">props</span>)</span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Hello World! my name is {props.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}
</code></pre>
<p>The <code>props</code> parameter will always be an object, and any prop you define when rendering the component will be passed as a property to the object.</p>
<h3 id="heading-how-to-pass-down-multiple-props">How to Pass Down Multiple Props</h3>
<p>You can pass as many props as you want into a single child component. Just add the props when using the component as shown below:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span>
      <span class="hljs-attr">name</span>=<span class="hljs-string">"John"</span>
      <span class="hljs-attr">age</span>=<span class="hljs-string">{29}</span>
      <span class="hljs-attr">hobbies</span>=<span class="hljs-string">{[</span>"<span class="hljs-attr">read</span> <span class="hljs-attr">books</span>", "<span class="hljs-attr">drink</span> <span class="hljs-attr">coffee</span>"]}
      <span class="hljs-attr">occupation</span>=<span class="hljs-string">"Software Engineer"</span>
    /&gt;</span></span>
  )
}
</code></pre>
<p>All the props above will be passed to the ChildComponent's <code>props</code> parameter.</p>
<p>You can even pass a function into props like this:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetings</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello World'</span>
  }

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">greetings</span>=<span class="hljs-string">{greetings}</span> /&gt;</span></span>
}
</code></pre>
<p>In the child component, you can call the function as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{props.greetings()}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}
</code></pre>
<p>Note that if you pass anything other than a string as a prop value, you need to put the value in curly brackets (numbers, functions, arrays, objects, and so on)</p>
<p>This is because JavaScript expressions can't be processed by JSX unless you put the expression inside curly brackets.</p>
<h3 id="heading-props-are-immutable">Props are Immutable</h3>
<p>Immutable means that a prop's value can't be changed no matter what happens.</p>
<p>In the code below, the <code>ChildComponent</code> tries to change the value of <code>props.name</code> property:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">props</span>)</span>{
  props.name = <span class="hljs-string">'Mark'</span>;
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Hello World! my name is {props.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">name</span>=<span class="hljs-string">'John'</span>/&gt;</span></span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ParentComponent
</code></pre>
<p>But you'll get an error in the console as follows:</p>
<pre><code class="lang-txt">Uncaught TypeError: Cannot assign to read only property 'name' of object '#&lt;Object&gt;'
</code></pre>
<p>As you can see, React props can't be changed once you declare them. But what if your data needs to change as a user interacts with your application? This is where state comes to the rescue.</p>
<h3 id="heading-state-in-react">State in React</h3>
<p>In React, states are arbitrary data that you can declare and manage in your components. To create a state in React, you need to call the <code>useState</code> hook as shown below:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">'John'</span>)

}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ParentComponent
</code></pre>
<p>In React, hooks are functions that allow you to tap into the features provided by React. The <code>useState</code> hook is a function that enables you to put value into the state mechanism.</p>
<p>When calling the <code>useState()</code> function, you can pass an argument that will serve as the initial value of the state. The function then returns an array with two elements.</p>
<p>The first element holds the state value, and the second element is a function that allows you to change the state value. You need to use the destructuring array syntax to receive both elements as shown above</p>
<p>You can give any names to the variables returned by <code>useState</code>, but it's recommended to use <code>[something, setSomething]</code>.</p>
<p>To render the state value, you can embed it into JSX as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">'John'</span>)

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello {name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
}
</code></pre>
<p>If you want to change the value of the <code>name</code> variable, you need to use the provided <code>setName()</code> function.</p>
<p>But you can't call <code>setName()</code> in the component's body, because React will refresh itself anytime you change the state value.</p>
<p>Instead, you can create a button that will change the value of name when you click it:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">'John'</span>)

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello {name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setName('Mark')}&gt;Change Name<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>In the code above, we create a <code>&lt;button&gt;</code> element and add the <code>onClick</code> prop, which gets executed anytime we click on the button.</p>
<p>Inside the prop, we pass a function that simply calls the <code>setName()</code> function, changing the state value.</p>
<h3 id="heading-how-to-pass-state-to-a-child-component">How to Pass State to a Child Component</h3>
<p>You can pass the state into any child component. When you need to update the state from a child component, you need to pass the <code>setSomething</code> function received from the <code>useState</code> hook.</p>
<p>Here's an example of passing a state from <code>ParentComponent</code> to <code>ChildComponent</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">'John'</span>)

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">name</span>=<span class="hljs-string">{name}</span> <span class="hljs-attr">setName</span>=<span class="hljs-string">{setName}</span> /&gt;</span></span>
}
</code></pre>
<p>In the <code>ChildComponent</code>, you can call the <code>setName()</code> function from <code>props</code> like this:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello {props.name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> props.setName('Mark')}&gt;Change Name<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>When the button on the <code>ChildComponent</code> is clicked, the value of the <code>name</code> state will change. Internally, React will refresh the application and reflect the changes in the user interface.</p>
<h3 id="heading-how-to-use-react-devtools-to-inspect-states-and-props">How to Use React DevTools to Inspect States and Props</h3>
<p>To help ease your development, you can install the React Developer Tools (DevTools for short) to inspect the current state and props value of your components. </p>
<p>You can <a target="_blank" href="https://chromewebstore.google.com/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi">install React DevTool for Chrome here</a>.</p>
<p>Once installed, open the developer tool and you should have two extra tabs called <em>Components</em> and <em>Profiler</em> as shown below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/4-react-devtool-chrome.png" alt="Image" width="600" height="400" loading="lazy">
<em>Opening React DevTool</em></p>
<p>Similar to how you can inspect CSS rules applied to HTML elements, you can inspect the state and props of React components using the developer tools. Click the <em>Components</em> tab, and inspect one of the two components we created earlier.</p>
<p>Below, you can see the props and state of the <code>ParentComponent</code>, as well as other details:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/4-react-devtool-inspect.png" alt="Image" width="600" height="400" loading="lazy">
<em>Inspecting Components With React DevTool</em></p>
<p>When you click on the button, the state value will change accordingly. You can inspect the <code>ChildComponent</code> to view its details. These DevTools will come in handy when you develop React applications.</p>
<h2 id="heading-chapter-5-react-conditional-rendering">Chapter 5: React Conditional Rendering</h2>
<p>You can control what output is being rendered by a component by implementing conditional rendering in your JSX code.</p>
<p>For example, let's say you want to switch between rendering the login and logout buttons, depending on the availability of the <code>user</code> state:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">const</span> { user } = props

  <span class="hljs-keyword">if</span> (user) {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Logout<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  }
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>You don't need to add an <code>else</code> statement in the component because React will stop further processes once it reaches a <code>return</code> statement.</p>
<p>In the example above, React will render the logout button when the <code>user</code> value is truthy, and the login button when <code>user</code> is falsy.</p>
<h3 id="heading-partial-rendering-with-a-regular-variable">Partial Rendering with a Regular Variable</h3>
<p>When developing with React, there will be cases where you want to render a part of your UI dynamically in a component.</p>
<p>In the example below, the JSX element is stored in a variable called <code>button</code>, and that variable is used again in the <code>return</code> statement:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">const</span> { user } = props

  <span class="hljs-keyword">let</span> button = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>

  <span class="hljs-keyword">if</span> (user) {
    button = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Logout<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello there!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {button}
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>Instead of writing two return statements, you store the dynamic UI element inside a variable and use that variable in the <code>return</code> statement.</p>
<p>This way, you can have a component that has static and dynamic elements.</p>
<h3 id="heading-inline-rendering-with-the-ampamp-operator">Inline Rendering with the <code>&amp;&amp;</code> Operator</h3>
<p>It's possible to render a component only if a certain condition is met and render null otherwise.</p>
<p>For example, let's say you want to render a dynamic message for users when they have new emails in their inbox:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> newEmails = <span class="hljs-number">2</span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello there!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {newEmails &gt; 0 &amp;&amp;
        <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>
          You have {newEmails} new emails in your inbox.
        <span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      }
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>In this example, the <code>&lt;h2&gt;</code> element only gets rendered when the <code>newEmails</code> count is greater than 0.</p>
<h3 id="heading-inline-rendering-with-the-conditional-ternary-operator">Inline Rendering with the Conditional (Ternary) Operator</h3>
<p>It's also possible to use a ternary operator in order to render the UI dynamically.</p>
<p>Take a look at the following example:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">const</span> { user } = props

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello there!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      { user? <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Logout<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> : <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> }
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>Instead of using a variable to hold the <code>&lt;button&gt;</code> element, you can simply use the ternary operator on the <code>user</code> value and render 'Logout' or 'Login' button according to the variable's value.</p>
<h2 id="heading-chapter-6-how-to-handle-user-events">Chapter 6: How to Handle User Events</h2>
<p>Under the hood, React has an internal event handler that connects to the native DOM event.</p>
<p>This is why we can add the <code>onClick</code> prop to buttons in the previous chapters, which gets executed in response to a click event.</p>
<p>When you call a function in response to events, the <code>event</code> object will be passed to the callback function as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!"</span>);
    <span class="hljs-built_in">console</span>.log(event);
  }
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span>&gt;</span>
      Click me
    <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  )
}
</code></pre>
<p>When you click on the button above, the <code>event</code> variable will be logged as a <code>SyntheticBaseEvent</code> object in your console:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/8-react-synthetic-event.png" alt="Image" width="600" height="400" loading="lazy">
<em>React's SyntheticBaseEvent Log</em></p>
<p>The <code>SyntheticBaseEvent</code> object is a built-in React object used to interact with the native DOM events. Different browsers have different implementations of the DOM event object, so the <code>SyntheticBaseEvent</code> makes React compatible with these browsers.</p>
<p>Whenever a DOM event is triggered, that synthetic event will be handled by React so that you can decide what to do with that event.</p>
<p>The use case for this Synthetic event is the same as the native DOM event. Three of the most common event handlers you're going to use are:</p>
<ul>
<li><code>onChange</code></li>
<li><code>onClick</code></li>
<li><code>onSubmit</code></li>
</ul>
<p>You can respond to user interactions like clicking, hovering, focusing or typing on a form input, submitting a form, and so on.</p>
<h3 id="heading-how-to-change-the-ui-by-handling-events">How to Change the UI By Handling Events</h3>
<p>In the previous chapter, you saw how conditional logic can be used to render different outputs.</p>
<p>By combining conditional logic with state, props, and event handlers, you can create a dynamic component that renders different outputs based on the data it currently holds.</p>
<p>For example, suppose you want to show or hide a <code>&lt;div&gt;</code> element with a button click. Here's how you do it:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// State to hold the visibility status of the paragraph</span>
  <span class="hljs-keyword">const</span> [isParagraphVisible, setIsParagraphVisible] = useState(<span class="hljs-literal">true</span>);

  <span class="hljs-comment">// Function to toggle the visibility status of the paragraph</span>
  <span class="hljs-keyword">const</span> toggleStatus = <span class="hljs-function">() =&gt;</span> {
    setIsParagraphVisible(!isParagraphVisible);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Change UI based on click<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      {isParagraphVisible &amp;&amp; (
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This paragraph will be shown/hidden on click<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      )}
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{toggleStatus}</span>&gt;</span>
        {isParagraphVisible ? 'Hide' : 'Show'} Paragraph
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>First, you create a state to hold the visibility status of the paragraph using the <code>useState</code> hook. The default value of the state is <code>true</code>.</p>
<p>Next, a function named <code>toogleStatus()</code> is defined. This function will change the <code>status</code> value from <code>true</code> to <code>false</code> and vice versa.</p>
<p>Finally, a <code>return</code> statement is added to render the elements to the screen. When the button is clicked, the <code>toogleStatus()</code> function will be executed. This will show or hide the paragraph depending on the current status.</p>
<p>By using states, props, and event handlers, the code you write becomes a description of what the user interface should look like. React then takes that description and renders it on the browser.</p>
<h2 id="heading-chapter-7-css-in-react">Chapter 7: CSS in React</h2>
<p>There are 4 common ways you can add CSS in a React application:</p>
<ol>
<li>Inline styling</li>
<li>CSS files</li>
<li>CSS modules</li>
<li>Tailwind CSS</li>
</ol>
<p>This chapter will explore these 4 different ways to write CSS in React components, and which one you should use when starting a React application.</p>
<h3 id="heading-react-inline-styling">React Inline Styling</h3>
<p>React components are composed of JSX elements. But just because you're not writing regular HTML elements doesn't mean you can't use the old inline style method.</p>
<p>The only difference with JSX is that inline styles must be written as an object instead of a string. See the example below:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> '<span class="hljs-attr">red</span>' }}&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
  );
}
</code></pre>
<p>In the style attribute above, the first set of curly brackets is used to write JavaScript expressions. The second set of curly brackets initializes a JavaScript object.</p>
<p>Style property names that have more than one word are written in camelCase instead of using the traditional hyphenated style. For example, the usual <code>text-align</code> property is written as <code>textAlign</code> in JSX:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">textAlign:</span> '<span class="hljs-attr">center</span>' }}&gt;</span>Hello World<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
  );
}
</code></pre>
<p>Because the style attribute is an object, you can also separate the style by writing it as a constant. This way, you can reuse the style in other elements as needed:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> pStyle = {
  <span class="hljs-attr">fontSize</span>: <span class="hljs-string">'16px'</span>,
  <span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{pStyle}</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{pStyle}</span>&gt;</span>The weather is sunny today.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>If you need to extend your paragraph style further down the line, you can use the spread operator.</p>
<p>This will let you add inline styles to your already declared style object. See the <code>&lt;p&gt;</code> element below:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> pStyle = {
  <span class="hljs-attr">fontSize</span>: <span class="hljs-string">'16px'</span>,
  <span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span>
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">...pStyle</span>, <span class="hljs-attr">color:</span> '<span class="hljs-attr">green</span>', <span class="hljs-attr">textAlign:</span> '<span class="hljs-attr">right</span>' }}&gt;</span>
      When you go to work, bring your umbrella with you!
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
  )
}
</code></pre>
<p>JSX inline styles allow you to write CSS directly into your component.</p>
<p>One of the benefits of using the inline style approach is that you will have a simple component-focused styling technique. When using an object for styling, you can extend your style by spreading the object.</p>
<p>But in a big and complex project where you have hundreds of React components to manage, this might not be the best choice for you.</p>
<p>You can't specify pseudo classes using inline styles. That means you can't define rules like <code>:hover</code>, <code>:focus</code>, <code>:active</code>, and so on.</p>
<p>Also, you can't specify media queries for responsive styling. Let's consider another way to style your React app.</p>
<h3 id="heading-css-files">CSS Files</h3>
<p>Another way to add CSS in React is to use <code>.css</code> files. Vite already knows how to handle a <code>.css</code> file, so all you need to do is import the CSS file into your JSX file and add the right <code>className</code> prop to your component.</p>
<p>Let's create a <code>style.css</code> file in your project folder with the following content:</p>
<pre><code class="lang-css"><span class="hljs-comment">/* style.css */</span>
<span class="hljs-selector-class">.paragraph-text</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#ff0000</span>;
}
</code></pre>
<p>Now, let's import the CSS file into the <code>App.jsx</code> file and add the class prop to the component:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> <span class="hljs-string">'./style.css'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"paragraph-text"</span>&gt;</span>
        The weather is sunny today.
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
  );
}
</code></pre>
<p>This way, the CSS will be separated from your JavaScript files, and you can just write CSS syntax as usual.</p>
<p>You can even include a CSS framework such as Bootstrap in React with this approach. All you need to do is import the CSS file in your root component.</p>
<p>This method will enable you to use all CSS features, including pseudo classes and media queries.</p>
<h3 id="heading-css-modules">CSS Modules</h3>
<p>A CSS module is a regular CSS file with all of its class and animation names scoped locally by default.</p>
<p>When applying this method, each React component will have its own CSS file, and you need to import that CSS file into your component.</p>
<p>To let React know you're using CSS modules, name your CSS file using the <code>[name].module.css</code> convention.</p>
<p>Here's an example:</p>
<pre><code class="lang-css"><span class="hljs-comment">/* App.module.css */</span>
<span class="hljs-selector-class">.BlueParagraph</span> {
  <span class="hljs-attribute">color</span>: blue;
  <span class="hljs-attribute">text-align</span>: left;
}
<span class="hljs-selector-class">.GreenParagraph</span> {
  <span class="hljs-attribute">color</span>: green;
  <span class="hljs-attribute">text-align</span>: right;
}
</code></pre>
<p>Then import it to your component file:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> styles <span class="hljs-keyword">from</span> <span class="hljs-string">"./App.module.css"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.BlueParagraph}</span>&gt;</span>
        The weather is sunny today.
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.GreenParagraph}</span>&gt;</span>
        Still, don't forget to bring your umbrella!
      <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>When you build your app, Vite will automatically look for CSS files that have the <code>.module.css</code> name and process the class names to a new localized name.</p>
<p>Using CSS Modules ensures that your CSS classes are scoped locally, preventing CSS rules from colliding with each other.</p>
<p>Another advantage of using CSS Modules is that you can compose a new class by inheriting from other classes that you've written. This way, you'll be able to reuse CSS code that you've written previously, like this:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.MediumParagraph</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">20px</span>;
}
<span class="hljs-selector-class">.BlueParagraph</span> {
  <span class="hljs-attribute">composes</span>: MediumParagraph;
  <span class="hljs-attribute">color</span>: blue;
  <span class="hljs-attribute">text-align</span>: left;
}
<span class="hljs-selector-class">.GreenParagraph</span> {
  <span class="hljs-attribute">composes</span>: MediumParagraph;
  <span class="hljs-attribute">color</span>: green;
  <span class="hljs-attribute">text-align</span>: right;
}
</code></pre>
<p>But we're not going to explore every single feature of CSS modules here, only enough to get you familiar with them.</p>
<h3 id="heading-tailwind-css">Tailwind CSS</h3>
<p>Tailwind CSS is a modern utility-first CSS framework that allows you to style elements by combining a bunch of classes together.</p>
<p>CSS frameworks like Bootstrap and Bulma provide you with high-level components that you can immediately use in your project. When you need to style a button, you just need to apply the classes that contain the desired CSS properties:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"btn btn-primary"</span>&gt;</span>Subscribe<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>When using Bootstrap, the <code>btn</code> class provides a combination of CSS properties such as padding, color, opacity, font weight, and so on.</p>
<p>On the other hand, Tailwind gives you utility classes where each class has only one or two properties:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'px-5 py-2 text-white bg-blue-500 border-2'</span>&gt;</span>
  Subscribe
<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>In the example above, the <code>px-5</code> is short for padding <code>padding-left</code> and <code>padding-right</code>, while 5 is a specific size for the paddings. The <code>text-white</code> applies <code>color: white</code>, the <code>bg-blue-500</code> applies the <code>background-color</code> property, and <code>border</code> applies <code>border-width</code>.</p>
<h3 id="heading-which-one-should-you-use">Which One Should You Use?</h3>
<p>It depends on the method you feel comfortable with the most. If you're working with a team, you need to discuss and agree on the method you want to apply, because mixing the styles makes it hard to develop and maintain the application.</p>
<p>Remember: Always use only one way to style React components in a specific project to avoid confusion.</p>
<h2 id="heading-chapter-8-how-to-build-forms-in-react">Chapter 8: How to Build Forms in React</h2>
<p>One of the most common interfaces you're going to build as a web developer is a form. In React, you can create a form by using state as the single source of that form's data.</p>
<p>In this chapter, I will show you how to handle form input, form submission, and form validation using React.</p>
<h3 id="heading-how-to-handle-form-input">How to Handle Form Input</h3>
<p>For example, suppose you want to create a form with a single text input and a button.</p>
<p>You can first set up the state that will serve as the input value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Form</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();
}
</code></pre>
<p>Next, add the <code>return</code> statement and define the form. On the <code>&lt;input&gt;</code> element, assign the <code>username</code> state as the <code>value</code> prop:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Form</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
      Username:
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">name</span>=<span class="hljs-string">'username'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<p>Next, add the <code>onChange</code> prop to the <code>&lt;input&gt;</code> element. In that prop, assign the <code>value</code> of the text input as the value of the <code>username</code> state:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Form</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
      Username:
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> setUsername(e.target.value)}
      /&gt;
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<p>The <code>e</code> or <code>event</code> object is passed by the <code>onChange</code> prop to the callback function. From that object, we can get the value of the text input at <code>event.target.value</code> property.</p>
<p>Now whenever the input value changes, the state will be updated to reflect the changes.</p>
<h3 id="heading-how-to-handle-form-submission">How to Handle Form Submission</h3>
<p>The next step is to submit the form. Let's create a function that handles the submit event called <code>handleSubmit()</code> as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Form</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    e.preventDefault();
    alert(username);
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
      Username:
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setUsername(e.target.value)}
      /&gt;
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<p>Here, the <code>handleSubmit()</code> function will stop the default form submission behavior, which will trigger a refresh, and then create an alert box to display the <code>username</code> value.</p>
<p>The function then gets passed to the <code>onSubmit</code> prop of the <code>&lt;form&gt;</code> element. A <code>&lt;button&gt;</code> is also added so that the user can submit the form.</p>
<h3 id="heading-how-to-handle-form-validation">How to Handle Form Validation</h3>
<p>To handle form validation, you need to create another state that will store the error message. You can name this state <code>usernameError</code> as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> [usernameError, setUsernameError] = useState();
</code></pre>
<p>Next, create a <code>handleUsername()</code> function that will run when the <code>username</code> input changes.</p>
<p>Inside this function, you can call the <code>setUsername()</code> function to update the state, and then write logic to validate the input value.</p>
<p>For example, suppose the <code>username</code> length must be longer than 6. Here's how you do it:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> handleUsername = <span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> {
  <span class="hljs-keyword">const</span> { value } = e.target;
  setUsername(value);

  <span class="hljs-comment">// Validate username value:</span>
  <span class="hljs-keyword">if</span> (value.length &lt;= <span class="hljs-number">6</span>) {
    setUsernameError(<span class="hljs-string">'Username length must be more than 6 characters'</span>);
  } <span class="hljs-keyword">else</span> {
    setUsernameError();
  }
};
</code></pre>
<p>Now that you have some validation logic, you need to set the <code>handleUsername()</code> function as the <code>onChange</code> prop handler.</p>
<p>Also, add a paragraph below the <code>&lt;input&gt;</code> element that will show the error message as follows:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">return</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
    Username:
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleUsername}</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{usernameError}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
);
</code></pre>
<p>Inside the <code>handleSubmit()</code> function, you can check if there's an error on the form by checking the <code>usernameError</code> state, then prevent the form from being submitted when there is an error:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  e.preventDefault();
  <span class="hljs-keyword">if</span>(usernameError){
    alert(<span class="hljs-string">'Unable to submit: Form contain errors'</span>);
  } <span class="hljs-keyword">else</span> {
    alert(username);
  }
}
</code></pre>
<p>This way, the form won't be submitted until the error is fixed.</p>
<p>Here's the full source code of the form if you want to try it:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [username, setUsername] = useState();
  <span class="hljs-keyword">const</span> [usernameError, setUsernameError] = useState();

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    e.preventDefault();
    <span class="hljs-keyword">if</span>(usernameError){
      alert(<span class="hljs-string">'Unable to submit: Form contain errors'</span>);
    } <span class="hljs-keyword">else</span> {
      alert(username);
    }
  }

  <span class="hljs-keyword">const</span> handleUsername = <span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> { value } = e.target;
    setUsername(value);

    <span class="hljs-comment">// Validate username value:</span>
    <span class="hljs-keyword">if</span> (value.length &lt;= <span class="hljs-number">6</span>) {
      setUsernameError(<span class="hljs-string">'Username length must be more than 6 characters'</span>);
    } <span class="hljs-keyword">else</span> {
      setUsernameError();
    }
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
      Username:
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
        <span class="hljs-attr">type</span>=<span class="hljs-string">'text'</span>
        <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
        <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleUsername}</span>
      /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{usernameError}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>A form can be as complex or as simple as required, but you'll use the pattern you see here no matter what form you build:</p>
<ul>
<li>State values are used as the source of form data and validation</li>
<li><code>onChange</code> prop as a way to update the state</li>
<li>Validations are triggered by user inputs</li>
<li>A <code>handleSubmit()</code> function is executed when the form is submitted</li>
</ul>
<p>Using these building blocks, you can build any form required by your application.</p>
<h2 id="heading-chapter-9-network-requests-in-react">Chapter 9: Network Requests in React</h2>
<p>Modern web applications tend to have a modular architecture, where the back end is separated from the front end. The front end app will need to send an HTTP network request to a remote endpoint.</p>
<p>React doesn't tell you how you should send network requests. The library only focuses on rendering UI with data management using props and states.</p>
<p>To fetch data using React, you can use any valid JavaScript library like Axios, Superagent, and even the native Fetch API.</p>
<p>In this chapter, we're going to see how to do network requests using Fetch in React.</p>
<h3 id="heading-the-useeffect-hook">The useEffect Hook</h3>
<p>When you create a React application that needs to synchronize with a system outside of React, you need to use the <code>useEffect</code> hook.</p>
<p>This hook allows you to run some code after rendering so that you can synchronize your component with some system outside of React.</p>
<p>When the hook has finished performing the data request, you can set the response into your component states and render the appropriate components based on the state values.</p>
<p>To show you an example, let's fetch data from <a target="_blank" href="https://jsonplaceholder.typicode.com/todos/1">https://jsonplaceholder.typicode.com/todos/1</a> which is a dummy end point:</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [title, setTitle] = useState(<span class="hljs-string">''</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    getData();
  }, []);

  <span class="hljs-keyword">const</span> getData = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>);
    <span class="hljs-keyword">const</span> task = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(task)
    setTitle(task.title);
  };

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}
</code></pre>
<p>In the code above, we create an <code>App</code> component that has a state called <code>title</code>, and we run the Fetch API to get a todo task from the API.</p>
<p>When a response is received, we parse the JSON string into a JavaScript object, log the object, and then set the <code>title</code> state to the <code>task.title</code> property value.</p>
<p>The response is as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/9-useeffect-log.png" alt="Image" width="600" height="400" loading="lazy">
<em>React useEffect Log</em></p>
<p>Here, you can see that the <code>console.log()</code> is called twice. This is because the <code>&lt;React.StrictMode&gt;</code> wrapper always runs a <code>useEffect</code> hook twice to help you in development.</p>
<p>If you remove the <code>&lt;React.StrictMode&gt;</code> wrapper in <code>main.jsx</code>, the <code>useEffect</code> hook will run only once.</p>
<p>The <code>useEffect</code> hook itself is a function that accepts two arguments:</p>
<ul>
<li>A callback function to run on every render</li>
<li>An array of state variables to watch for changes. <code>useEffect</code> will be skipped if none of the variables are updated.</li>
</ul>
<p>When you want to run <code>useEffect</code> only once, you can pass an empty array as the second argument to the function, as shown in the example above.</p>
<p>By using the <code>useEffect</code> hook, React can send HTTP requests and fetch data from any external system, then store that data in the component state.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Congratulations on finishing this handbook! I hope you found it useful and now feel that learning React is not impossible or confusing at all. All you need is a step-by-step guide that reveals the key concepts of React one by one.</p>
<p>If you're eager to dive deeper into React and expand your skills, I encourage you to check out my new book called <em>Beginning React</em> here:</p>
<p><a target="_blank" href="https://codewithnathan.com/beginning-react"><img src="https://www.freecodecamp.org/news/content/images/2024/02/beginning-react-promo.png" alt="Beginning React Book" width="600" height="400" loading="lazy"></a></p>
<p>The goal of this book is to help you see how to build an application using React. There are two projects included in this book that will give you the "experience" of building a web application using React.</p>
<p>You will see how React concepts like components, JSX, props, states, hooks, and Context API are used to create a dynamic front-end application.</p>
<p>Here's my promise: <em>You will actually feel confident building web applications from scratch using React.</em></p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use the Geolocation API in JavaScript – with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ The Geolocation API is a standard API implemented in browsers to retrieve the location of the people who are interacting with a web application. This API enable users to send their location to a web application to enable relevant services, such as se... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-the-javascript-geolocation-api/</link>
                <guid isPermaLink="false">66bd915d621c718d60a31067</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ geolocation ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Mon, 26 Feb 2024 22:34:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/js-geolocation-api-cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The Geolocation API is a standard API implemented in browsers to retrieve the location of the people who are interacting with a web application.</p>
<p>This API enable users to send their location to a web application to enable relevant services, such as seeking a restaurant or hotel near the user.</p>
<p>In this article, I'm going to show you how to use the Geolocation API with JavaScript and display a user's current location using a map API. </p>
<p>Let's get started!</p>
<h2 id="heading-how-to-access-the-geolocation-api">How to Access the Geolocation API</h2>
<p>Browsers implement the geolocation API in the <code>navigator.geolocation</code> object. You can check if the browser you use supports this API as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (<span class="hljs-string">'geolocation'</span> <span class="hljs-keyword">in</span> navigator) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Geolocation is Available'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Geolocation is NOT Available'</span>);
}
</code></pre>
<p>If the browser replies with 'Geolocation is Available', then you can use the methods of the <code>geolocation</code> object to get the user data.</p>
<p>The Geolocation API is only available under a secure HTTPS context, but modern browsers like Chrome and Firefox allow access to this API from localhost for development purposes.</p>
<p>There are two methods you can use to get user data:</p>
<ul>
<li><code>getCurrentPosition()</code>: Returns the current position of the device.</li>
<li><code>watchPosition()</code>: Observes the position of the device continuously until the watcher is stopped.</li>
</ul>
<p>Both methods above receive 3 arguments as follows:</p>
<ul>
<li><code>success</code>: a callback function for when the geolocation data is retrieved (required).</li>
<li><code>error</code>: a callback function for when the method encounters an error (optional).</li>
<li><code>options</code>: an object defining extra parameters when running the method (optional).</li>
</ul>
<p>When the Geolocation API is accessed for the first time, a permission request will pop up near the URL bar as shown below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/geolocation-permission.png" alt="Image" width="600" height="400" loading="lazy">
<em>Requesting Permission to Access User's Location</em></p>
<p>You might be familiar with the pop up above. When you choose to block the request, then the <code>error</code> callback function will be executed by the API.</p>
<p>Otherwise, the <code>success</code> callback will be executed.</p>
<h2 id="heading-how-to-get-users-current-position">How to Get User's Current Position</h2>
<p>To get the user's current position, you can call the <code>getCurrentPosition()</code> from the <code>navigator.geolocation</code> object as shown below:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">success</span>(<span class="hljs-params">position</span>) </span>{
  <span class="hljs-built_in">console</span>.log(position);
}

navigator.geolocation.getCurrentPosition(success);
</code></pre>
<p>The <code>getCurrentPosition()</code> method will send the <code>position</code> object to the <code>success()</code> function above.</p>
<p>The <code>position</code> object contains the location coordinates and timestamp showing when the location was retrieved. </p>
<p>Below is an example of the <code>position</code> object:</p>
<pre><code class="lang-js">{
  <span class="hljs-attr">coords</span>: {
    <span class="hljs-attr">latitude</span>: <span class="hljs-number">1.314</span>,
    <span class="hljs-attr">longitude</span>: <span class="hljs-number">103.84425</span>
    <span class="hljs-attr">altitude</span>: <span class="hljs-literal">null</span>
  },
  <span class="hljs-attr">timestamp</span>: <span class="hljs-number">1708674456885</span>
}
</code></pre>
<p>Using the latitude and longitude information, you can pinpoint the user's location and provide relevant information and services.</p>
<p>For example, let's see how you can send a request to the <a target="_blank" href="https://www.openstreetmap.org/">OpenStreetMap</a> website and pin the user's current location using the data from Geolocation API.</p>
<p>OpenStreetMap is an open source project providing a free geographic map of the whole earth.</p>
<p>You need to create an HTML document with the following body content:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"getLocation"</span>&gt;</span>Get Location<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">br</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"locationResult"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>When the user clicks on the <em>Get Location</em> button above, we will access the Geolocation API, retrieve the user location, and provide a link to see the user's location on a map.</p>
<p>Next, create a <code>&lt;script&gt;</code> tag before the closing <code>&lt;/body&gt;</code> tag and write the following JavaScript code:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">const</span> locationResult = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#locationResult'</span>);
  <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#getLocation'</span>).addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
    locationResult.textContent = <span class="hljs-string">'Retrieving User Location...'</span>

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">success</span>(<span class="hljs-params">position</span>) </span>{
      <span class="hljs-keyword">let</span> { coords } = position;
      locationResult.textContent = <span class="hljs-string">'See my location on a map'</span>;
      locationResult.href = <span class="hljs-string">`https://www.openstreetmap.org?mlat=<span class="hljs-subst">${coords.latitude}</span>&amp;mlon=<span class="hljs-subst">${coords.longitude}</span>`</span>;
    }

    navigator.geolocation.getCurrentPosition(success);
  });
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>When the button is clicked, we'll run the <code>getCurrentPosition()</code> method and set the <code>href</code> attribute of the <code>&lt;a&gt;</code> tag to the OpenStreetMap website, passing along the <code>latitude</code> and <code>longitude</code> data under the <code>mlat</code> and <code>mlong</code> query string.</p>
<p>Visiting the link would show a map of the current location as shown below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/geolocation-getCurrentPosition.png" alt="OpenStreetMap Using Geolocation API data" width="600" height="400" loading="lazy">
<em>The OpenStreetMap Website Pin On the Latitude and Longitude Data</em></p>
<p>And that's how you get the current location of the user. How to process the location information is up to you.</p>
<p>I've created a website where you can test this functionality at <a target="_blank" href="https://nathansebhastian.github.io/js-geolocation-api/">https://nathansebhastian.github.io/js-geolocation-api/</a></p>
<p>Next, let's learn about the <code>watchPosition()</code> method.</p>
<h2 id="heading-how-to-watch-users-position">How to Watch User's Position</h2>
<p>The <code>watchPosition()</code> method will continue watching the device position when called. It will run the <code>success</code> callback function each time the device location changes.</p>
<p>You can call the method as follows:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">success</span>(<span class="hljs-params">position</span>) </span>{
  <span class="hljs-keyword">const</span> { coords } = position;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Latitude data: '</span> + coords.latitude);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Longitude data: '</span> + coords.longitude);
}

navigator.geolocation.watchPosition(success);
</code></pre>
<p>The <code>watchPosition()</code> method returns an ID number that tracks the watcher. If you want to stop the watcher from sending location data, you need to call the <code>clearWatch()</code> method and pass the ID number:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">success</span>(<span class="hljs-params">position</span>) </span>{
  <span class="hljs-keyword">const</span> { coords } = position;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Latitude data: '</span> + coords.latitude);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Longitude data: '</span> + coords.longitude);
}

<span class="hljs-comment">// Store the ID number in a variable</span>
<span class="hljs-keyword">const</span> watcherID = navigator.geolocation.watchPosition(success);

<span class="hljs-comment">// Stop the watcher</span>
navigator.geolocation.clearWatch(watcherID);
</code></pre>
<p>And that's all there is to the <code>watchPosition()</code> method.</p>
<h3 id="heading-how-to-add-the-options-object">How to Add the Options Object</h3>
<p>Next, let's take a look at the optional <code>options</code> object that you can pass to <code>getCurrentPosition()</code> and <code>watchPosition()</code> methods.</p>
<p>The <code>options</code> object allows you to customize the behavior of the methods. There are three options you can set:</p>
<ul>
<li><code>enableHighAccuracy</code>: a Boolean value that instructs the method to provide a more accurate position. This will increase power consumption. The default value is <code>false</code>.</li>
<li><code>timeout</code>: a number value representing how long the method waits for a response. The default value is <code>Infinity</code>, which means the method will wait until a location is available.</li>
<li><code>maximumAge</code>: a number value representing how long the Geolocation API can send the previous location data. The default value is <code>0</code>, so the API always returns the latest location. If set to <code>Infinity</code>, then the API will always return the first location data retrieved.</li>
</ul>
<p>You can use the options object when calling the <code>geolocation</code> methods. </p>
<p>For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> options = {
  <span class="hljs-attr">enableHighAccuracy</span>: <span class="hljs-literal">true</span>, <span class="hljs-comment">// enable high accuracy</span>
  <span class="hljs-attr">timeout</span>: <span class="hljs-number">300000</span>, <span class="hljs-comment">// wait for 5 minutes</span>
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">success</span>(<span class="hljs-params">position</span>) </span>{
  <span class="hljs-built_in">console</span>.log(position);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">error</span>(<span class="hljs-params">error</span>) </span>{
  <span class="hljs-built_in">console</span>.log(error);
}

<span class="hljs-comment">// Run the getCurrentPosition() method with custom options</span>
navigator.geolocation.getCurrentPosition(
  success,
  error,
  options
);
</code></pre>
<p>In the code above, the <code>getCurrentPosition()</code> method will use high accuracy mode, and it will wait for 5 minutes for a response from the device.</p>
<h2 id="heading-summary">Summary</h2>
<p>The Geolocation API is a standard JavaScript API that allows a web application to access user location data.</p>
<p>Using the Geolocation data, you can provide services or content relevant to the user's location, such as the nearest public transport or hospital.</p>
<p>If you enjoyed this article and want to learn more from me, I recommend you check out my new book <em><a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript">Beginning Modern JavaScript</a></em>.</p>
<p><a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="Beginning Modern JavaScript" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy for beginners and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide to help you understand how to use JavaScript to create a dynamic web application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>See you in other articles!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Fetch API For Beginners – Explained With Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ The Fetch API is a JavaScript function that you can use to send a request to any Web API URL and get a response. In this article, I'm going to show you how to make HTTP requests to external APIs using the JavaScript Fetch API. You're going to learn h... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-fetch-api-for-beginners/</link>
                <guid isPermaLink="false">66bd917b6d46d5e73b73e91f</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Fri, 23 Feb 2024 12:14:53 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/javascript-fetch-cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The Fetch API is a JavaScript function that you can use to send a request to any Web API URL and get a response.</p>
<p>In this article, I'm going to show you how to make HTTP requests to external APIs using the JavaScript Fetch API. You're going to learn how to create GET, POST, PUT/PATCH, and DELETE requests using the Fetch API.</p>
<p>To get the most out of this article, you need to have a good understanding of JavaScript promises. You can read my <a target="_blank" href="https://www.freecodecamp.org/news/javascript-promise-object-explained/">JavaScript Promises</a> article if you need a refresher.</p>
<ul>
<li><a class="post-section-overview" href="#heading-how-the-fetch-api-works">How the Fetch API Works</a></li>
<li><a class="post-section-overview" href="#heading-how-to-send-a-get-request-using-the-fetch-api">How to Send a GET Request</a></li>
<li><a class="post-section-overview" href="#heading-how-to-send-a-post-request-using-the-fetch-api">How to Send a POST Request</a></li>
<li><a class="post-section-overview" href="#heading-how-to-send-a-put-request">How to Send a PUT Request</a></li>
<li><a class="post-section-overview" href="#heading-how-to-send-a-patch-request">How to Send a PATCH Request</a></li>
<li><a class="post-section-overview" href="#heading-how-to-send-a-delete-request">How to Send a DELETE Request</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-asyncawait-with-the-fetch-api">How to Use Async/Await With the Fetch API</a></li>
<li><a class="post-section-overview" href="#heading-run-code-example">Run Code Examples</a></li>
<li><a class="post-section-overview" href="#heading-summary">Summary</a></li>
</ul>
<p>Let's get started!</p>
<h2 id="heading-how-the-fetch-api-works">How the Fetch API Works</h2>
<p>To send a request similar to that of an HTML form, you only need to pass the URL where you want to send the data to as an argument to the <code>fetch()</code> function:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'&lt;Your URL&gt;'</span>, {})
</code></pre>
<p>The <code>fetch()</code> function accepts two parameters:</p>
<ol>
<li>The URL to send the request to (this is a required parameter).</li>
<li>The options to set in the request. You can set the request method here (this is an optional parameter).</li>
</ol>
<p>Under the hood, the <code>fetch()</code> function returns a <code>Promise</code>, so you need to add the <code>.then()</code> and <code>.catch()</code> methods.</p>
<p>When the request returns a response, the <code>then()</code> method will be called. If the request returns an error, then the <code>catch()</code> method will be executed:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'&lt;Your URL&gt;'</span>, {})
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
    <span class="hljs-comment">// Handle Fetch response here.</span>
  })
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
    <span class="hljs-comment">// If there's an error, handle it here</span>
  })
</code></pre>
<p>Inside the <code>.then()</code> and <code>.catch()</code> methods, you pass a callback function to execute when the respective methods are called. </p>
<p>The <code>.catch()</code> method can be omitted from Fetch API. It's used only when Fetch can't make a request to the API, such as no network connection or the URL not found.</p>
<h2 id="heading-how-to-send-a-get-request-using-the-fetch-api">How to Send a GET Request Using the Fetch API</h2>
<p>The GET request is an HTTP request used to ask for specific data from an API, such as when you need </p>
<p>In the following example, we're going to hit a dummy URL located at https://jsonplaceholder.typicode.com to request for a user registered on the site:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(error));
</code></pre>
<p>The code above will give the following response:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/fetch-readable-stream.png" alt="Image" width="600" height="400" loading="lazy">
<em>Fetch Request Response</em></p>
<p>Here, you can see that the body property contains a <code>ReadableStream</code>. To use the <code>ReadableStream</code> in our JavaScript application, we need to convert it to call the <code>json()</code> method:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
</code></pre>
<p>The <code>json()</code> method converts the <code>ReadableStream</code> into a JavaScript object. The <code>data</code> variable above will be printed as follows:</p>
<pre><code class="lang-js">{
  <span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>,
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Leanne Graham"</span>,
  <span class="hljs-string">"username"</span>: <span class="hljs-string">"Bret"</span>,
  <span class="hljs-string">"email"</span>: <span class="hljs-string">"Sincere@april.biz"</span>,
  <span class="hljs-string">"address"</span>: {
    <span class="hljs-string">"street"</span>: <span class="hljs-string">"Kulas Light"</span>,
    <span class="hljs-string">"suite"</span>: <span class="hljs-string">"Apt. 556"</span>,
    <span class="hljs-string">"city"</span>: <span class="hljs-string">"Gwenborough"</span>,
    <span class="hljs-string">"zipcode"</span>: <span class="hljs-string">"92998-3874"</span>,
    <span class="hljs-string">"geo"</span>: {
      <span class="hljs-string">"lat"</span>: <span class="hljs-string">"-37.3159"</span>,
      <span class="hljs-string">"lng"</span>: <span class="hljs-string">"81.1496"</span>
    }
  },
  <span class="hljs-string">"phone"</span>: <span class="hljs-string">"1-770-736-8031 x56442"</span>,
  <span class="hljs-string">"website"</span>: <span class="hljs-string">"hildegard.org"</span>,
  <span class="hljs-string">"company"</span>: {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"Romaguera-Crona"</span>,
    <span class="hljs-string">"catchPhrase"</span>: <span class="hljs-string">"Multi-layered client-server neural-net"</span>,
    <span class="hljs-string">"bs"</span>: <span class="hljs-string">"harness real-time e-markets"</span>
  }
}
</code></pre>
<p>Now that you have the <code>data</code> object, you can use this value in any way you want. For example, if you want to display the user name and email in HTML, here's how you do it:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">id</span>=<span class="hljs-string">'user-name'</span>&gt;</span>Waiting for data<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">id</span>=<span class="hljs-string">'user-email'</span>&gt;</span>Waiting for data<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</span>)
      .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
      .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
        <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#user-name'</span>).textContent = data.name
        <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#user-email'</span>).textContent = data.email
      })
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>In the above code, the Fetch API will run as soon as the browser loads the HTML document.</p>
<p>After processing the <code>response</code> into a <code>data</code> object, JavaScript will change the text of the <code>&lt;h1&gt;</code> and <code>&lt;h2&gt;</code> elements above to reflect the <code>name</code> and <code>email</code> of the user.</p>
<p>If you run the code above, you'll get the following output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/fetch-get-response.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Fetch Request Output Displayed in the Browser</em></p>
<p>And that's how you send a GET request using Fetch and display the returned data in HTML.</p>
<p>Note that depending on the request you are asking for, an API might return a different type of data. </p>
<p>In this example, the typicode API sends back an object, but you might also get an array when you request more than one unit of data.</p>
<p>If you access the URL at <a target="_blank" href="https://jsonplaceholder.typicode.com/users">https://jsonplaceholder.typicode.com/users</a>, you'll see that the API respond with an array of objects. </p>
<p>To handle an array of objects, you can iterate over the array and show the data in HTML as follows:</p>
<pre><code class="lang-js"><span class="hljs-comment">// example</span>
</code></pre>
<p>You need to know the data type returned by the API to handle it correctly.</p>
<h2 id="heading-how-to-send-a-post-request-using-the-fetch-api">How to Send a POST Request Using the Fetch API</h2>
<p>If you want to send a POST request instead of a GET request, you need to define the second argument when calling the function, which is the option object.</p>
<p>Inside the option object, define a <code>method</code> property as follows:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>, <span class="hljs-comment">// Set method here</span>
})
.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
.then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
</code></pre>
<p>When you send a POST method, you need to set the request header and body properties to ensure a smooth process.</p>
<p>For the header, you need to add the <code>Content-Type</code> property and set it to <code>application/json</code>.</p>
<p>The data you want to send should be put inside the <code>body</code> property in a JSON format. See the example below:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Nathan Sebhastian'</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">'ns@mail.com'</span>
  }),
}).then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
</code></pre>
<p>In the example above, we sent a POST request to create a new user. In the <code>body</code> property, a regular JavaScript object was converted into a JSON string by calling the <code>JSON.stringify()</code> method.</p>
<p>JSON is one of the formats computers use to communicate with each other on the internet.</p>
<p>The response from the typicode.com API would be similar as follows:</p>
<pre><code class="lang-js">{
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"Nathan Sebhastian"</span>,
  <span class="hljs-string">"email"</span>: <span class="hljs-string">"ns@mail.com"</span>,
  <span class="hljs-string">"id"</span>: <span class="hljs-number">11</span>
}
</code></pre>
<p>This means that we successfully created a new user. Since typicode.com is a fake API, the user won't really be added, but it will pretend as if it was.</p>
<h2 id="heading-how-to-send-a-put-request">How to Send a PUT Request</h2>
<p>A PUT request is used to create a new resource or update an existing one.</p>
<p>For example, if you want to update an existing user <code>name</code> and <code>email</code> data. You can use a PUT request to do so:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'PUT'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Nathan Sebhastian'</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">'nathan@mail.com'</span>
  }),
}).then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
</code></pre>
<p>The request above will receive the following response:</p>
<pre><code class="lang-js">{
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"Nathan Sebhastian"</span>,
    <span class="hljs-string">"email"</span>: <span class="hljs-string">"nathan@mail.com"</span>,
    <span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>
}
</code></pre>
<p>Because user data with an <code>id</code> value of 1 already exists, the PUT request above updates that data.</p>
<p>Next, let's look at the PATCH request.</p>
<h2 id="heading-how-to-send-a-patch-request">How to Send a PATCH Request</h2>
<p>The PATCH request is sent when you need to update an existing request. </p>
<p>For example, if you want to change the <code>name</code> and <code>username</code> data from an existing user.</p>
<p>Here's an example of sending a PATCH request to typicode.com:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'PATCH'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({ 
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Nathan Sebhastian'</span>,
    <span class="hljs-attr">username</span>: <span class="hljs-string">'nsebhastian'</span>
  }),
}).then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
</code></pre>
<p>The request above will give the following response:</p>
<pre><code class="lang-js">{
    <span class="hljs-string">"id"</span>: <span class="hljs-number">1</span>,
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"Nathan Sebhastian"</span>,
    <span class="hljs-string">"username"</span>: <span class="hljs-string">"nsebhastian"</span>,
    <span class="hljs-string">"email"</span>: <span class="hljs-string">"Sincere@april.biz"</span>,
    <span class="hljs-comment">// ... the rest of user data</span>
}
</code></pre>
<p>Above, you can see that the <code>name</code> and <code>username</code> property values are updated using the body of the PATCH request.</p>
<h2 id="heading-how-to-send-a-delete-request">How to Send a DELETE Request</h2>
<p>The DELETE request is used when you want to request that a resource be removed permanently from the server.</p>
<p>To run a DELETE request with Fetch, you only need to specify the URL for the resource to delete and the <code>method: 'DELETE'</code> property as follows:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'DELETE'</span>,
}).then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
</code></pre>
<p>The request above will delete a user data that has an id value of 1.</p>
<p>The API might respond with some message to confirm that the resource has been removed. But since typicode.com is a dummy API, it will send back an empty JavaScript Object <code>{}</code> .</p>
<h2 id="heading-how-to-use-asyncawait-with-the-fetch-api">How to Use Async/Await With the Fetch API</h2>
<p>Since Fetch returns a <code>Promise</code> object, this means that you can also use the <code>async</code>/<code>await</code> syntax to replace the <code>.then()</code> and <code>.catch()</code> methods.</p>
<p>Here's an example of sending a GET request using Fetch in async/await syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">try</span> {
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/users/1'</span>);
  <span class="hljs-keyword">const</span> json = <span class="hljs-keyword">await</span> response.json();
  <span class="hljs-built_in">console</span>.log(json);
} <span class="hljs-keyword">catch</span> (error) {
  <span class="hljs-built_in">console</span>.log(error);
}
</code></pre>
<p>Handling a Fetch response using <code>async</code>/<code>await</code> looks cleaner because you don't have to use the <code>.then()</code> and <code>.catch()</code> callbacks.</p>
<p>If you need a refresher on async/await, you can read my <a target="_blank" href="https://www.freecodecamp.org/news/javascript-async-await/">JavaScript Async/Await</a> article.</p>
<h2 id="heading-run-code-example">Run Code Example</h2>
<p>I've also created an example website that shows you how to run these 5 HTTP request protocols at <a target="_blank" href="https://nathansebhastian.github.io/js-fetch-api/">https://nathansebhastian.github.io/js-fetch-api/</a></p>
<p>Check it out and study the returned <code>data</code> object. To know what API requests you can send to a specific API, you need to look at the documentation of that API project.</p>
<h2 id="heading-summary">Summary</h2>
<p>The Fetch API allows you to access APIs and perform a network request using standard request methods such as GET, POST, PUT, PATCH, and DELETE.</p>
<p>The Fetch API returns a promise, so you need to chain the function call with <code>.then()</code> and <code>.catch()</code> methods, or use the async/await syntax.</p>
<p>And that's how the Fetch API works! If you enjoyed this article, you might want to check out my <a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript"><em>Beginning Modern JavaScript</em></a> book to level up your JavaScript skill:</p>
<p><a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="Beginning Modern JavaScript" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy for beginners and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic web application.</p>
<p>Here's my promise: You will actually feel like you understand what you're doing with JavaScript.</p>
<p>See you in other articles!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use the JavaScript Map and Set Objects – Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Map and Set are two JavaScript data structures you can use to store a collection of values, similar to Objects and Arrays. They are specialized data structures that can help you store and manipulate related values.  In this tutorial, we will see how ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-map-and-set-objects-explained/</link>
                <guid isPermaLink="false">66bd91812fbe28509b2d6ebe</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Wed, 21 Feb 2024 21:39:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/javascript-mat-and-set-objects-introduction.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Map and Set are two JavaScript data structures you can use to store a collection of values, similar to Objects and Arrays. They are specialized data structures that can help you store and manipulate related values. </p>
<p>In this tutorial, we will see how Map and Set work in detail and when to use them. We will also explore the Set object composition methods that were recently added to the JavaScript standard.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
  <li><a href="#the-map-object-explained">The Map Object Explained</a></li>
  <ul>
    <li><a href="#how-to-create-a-map-object">How to Create a Map Object</a></li>
    <li>
      <a href="#map-object-methods-and-properties">Map Object Methods and Properties</a>
    </li>
    <li>
      <a href="#other-ways-to-create-a-map-object">Other Ways to Create a Map Object</a>
    </li>
    <li>
      <a href="#iterate-over-map-object-data">Iterate Over Map Object Data</a>
    </li>
    <li>
      <a href="#when-to-use-the-map-object">When to Use the Map Object</a>
    </li>
  </ul>
  <li><a href="#set-object-explained">Set Object Explained</a></li>
  <ul>
    <li>
      <a href="#how-to-create-a-set-object">How to create a Set Object</a>
    </li>
    <li>
      <a href="#set-object-methods-and-properties">Set Object Methods and Properties</a>
    </li>
    <li><a href="#set-composition-methods">Set Composition Methods</a></li>
    <li><a href="#iterate-over-a-set-object">Iterate Over a Set Object</a></li>
    <li>
      <a href="#when-to-use-the-set-object">When to Use the Set Object</a>
    </li>
  </ul>
  <li><a href="#conclusion">Conclusion</a></li>
</ul>


<h2 id="heading-the-map-object-explained">The Map Object Explained</h2>
<p>The <code>Map</code> object stores data in a key/value pair structure, just like an Object. The main differences between a regular object and a <code>Map</code> are:</p>
<ul>
<li>A <code>Map</code> can have any type of data as the key value</li>
<li>A <code>Map</code> maintains the order of data added to the object</li>
</ul>
<h3 id="heading-how-to-create-a-map-object">How to Create a Map Object</h3>
<p>To create a <code>Map</code> object, you can call the <code>Map()</code> constructor as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();
</code></pre>
<p>The code above creates a new empty <code>Map</code> object.</p>
<h3 id="heading-map-object-methods-and-properties">Map Object Methods and Properties</h3>
<p>A <code>Map</code> object has the following methods and properties:</p>
<ul>
<li><code>set(key, value)</code> – Adds a key/value pair to a Map</li>
<li><code>get(key)</code> – Retrieves a value from a Map (returns <code>undefined</code> if key doesn't exist)</li>
<li><code>has(key)</code> – Checks if a Map has a specific key</li>
<li><code>delete(key)</code> – Removes a specific key from a Map</li>
<li><code>clear()</code> – Removes all items from a Map</li>
<li><code>keys()</code> – Returns all keys in a Map</li>
<li><code>values()</code> – Returns all values in a Map</li>
<li><code>entries()</code> – Returns all keys and values in a Map</li>
<li><code>size</code> – Returns the number of items in Map</li>
</ul>
<p>To insert data into the <code>Map</code> object, you can use the <code>set()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

myMap.set(<span class="hljs-number">1</span>, <span class="hljs-string">'Jack'</span>);
myMap.set(<span class="hljs-number">2</span>, <span class="hljs-string">'Jill'</span>);
myMap.set(<span class="hljs-string">'animal'</span>, <span class="hljs-string">'Elephant'</span>);
</code></pre>
<p>The code above creates a <code>Map</code> object with 3 entries as follows:</p>
<pre><code class="lang-txt">Map(3)
0: {1 =&gt; "Jack"}
1: {2 =&gt; "Jill"}
2: {"animal" =&gt; "Elephant"}
</code></pre>
<p>To retrieve a value from the <code>Map</code> object, you need to use the <code>get()</code> method and pass the key as its argument:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(myMap.get(<span class="hljs-number">1</span>)); <span class="hljs-comment">// Jack</span>

<span class="hljs-built_in">console</span>.log(myMap.get(<span class="hljs-string">'animal'</span>)); <span class="hljs-comment">// Elephant</span>
</code></pre>
<p> To see how many key/value pairs a <code>Map</code> has, you can access the <code>size</code> property:</p>
<pre><code class="lang-js">myMap.size; <span class="hljs-comment">// 3</span>
</code></pre>
<p>To see if a certain key exists in a <code>Map</code> object, you can use the <code>has()</code> method. See the example below:</p>
<pre><code class="lang-js">myMap.has(<span class="hljs-number">1</span>); <span class="hljs-comment">// true</span>

myMap.has(<span class="hljs-number">10</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p>To remove a key/value pair from a <code>Map</code> object, you can use the <code>delete()</code> method and pass the key of the pair you want to remove as follows:</p>
<pre><code class="lang-js">myMap.delete(<span class="hljs-number">1</span>);

<span class="hljs-built_in">console</span>.log(myMap);
<span class="hljs-comment">// 0: {2 =&gt; "Jill"}</span>
<span class="hljs-comment">// 1: {"animal" =&gt; "Elephant"}</span>
</code></pre>
<p>If you want to remove all key/value pairs, you can use the <code>clear()</code> method instead:</p>
<pre><code class="lang-js">myMap.clear();

<span class="hljs-built_in">console</span>.log(myMap); <span class="hljs-comment">// Map(0) {size: 0}</span>
</code></pre>
<h3 id="heading-other-ways-to-create-a-map-object">Other Ways to Create a Map Object</h3>
<p>You can also create a <code>Map</code> object from an Array as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([
  [<span class="hljs-number">1</span>, <span class="hljs-string">'Jack'</span>],
  [<span class="hljs-number">2</span>, <span class="hljs-string">'Jill'</span>],
  [<span class="hljs-string">'animal'</span>, <span class="hljs-string">'Elephant'</span>],
]);
</code></pre>
<p>When creating a <code>Map</code> from an Array, you need to create a two-dimensional array and specify two elements in each array. </p>
<p>The first element will be the key, the second element will be the value. Any extra value in the array will be ignored.</p>
<p>In the example below, the value 'Johnson' from the first array will be ignored by the <code>Map()</code> constructor:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([
  [<span class="hljs-number">1</span>, <span class="hljs-string">'Jack'</span>, <span class="hljs-string">'Johnson'</span>], <span class="hljs-comment">// the value 'Johnson' is ignored</span>
  [<span class="hljs-number">2</span>, <span class="hljs-string">'Jill'</span>],
  [<span class="hljs-string">'animal'</span>, <span class="hljs-string">'Elephant'</span>],
]);
</code></pre>
<p>Because you can create a <code>Map</code> object from an array, you can also create one from an object. You need to transform the object into an array first using the <code>Object.entries()</code> method.</p>
<p>The following example shows how to use an object to create a <code>Map</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> person = {
    <span class="hljs-string">'name'</span>: <span class="hljs-string">'Jack'</span>,
    <span class="hljs-string">'age'</span>: <span class="hljs-number">20</span>,
}

<span class="hljs-keyword">const</span> myMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>(<span class="hljs-built_in">Object</span>.entries(person));

<span class="hljs-built_in">console</span>.log(myMap); <span class="hljs-comment">// Map(2) { 'name' =&gt; 'Jack', 'age' =&gt; 20 }</span>
</code></pre>
<h3 id="heading-iterate-over-map-object-data">Iterate Over Map Object Data</h3>
<p>To iterate over a <code>Map</code> object data, you can use either the <code>forEach()</code> method or the <code>for .. of</code> loop:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([
  [<span class="hljs-number">1</span>, <span class="hljs-string">'Jack'</span>],
  [<span class="hljs-number">2</span>, <span class="hljs-string">'Jill'</span>],
  [<span class="hljs-string">'animal'</span>, <span class="hljs-string">'Elephant'</span>],
]);

<span class="hljs-comment">// iterate using the forEach() method</span>
myMap.forEach(<span class="hljs-function">(<span class="hljs-params">value, key</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${key}</span>: <span class="hljs-subst">${value}</span>`</span>);
});

<span class="hljs-comment">// or using the for .. of loop</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> [key, value] <span class="hljs-keyword">of</span> myMap) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${key}</span>: <span class="hljs-subst">${value}</span>`</span>);
}
</code></pre>
<p>Both methods give the same output:</p>
<pre><code class="lang-txt">1: Jack
2: Jill
animal: Elephant
</code></pre>
<h3 id="heading-when-to-use-the-map-object">When to Use the Map Object</h3>
<p>You can think of the <code>Map</code> object as an upgraded version of the regular Object. It can use any type of data as the key value, while an object can only use string values as keys.</p>
<p>Under the hood, the <code>Map</code> object performs better when you need to add and remove keys, so you might consider using it when your data changes frequently.</p>
<p>Also, the Map object has many useful methods for data manipulation, such as <code>has()</code> to see if the Map contains a specific key, <code>keys()</code> to get all keys defined in the <code>Map</code>, <code>values</code> to get all values, and <code>entries()</code> to get all key/value pairs.</p>
<p>But if you only want to create an object without further manipulation, then you don't need to use the <code>Map</code> object. </p>
<p>One example is when you send a network request using the <code>fetch()</code> method. You would create an object and convert it into a JSON string, so using a <code>Map</code> object won't give any benefit.</p>
<h2 id="heading-set-object-explained">Set Object Explained</h2>
<p>The <code>Set</code> object allows you to store a collection of elements, just like an Array. The differences between a <code>Set</code> and an array are:</p>
<ul>
<li>A <code>Set</code> requires all elements to be unique</li>
<li>A <code>Set</code> has fewer methods for data manipulation</li>
</ul>
<h3 id="heading-how-to-create-a-set-object">How to Create a Set Object</h3>
<p>To create a new <code>Set</code> object, you need to call the <code>Set()</code> constructor as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mySet = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>();
</code></pre>
<p>The code above will create a new empty set.</p>
<h3 id="heading-set-object-methods-and-properties">Set Object Methods and Properties</h3>
<p>A <code>Set</code> object has the following methods and properties:</p>
<ul>
<li><code>add(value)</code> – Adds a value to a Set</li>
<li><code>has(value)</code> – Checks if a Set contains a specific value</li>
<li><code>delete(value)</code> – Removes a specific value from a Set</li>
<li><code>clear()</code> – Removes all items from a Set</li>
<li><code>keys()</code> – Returns all values in a Set</li>
<li><code>values()</code> – Returns all values in a Set</li>
<li><code>entries()</code> – Returns all values in a Set as <code>[value, value]</code> array</li>
<li><code>size</code> – Returns the number of items in Set</li>
</ul>
<p>Note that the <code>keys()</code> and <code>values()</code> methods in a Set object return the same output.</p>
<p>There's also the <code>entries()</code> method which returns an array as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mySet = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-string">'Jack'</span>, <span class="hljs-string">'Jill'</span>, <span class="hljs-string">'John'</span>]);

<span class="hljs-built_in">console</span>.log(mySet.entries());
</code></pre>
<p>Output:</p>
<pre><code class="lang-txt">[Set Entries] {
  [ 'Jack', 'Jack' ],
  [ 'Jill', 'Jill' ],
  [ 'John', 'John' ]
}
</code></pre>
<p>Notice how the values are repeated once in each array above. The <code>entries()</code> method is created to make <code>Set</code> similar to the <code>Map</code> object, but you probably don't need it.</p>
<p>There are extra methods that you can use to interact with another <code>Set</code> object. We'll discuss them in the next section.</p>
<p>To add an element to the Set object, you can use the add method:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mySet = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>();

mySet.add(<span class="hljs-number">1</span>);
mySet.add(<span class="hljs-number">2</span>);
mySet.add(<span class="hljs-number">3</span>);

<span class="hljs-built_in">console</span>.log(mySet); <span class="hljs-comment">// [1, 2, 3]</span>
</code></pre>
<p>To get all values stored in a <code>Set</code>, call the <code>values()</code> method:</p>
<pre><code class="lang-js">mySet.values(); <span class="hljs-comment">// [Set Iterator] { 'Jack', 'Jill', 'John' }</span>
</code></pre>
<p>To check if the <code>Set</code> has a specific value, use the <code>has()</code> method:</p>
<pre><code class="lang-js">mySet.has(<span class="hljs-string">'Jack'</span>); <span class="hljs-comment">// true</span>

mySet.has(<span class="hljs-string">'Michael'</span>); <span class="hljs-comment">// false</span>
</code></pre>
<p>To remove a single value, call the <code>delete()</code> method. To remove all values, use the <code>clear()</code> method:</p>
<pre><code class="lang-js">mySet.delete(<span class="hljs-string">'Jill'</span>);

mySet.clear();
</code></pre>
<h3 id="heading-set-composition-methods">Set Composition Methods</h3>
<p>Aside from the regular methods above, <code>Set</code> also has composition methods that you can use to perform various set theory operations such as difference, union, and intersection.</p>
<p>The following table is from <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set#set_composition">MDN Set documentation</a>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/set-composition-methods.png" alt="Image" width="600" height="400" loading="lazy">
<em>A List of Set Composition Methods</em></p>
<p>For example, you can get a set containing the differences between two other sets as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> setA = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]);

<span class="hljs-keyword">const</span> setB = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>]);

<span class="hljs-keyword">const</span> diffsA = setA.difference(setB); <span class="hljs-comment">// Set(3) {1, 2, 3}</span>
<span class="hljs-keyword">const</span> diffsB = setB.difference(setA); <span class="hljs-comment">// Set(3) {6, 7, 8}</span>
</code></pre>
<p>Here, the <code>setA.difference(setB)</code> returns a <code>Set</code> containing values unique to the <code>setA</code> object.</p>
<p>The opposite values are returned when you run <code>setB.difference(setA)</code> method.</p>
<p>Note that these methods are new additions to the JavaScript standard, and as of this writing, only Safari 17 and Chrome 122 support these methods.</p>
<p>Most likely, these methods will be included in Node.js soon.</p>
<h3 id="heading-iterate-over-a-set-object">Iterate Over a Set Object</h3>
<p>To iterate over a <code>Set</code> object, you can use either the <code>forEach()</code> method or the <code>for .. of</code> loop:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mySet = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-string">'Jack'</span>, <span class="hljs-string">'Jill'</span>, <span class="hljs-string">'John'</span>]);

<span class="hljs-comment">// iterate using the forEach() method</span>
mySet.forEach(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(value);
});

<span class="hljs-comment">// or using the for .. of loop</span>

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> value <span class="hljs-keyword">of</span> mySet) {
  <span class="hljs-built_in">console</span>.log(value);
}
</code></pre>
<p>Output:</p>
<pre><code class="lang-txt">Jack
Jill
John
</code></pre>
<h3 id="heading-when-to-use-the-set-object">When to Use the Set Object</h3>
<p>You can think of the <code>Set</code> object as the alternative version of the regular Array.</p>
<p>Because a <code>Set</code> object ignores duplicate values, you can use this object to purge duplicates from an Array, then turn the <code>Set</code> object back to an Array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myArray = [<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">3</span>];

<span class="hljs-keyword">const</span> uniqueArray = [...new <span class="hljs-built_in">Set</span>(myArray)];

<span class="hljs-built_in">console</span>.log(uniqueArray); <span class="hljs-comment">// [ 1, 2, 3 ]</span>
</code></pre>
<p>Another reason you may want to use a <code>Set</code> is when you need to compose multiple set objects using the composition methods, such as <code>union()</code> and <code>difference()</code>. These methods are not available in an Array.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you've learned how the Map and Set objects work and when to use them in your code.</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript">here</a>.</p>
<p><a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy for beginners and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic web application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>See you later!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Web Storage API – How to Store Data on the Browser ]]>
                </title>
                <description>
                    <![CDATA[ The Web Storage API is a set of APIs exposed by the browser so that you can store data in the browser. The data stored in the Web Storage use the key/value pair format, and both data will be stored as strings. There are two types of storage introduce... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/web-storage-api-how-to-store-data-on-the-browser/</link>
                <guid isPermaLink="false">66bd91a827629f4c5e1893bc</guid>
                
                    <category>
                        <![CDATA[ browser ]]>
                    </category>
                
                    <category>
                        <![CDATA[ data ]]>
                    </category>
                
                    <category>
                        <![CDATA[ storage ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Fri, 12 Jan 2024 17:43:34 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/web-storage-api-feature-image.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The Web Storage API is a set of APIs exposed by the browser so that you can store data in the browser.</p>
<p>The data stored in the Web Storage use the key/value pair format, and both data will be stored as strings.</p>
<p>There are two types of storage introduced in the Web Storage API: Local Storage and Session Storage.</p>
<p>In this article, I’m going to show you how to use the Web Storage API and why it’s useful for web developers.</p>
<h2 id="heading-how-the-web-storage-api-works">How the Web Storage API Works</h2>
<p>The Web Storage API exposes a set of objects and methods that you can use to store data in the browser. The data you store in Web Storage is private, which means no other website can access it.</p>
<p>In Google Chrome, you can view Web Storage by opening the developer tools window and going to the Application tab as shown below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/web-storage-location-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>The web storage location in Google Chrome</em></p>
<p>In the picture above, you can see that the Storage menu also has other storage types like Indexed DB, Web SQL, and cookies. The Web SQL standard has been deprecated, and IndexedDB is rarely used because it’s too complex. Any data you store in IndexedDB might better be stored on the server.</p>
<p>As for cookies, it’s a more traditional mechanism of storing data that only allows you to store a maximum of 4 KB of data. By contrast, the Local Storage capacity is 10 MB and the session storage has 5 MB capacity.</p>
<p>This is why we’re going to focus only on Local Storage and Session Storage in this article.</p>
<h2 id="heading-local-storage-and-session-storage-explained">Local Storage and Session Storage Explained</h2>
<p>Local Storage and Session Storage are the two standard mechanisms supported by the Web Storage API.</p>
<p>Web storage is domain specific, meaning data stored under one domain (netflix.com) can’t be accessed by another domain (www.netflix.com or members.netflix.com)</p>
<p>Web storage is also protocol specific. This means the data you store in a <code>http://</code> site won’t be available under the <code>https://</code> site.</p>
<p>The main difference between Local and Session Storage is that Local Storage will store your data forever. If you want to remove the data, you need to use the available method or clear it manually from the Applications tab.</p>
<p>By contrast, the data stored in session storage is only available during the page session. When you close the browser or the tab, the session storage for that specific tab is removed.</p>
<p>Both Local and Session Storage can be accessed through the <code>window</code> object under the variables <code>localStorage</code> and <code>sesionStorage</code>, respectively. Let’s see the methods and properties of these storage types next.</p>
<h3 id="heading-methods-and-properties-of-local-and-session-storage">Methods and Properties of Local and Session Storage</h3>
<p>Both Local and Session Storage have the same methods and properties. To set a new key/value pair in the Local Storage, you can use the <code>setItem()</code> method of the <code>localStorage</code> object:</p>
<pre><code class="lang-js"><span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'firstName'</span>, <span class="hljs-string">'Nathan'</span>);
</code></pre>
<p>If you look into the Local Storage menu in the browser, you should see the data above saved into the storage as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/localstorage-setitem.png" alt="Image" width="600" height="400" loading="lazy">
<em>Storing a key/value pair in Local Storage</em></p>
<p>The key you used in <code>localStorage</code> must be unique. If you set another data with a key that already exists, then the <code>setItem()</code> method will replace the previous value with the new one.</p>
<p>To get the value out of local storage, you need to call the <code>getItem()</code> method and pass the key you used when saving the data. If the key doesn’t exist, then <code>getItem()</code> will return <code>null</code> back:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> firstName = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'firstName'</span>);
<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// Nathan</span>

<span class="hljs-keyword">const</span> lastName = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'lastName'</span>);
<span class="hljs-built_in">console</span>.log(lastName); <span class="hljs-comment">// null</span>
</code></pre>
<p>To remove the data you have in local storage, call the <code>removeItem()</code> method and pass the key pointing to the data you want to remove:</p>
<pre><code class="lang-js"><span class="hljs-built_in">localStorage</span>.removeItem(<span class="hljs-string">'firstName'</span>);
</code></pre>
<p>The <code>removeItem()</code> method will always return <code>undefined</code>. When the data you want to remove doesn’t exist, the method simply does nothing.</p>
<p>If you want to clear the storage, you can use the <code>clear()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-built_in">localStorage</span>.clear();
</code></pre>
<p>The <code>clear()</code> method removes all key/value pairs from the storage object you are accessing.</p>
<h3 id="heading-properties-of-local-and-session-storage">Properties of Local and Session Storage</h3>
<p>Both storage types have only one property, which is the <code>length</code> property that shows the amount of data stored in them.</p>
<pre><code class="lang-js">sessionStorage.setItem(<span class="hljs-string">'firstName'</span>, <span class="hljs-string">'Nathan'</span>);
sessionStorage.setItem(<span class="hljs-string">'lastName'</span>, <span class="hljs-string">'Sebhastian'</span>);

<span class="hljs-built_in">console</span>.log(sessionStorage.length); <span class="hljs-comment">// 2</span>

sessionStorage.clear();
<span class="hljs-built_in">console</span>.log(sessionStorage.length); <span class="hljs-comment">// 0</span>
</code></pre>
<p>And that’s all the methods and properties you can access in <code>localStorage</code> and <code>sessionStorage</code>.</p>
<h2 id="heading-how-to-store-json-strings-in-web-storage-storage">How to Store JSON Strings in Web Storage Storage</h2>
<p>Since Web Storage always stores data as strings, you can store complex data as a JSON string, and then convert that string back into an object when you access it.</p>
<p>For example, suppose I want to store the following information about a user:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">'Nathan'</span>,
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Sebhastian'</span>,
  <span class="hljs-attr">url</span>: <span class="hljs-string">'https://codewithnathan.com'</span>,
};
</code></pre>
<p>At first, I might store the data as a series of key/value pairs like this:</p>
<pre><code class="lang-js"><span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'firstName'</span>, user.firstName);
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'lastName'</span>, user.lastName);
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'url'</span>, user.url);
</code></pre>
<p>But a better way is to convert the JavaScript object into a JSON string, and then store the data under one key as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">'Nathan'</span>,
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Sebhastian'</span>,
  <span class="hljs-attr">url</span>: <span class="hljs-string">'https://codewithnathan.com'</span>,
};

<span class="hljs-keyword">const</span> userData = <span class="hljs-built_in">JSON</span>.stringify(user);

<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'user'</span>, userData);
</code></pre>
<p>Now the local storage will have only one key/value pair with the JSON string as its value. You can open the Applications tab to see this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/store-as-json.png" alt="Image" width="600" height="400" loading="lazy">
<em>Storing a JSON string in Local Storage</em></p>
<p>When you need the data, call the <code>getItem()</code> and <code>JSON.parse()</code> methods as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getUser = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'user'</span>));

<span class="hljs-built_in">console</span>.log(getUser);
<span class="hljs-comment">// {firstName: 'Nathan', lastName: 'Sebhastian', url: 'https://codewithnathan.com'}</span>
</code></pre>
<p>Here, you can see that the data is returned as a regular JavaScript object.</p>
<h2 id="heading-local-storage-vs-session-storage-which-one-to-use">Local Storage vs Session Storage – Which One to Use?</h2>
<p>Based on my experience, <code>localStorage</code> is the preferred Web Storage mechanism because the data will persist as long as you need it to. When you don’t need the data, you can remove it using the <code>removeItem()</code> method.</p>
<p><code>sessionStorage</code> is only used when you need to store temporary data, like tracking whether a popup box has been shown to the user or not.</p>
<p>But this is also open to discussion because you might not want to show a popup every time the user logs into your web application, but only once. In that case, you should use <code>localStorage</code> instead.</p>
<p>My rule of thumb is to use <code>localStorage</code> first, and <code>sessionStorage</code> when the situation needs it.</p>
<h2 id="heading-benefits-of-using-the-web-storage-api">Benefits of Using the Web Storage API</h2>
<p>Now that you know how the Web Storage API works, you can see that there are some benefits of using it:</p>
<ol>
<li>Storing data on the browser reduces the need to make a server request for a piece of information. This can improve the performance of your web applications.</li>
<li>The simple key/value pair format allows you to store user preferences and local settings that should persist between sessions.</li>
<li>The Web Storage API is simple to use, providing only a few methods and one property. It’s simple to set and retrieve data using JavaScript</li>
<li>It has offline support. By storing necessary data locally, the Web Storage enables your web application to work offline.</li>
<li>The Web Storage is also a standardized API, meaning the code you write will work in many different browsers.</li>
</ol>
<p>But of course, not all data should be stored in the Web Storage API. You still need a server database to keep records that are important for your application.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Web Storage is a useful API that allows you to quickly store and retrieve data from the browser. Using Web Storage, you can store the user’s preferences when accessing your application.</p>
<p><code>localStorage</code> allows you to store data forever until it’s removed manually, while <code>sessionStorage</code> will persist as long as the browser or tab is open.</p>
<p>Some benefits of using the Web Storage API include reducing server requests, offline support, and a simple API that’s easy to use. It’s also standardized, so it will work on different browsers.</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript">here</a>.</p>
<p><a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy for beginners and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic web application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>See you later!  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Understanding DOM Events and JavaScript Event Listeners ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript code in the browser uses an event-driven programming pattern. What this means is that when a specific DOM event happens in the browser, a piece of code will be executed as a response to that action. In this article, I will help you see and... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/dom-events-and-javascript-event-listeners/</link>
                <guid isPermaLink="false">66bd9150abf0ccf74f1ce9b2</guid>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Wed, 10 Jan 2024 20:38:04 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/DOM-events-feature-image.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript code in the browser uses an event-driven programming pattern. What this means is that when a specific DOM event happens in the browser, a piece of code will be executed as a response to that action.</p>
<p>In this article, I will help you see and understand how to listen and respond to DOM events using JavaScript.</p>
<p>If you need a refresher on the DOM, I have written an article that explains <a target="_blank" href="https://www.freecodecamp.org/news/introduction-to-the-dom/">what the DOM is and how JavaScript interacts with it</a>.</p>
<h2 id="heading-what-are-dom-events-and-why-are-they-useful">What Are DOM Events and Why Are They Useful?</h2>
<p>DOM events are signals exposed by the browser that you can use to run a piece of JavaScript code.</p>
<p>These DOM events occur when the user interacts with the application we've created, such as clicking a button or typing letters into an input field.</p>
<p>As a web developer, you can instruct JavaScript to listen for a specific event and do something in response to that event.</p>
<p>For example:</p>
<ul>
<li>When <strong>a button</strong> is clicked, do <strong>change the</strong> text <strong>of</strong> a paragraph.</li>
<li>When <strong>a form is submitted</strong>, do <strong>a POST request using the Fetch API.</strong></li>
</ul>
<p>In this article, I will help you see and understand how to listen and respond to DOM events using JavaScript.</p>
<h2 id="heading-how-to-listen-to-dom-events">How to Listen to DOM Events</h2>
<p>To listen for an event, you need to attach an event listener to an element by using the <code>addEventListener()</code> method.</p>
<p>The <code>addEventListener()</code> method accepts two parameters:</p>
<ol>
<li>The event <code>type</code> to listen to</li>
<li>A function to run when the event is triggered</li>
</ol>
<pre><code class="lang-js">Element.addEventListener(type, <span class="hljs-function"><span class="hljs-keyword">function</span>);</span>
</code></pre>
<p>Back to the example, suppose you want to change the text of a paragraph when a <code>button</code> element is clicked. Here’s how you do it:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myParagraph"</span>&gt;</span>This is an example paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"changeText"</span>&gt;</span>Change Text<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#changeText'</span>);

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">newText</span>(<span class="hljs-params">event</span>) </span>{
      <span class="hljs-keyword">const</span> p = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#myParagraph'</span>);
      p.innerText = <span class="hljs-string">'The text has been changed'</span>;
    }

    button.addEventListener(<span class="hljs-string">'click'</span>, newText);
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>To insert JavaScript code into the HTML document, we need to use the <code>script</code> tag as shown above.</p>
<p>The button element is selected using <code>document.querySelector()</code> method, then the method <code>addEventListener()</code> is called on the element. This means you attach an event listener to the button.</p>
<p>First, you specify the <code>type</code> of event to listen to, which is a <code>click</code> event in this case. Next, you specify the function to run when that event happens.</p>
<p>In the code above, the <code>newText</code> function will be executed when the <code>click</code> event is triggered.</p>
<p>The event listener will also send an <code>event</code> object, which carries information about the event that was triggered. That’s why there’s an <code>event</code> parameter in the <code>newText</code> function above.</p>
<p>You can log the event to the console to see its details:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">newText</span>(<span class="hljs-params">event</span>) </span>{
  <span class="hljs-built_in">console</span>.log(event);
}
</code></pre>
<p>If you click on the button again, you will have the following output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/event-log-example-1.png" alt="Event object log" width="600" height="400" loading="lazy">
<em>An example Event object log</em></p>
<p>Depending on what you want to do when an event is triggered, you may need to use the information contained inside the <code>event</code> object.</p>
<p>Here, all we want to do is to change the text of the paragraph, so the <code>event</code> object is not needed. We’ll see an example of using the <code>event</code> object later, when handling the keyboard events.</p>
<p>There are many events you can listen to in the browser. Here are some of the most common events you may need when developing a web application:</p>
<table><tbody><tr><td>Event</td><td>Event is fired</td></tr><tr><td>click</td><td>When you press down and release the primary mouse button. Used to track buttons and clickable elemennts</td></tr><tr><td>mousemove</td><td>When you move the mouse cursor</td></tr><tr><td>mouseover</td><td>When you move the mouse cursor over an element. It's like the CSS hover state</td></tr><tr><td>mouseout</td><td>When your mouse cursor moves outside the boundaries of an element</td></tr><tr><td>dblclick</td><td>When you click twice</td></tr><tr><td>DOMContentLoaded</td><td>When the DOM content is fully loaded</td></tr><tr><td>keydown</td><td>When you press a key on your keyboard</td></tr><tr><td>keyup</td><td>When you release a key on your keyboard</td></tr><tr><td>submit</td><td>When a form is submitted</td></tr></tbody></table>

<p>If you want to read the full list of DOM event types, you can <a target="_blank" href="https://en.wikipedia.org/wiki/DOM_event">visit this page</a>.</p>
<p>The DOM Events are broken into several categories. Here we will just look at two of the most common events you might use in your project: keyboard and mouse events.</p>
<h2 id="heading-keyboard-events">Keyboard Events</h2>
<p>For the keyboard, you can track the <code>keydown</code> and <code>keyup</code> events, which run when you press and release a key, respectively.</p>
<p>To show you an example, run the following code from the console:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'keydown'</span>, <span class="hljs-function"><span class="hljs-params">event</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`A key is pressed: <span class="hljs-subst">${event.key}</span>`</span>);
});

<span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'keyup'</span>, <span class="hljs-function"><span class="hljs-params">event</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`A key is released: <span class="hljs-subst">${event.key}</span>`</span>);
});
</code></pre>
<p>Once you run the code above, press a key on your keyboard slowly, then release it slowly.</p>
<p>You should see a log output as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/keydown-event-1.png" alt="Keyboard events log" width="600" height="400" loading="lazy">
<em>Logging keyup and keydown events</em></p>
<p>Notice how the 'keydown' log appears as soon as you press a key, and the 'keyup' log appears only when you release the key.</p>
<p>The keyboard events are usually attached to the <code>document</code> object instead of a specific element, because the whole website should be able to listen to that event.</p>
<h2 id="heading-mouse-events">Mouse Events</h2>
<p>Aside from keyboard events, the DOM also provides a way to track any mouse events.</p>
<p>The most common mouse events that you can track are:</p>
<ul>
<li><code>mousedown</code> – the mouse button was pressed</li>
<li><code>mouseup</code> – the mouse button was released </li>
<li><code>click</code> – a click event </li>
<li><code>dblclick</code> – a double click event </li>
<li><code>mousemove</code> – when the mouse is moved over the element </li>
<li><code>contextmenu</code> – when the context menu is opened, for example on a right mouse button click</li>
</ul>
<p>Again, you can test these events by adding an event listener directly to the <code>document</code> object:</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'mousedown'</span>, <span class="hljs-function"><span class="hljs-params">event</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The mouse is pressed`</span>);
});

<span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'mouseup'</span>, <span class="hljs-function"><span class="hljs-params">event</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The mouse is released`</span>);
});
</code></pre>
<p>Run the code above, then click anywhere inside the browser. You should see the <code>mousedown</code> and <code>mouseup</code> events logged, respectively.</p>
<h2 id="heading-how-to-remove-event-listeners">How to Remove Event Listeners</h2>
<p>To remove an event listener attached to an element, you need to call the <code>removeEventListener()</code> method, passing the <code>type</code> of the event and the <code>function</code> you passed to the <code>addEventListener()</code> method as follows:</p>
<pre><code class="lang-js">button.removeEventListener(<span class="hljs-string">'click'</span>, newText);
</code></pre>
<p>The above code is enough to remove the 'click' event listener from the <code>button</code> element. Notice how you need to call the <code>removeEventListener()</code> method on the element while also passing the function <code>newText</code> to the method.</p>
<p>To correctly remove an event listener, you need to have a reference to the function attached to the event. If you pass a nameless function to the <code>addEventListener()</code> method, then that event can’t be removed:</p>
<pre><code class="lang-js">button.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">event</span>) </span>{
  alert(<span class="hljs-string">'Button save is clicked'</span>);
});
</code></pre>
<p>Without the function name as in the example above, you won’t be able to remove the event listener.</p>
<h2 id="heading-how-to-listen-to-events-using-html-attributes">How to Listen to Events using HTML Attributes</h2>
<p>Aside from using the <code>addEventListener()</code> method, you can also listen to events by adding the <code>on[eventname]</code> attribute to your HTML elements.</p>
<p>For example, suppose you want to listen to a button click. You can add the <code>onclick</code> attribute to your button as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"handleClick()"</span>&gt;</span>Click Me!<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params">event</span>) </span>{
      alert(<span class="hljs-string">'The button is clicked!'</span>);
    }
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>In the button element above, we add the <code>onclick</code> property and pass the <code>handleClick()</code> function to it. </p>
<p>When we click on the button, the <code>handleClick()</code> function will be executed.</p>
<p>You can also add the <code>onclick</code> attribute using JavaScript as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myBtn"</span>&gt;</span>Click Me!<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-keyword">const</span> myBtn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#myBtn'</span>);
    myBtn.onclick = handleClick;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params">event</span>) </span>{
      alert(<span class="hljs-string">'The button is clicked!'</span>);
    }
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>Here, we assign a reference to the <code>handleClick</code> function to the <code>onclick</code> property using JavaScript.</p>
<p>To remove the onclick attribute, you can assign the property to null:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myBtn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#myBtn'</span>);
myBtn.onclick = <span class="hljs-literal">null</span>;
</code></pre>
<h2 id="heading-which-one-should-you-use">Which One Should You Use?</h2>
<p>As you can see, there are two ways you can listen to DOM events: the <code>addEventListener()</code> method and the <code>on[eventname]</code> HTML attribute. Which one should you use? </p>
<p>The answer is that the <code>addEventListener()</code> method can be used when you need more extensibility, and the <code>on[eventname]</code> can be used when you prefer things to be simple.</p>
<p>When developing web applications, the <code>.html</code> file should only serve as the structure of the page, while the <code>.js</code> file should define any behavior the web application can have.</p>
<p>To make your application easier to maintain and extend, JavaScript should have access to HTML elements, but no HTML elements should be able to execute JavaScript functions. This is why <code>addEventListener()</code> should be the recommended method.</p>
<p>But <code>addEventListener()</code> doesn't come without a cost: you trade extensibility with verbosity, making your code quite cumbersome to read.</p>
<p>When using the <code>on[eventname]</code> attribute, you only need to specify the function name in your HTML element:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"handleClick()"</span>&gt;</span>Click Me!<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params">event</span>) </span>{
      alert(<span class="hljs-string">'The button is clicked!'</span>);
    }
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>But when you use the <code>addEventListener()</code> method, you need to query the element you need, call the method, then specify the event and the callback function to run:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myBtn"</span>&gt;</span>Click Me!<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-keyword">const</span> myBtn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#myBtn'</span>);
    myBtn.addEventListener(<span class="hljs-string">'click'</span>, handleClick);

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params">event</span>) </span>{
      alert(<span class="hljs-string">'The button is clicked!'</span>);
    }
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>As you can see above, there are two additional lines that you don't need to write when you use the <code>on[eventname]</code> attribute. </p>
<p>While it might look insignificant, it will be a serious issue when you work on a large scale application with many HTML and JS files.</p>
<p>In addition, the <code>addEventListener()</code> method also allows you to attach multiple listeners to the same element as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myBtn"</span>&gt;</span>Click Me!<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-keyword">const</span> myBtn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#myBtn'</span>);

    myBtn.addEventListener(<span class="hljs-string">'click'</span>, handleClick);

    myBtn.addEventListener(<span class="hljs-string">'click'</span>, handleClickTwo);

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Run from handleClick function'</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClickTwo</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Run from handleClickTwo function'</span>);
    }
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>When you click on the button above, JavaScript will execute both event listeners.</p>
<p>This is not possible with the <code>onclick</code> property because you can only assign one function as a reference at a time:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myBtn"</span>&gt;</span>Click Me!<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-keyword">const</span> myBtn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#myBtn'</span>);

    myBtn.onclick = handleClick;

    <span class="hljs-comment">// when you assign a new function to onclick,</span>
    <span class="hljs-comment">// the old function is overwritten</span>

    myBtn.onclick = handleClickTwo;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Run from handleClick function'</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClickTwo</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Run from handleClickTwo function'</span>);
    }
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>But I never encountered a situation where I needed to listen to the same event twice, so this advantage might not be useful at all.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The DOM events exposed by the browser enable you to respond to user actions in the appropriate way. </p>
<p>This pattern of using event listeners to do specific tasks is known as event-driven programming, and you'll use this pattern a lot when developing a web application using JavaScript.</p>
<p>There are two ways you can listen to events: using the <code>addEventListener()</code> JavaScript method and the <code>on[eventname]</code> HTML attributes. Each has its advantages and disadvantages, so it's good to be familiar with both.</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript">here</a>.</p>
<p><a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy for beginners and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic web application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is the Document Object Model? DOM for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ In this article, I'm going to explain to you how the DOM works so that you have a clear picture of why JavaScript is needed to develop a web application. First, let's recap what we know about HTML, CSS, and JavaScript. How HTML, CSS, and JavaScript w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/introduction-to-the-dom/</link>
                <guid isPermaLink="false">66bd9167621c718d60a31069</guid>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Wed, 10 Jan 2024 15:14:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/dom-introduction-feature-image-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this article, I'm going to explain to you how the DOM works so that you have a clear picture of why JavaScript is needed to develop a web application.</p>
<p>First, let's recap what we know about HTML, CSS, and JavaScript.</p>
<h2 id="heading-how-html-css-and-javascript-work">How HTML, CSS, and JavaScript work</h2>
<p>When you want to build a web application, you create an HTML document filled with HTML, CSS, and JavaScript.</p>
<p>These three technologies are used together like a team, each playing a different role in building what you see in your web browser.</p>
<p>HTML is a markup language used to define the structure and content of the page. The tags we use like <code>&lt;head&gt;</code>, <code>&lt;body&gt;</code>, and <code>&lt;button&gt;</code> have meanings, and the browser will process these tags, rendering the content of the document to the screen</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/9-just-html.png" alt="9 just html" width="600" height="400" loading="lazy">
<em>What an HTML-only website looks like</em></p>
<p>But the HTML alone produces a very boring and generic-looking page. CSS was created to enable us to change the way the HTML tags are represented on the browser.</p>
<p>By using CSS, you can make a button displayed in a color of your choice, or a text input box with a rounded border, making them more appealing and modern.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/9-html-and-css-1.png" alt="9 html and css" width="600" height="400" loading="lazy">
<em>A Website styled with CSS looks appealing and modern</em></p>
<p>HTML and CSS are great partners, but even then, a web page is still just a passive thing. Once the browser processes the content and renders it, you can’t edit the page in any way.</p>
<p>You can’t change the background and text color of the page (like switching to dark mode, for example). You can’t create cool animations, turn on the microphone or webcam, or retrieve data from another website to display on the page after a click.</p>
<p>JavaScript is the programming language that’s supported by the browser, and it fills this gap left open by HTML and CSS.</p>
<p>In short, JavaScript breathes life into static websites, turning them dynamic. It allows a website to interact with the user, respond to their actions, and dynamically update the content without requiring a page reload.</p>
<h2 id="heading-the-dom-explained">The DOM Explained</h2>
<p>So how come JavaScript can do things that HTML and CSS can’t do? Well, the answer is that JavaScript can manipulate the Document Object Model, or the DOM for short.</p>
<p>The DOM is a hierarchical structure composed of objects that make up a web page. Web browsers then expose this DOM so that you can change the page structure, style, and content using JavaScript.</p>
<p>For example, suppose you have the following HTML content in your document:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is a paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>The DOM graph generated by the HTML document above is as follows. I’m going to explain what the graph means below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/9-dom-example.png" alt="9 dom example" width="600" height="400" loading="lazy">
<em>Example of the DOM tree graph</em></p>
<p>The DOM looks like a tree structure with a set of connected nodes. These nodes are objects that you can access using JavaScript. The <code>html</code> node and its children are the content of your document.</p>
<p>For now, let’s focus on the <code>window</code> and <code>document</code> objects.</p>
<h2 id="heading-the-window-object">The Window Object</h2>
<p>The <code>window</code> object is the root of the DOM tree, and this object is used to instruct the browser to do tasks like:</p>
<ul>
<li>Displaying an alert box or a prompt</li>
<li>Log messages or errors to the console</li>
<li>Access the browser’s local storage</li>
<li>Access the document object</li>
</ul>
<p>You can access the window object from the Console by typing <code>window</code> and pressing Enter. The browser will respond by showing you the methods and properties of the object as follows:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/9-window.png" alt="9 window" width="600" height="400" loading="lazy">
<em>The Window object properties and methods</em></p>
<p>The <code>window</code> object provides both child objects and methods that you’re going to access to manipulate a web page.</p>
<p>For example, the <code>window</code> has the <code>console</code> object that you can use to log a message to the console.</p>
<p>Type the code below to the console and hit Enter:</p>
<pre><code class="lang-js"><span class="hljs-built_in">window</span>.console.log(<span class="hljs-string">'Hello World!'</span>);
</code></pre>
<p>You’ll see the string 'Hello World!' logged into the console.</p>
<p>The <code>window</code> object is a global object, so you can omit it when calling its child object. To access the <code>console</code> object, just type console as follows:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World!'</span>);
</code></pre>
<p>The same goes for when you access the <code>document</code> object. You can write <code>document.propertyOrMethod</code> instead of <code>window.document.propertyOrMethod</code>.</p>
<p>I won’t go too deep on the <code>window</code> object, because as a web developer, you’re going to interact more with the <code>document</code> object in your daily routine.</p>
<h2 id="heading-the-document-object">The Document Object</h2>
<p>The <code>document</code> object is the entry point for all HTML elements that you write in your document. This object is also what gives the Document Object Model its name.</p>
<p>It’s not called the Window Object Model because we’re mostly going to work with the Document object instead of the Window object.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/9-dom-example-html.png" alt="9 dom example html" width="600" height="400" loading="lazy">
<em>The Document Object is the child of the Window object</em></p>
<p>From the document object, you can retrieve any data related to the HTML content using JavaScript. </p>
<p>For example, you can get the Document title using the <code>document.title</code> property, and the URL using <code>document.URL</code>. The referrer is available in <code>document.referrer</code>, the domain in <code>document.domain</code>.</p>
<p>For the HTML document itself, you can access the whole HTML Element node using <code>document.documentElement</code>, the document head using the <code>document.head</code> property, or the body using <code>document.body</code></p>
<p>You can try to access these elements from the console as shown below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/9-document-properties.png" alt="9 document properties" width="600" height="400" loading="lazy">
<em>documentElement, head, and body properties of the Document object</em></p>
<p>You can see the documentation of all the properties and methods of the document object <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Document">here</a> (note that it might be overwhelming at first).</p>
<p>Of course, you can do much more than just read your document data. I've written another article that shows you <a target="_blank" href="https://www.freecodecamp.org/news/javascript-document-object-model-explained/">how to manipulate the DOM using JavaScript</a>.</p>
<h2 id="heading-summary">Summary</h2>
<p>The DOM is a tree-like structure generated from the HTML file that we created and loaded into the browser.</p>
<p>The browser then exposes this DOM as a set of JavaScript objects that we can access, such as the <code>window</code> and <code>document</code> objects.</p>
<p>It’s an important piece of technology that allows you to program the web browser to do specific tasks or change your HTML content.</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript">here</a>.</p>
<p><a target="_blank" href="https://codewithnathan.com/beginning-modern-javascript"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy for beginners and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic web application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Advanced JavaScript Operators – Nullish Coalescing, Optional Chaining, and Destructuring Assignment ]]>
                </title>
                <description>
                    <![CDATA[ Hi Everyone! In this article, I'm going to teach you how to use three advanced JavaScript operators: the Nullish Coalescing, Optional Chaining, and Destructuring Assignment operators. These three operators will help you write clearer and less error-p... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-advanced-operators/</link>
                <guid isPermaLink="false">66bd9169621c718d60a3106b</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Operators ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Thu, 04 Jan 2024 15:22:39 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/js-advanced-operators.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi Everyone! In this article, I'm going to teach you how to use three advanced JavaScript operators: the Nullish Coalescing, Optional Chaining, and Destructuring Assignment operators.</p>
<p>These three operators will help you write clearer and less error-prone code. </p>
<h2 id="heading-the-nullish-coalescing-operator">The Nullish Coalescing Operator</h2>
<p>When you’re inspecting JavaScript code, you may find an expression using a double question mark (<code>??</code>), as in the code below:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(username ?? <span class="hljs-string">"Guest"</span>);
</code></pre>
<p>The double question mark is a logical operator that returns the expression on the right-hand side of the mark when the expression on the left-hand side is <code>null</code> or <code>undefined</code></p>
<p>This operator is also known as the nullish coalescing operator. It’s a new feature introduced in JavaScript ES2020 that allows you to check for <code>null</code> or <code>undefined</code> values in a more concise way.</p>
<h3 id="heading-nullish-coalescing-operator-syntax">Nullish Coalescing Operator Syntax</h3>
<p>The syntax for the nullish coalescing operator is very simple. It consists of two question marks <code>??</code> placed between two operands.</p>
<p>Here’s an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> firstName = <span class="hljs-literal">null</span>;
<span class="hljs-keyword">let</span> username = firstName ?? <span class="hljs-string">"Guest"</span>;
<span class="hljs-built_in">console</span>.log(username); <span class="hljs-comment">// "Guest"</span>
</code></pre>
<p>The code above assigns the <code>firstName</code> variable value as the value of the <code>username</code> variable.</p>
<p>When the <code>firstName</code> value is <code>null</code> or <code>undefined</code>, then the value <code>Guest</code> will be assigned to the <code>username</code> variable instead:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/nullish-coalescing-output.png" alt="Image" width="600" height="400" loading="lazy">
<em>Result of using the nullish coalescing operator</em></p>
<p>You can also write it this way:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> username = <span class="hljs-literal">undefined</span> ?? <span class="hljs-string">"Guest"</span>;
<span class="hljs-built_in">console</span>.log(username); <span class="hljs-comment">// "Guest"</span>
</code></pre>
<p>As you can see, you don’t need an <code>if-else</code> statement to check for <code>null</code> or <code>undefined</code> values.</p>
<h3 id="heading-why-javascript-needs-this-operator">Why JavaScript Needs This Operator</h3>
<p>The nullish coalescing operator was created as an improved alternative to the OR operator <code>||</code>.</p>
<p>The OR operator was originally created to provide a default or fallback value when the left-hand expression is falsy, or evaluates to <code>false</code>.</p>
<p>But after some real-world uses, it’s clear that there are times when developers want to return values that are considered falsy, such as <code>0</code> and an empty string (<code>""</code>)</p>
<p>The use of the OR operator will prevent you from returning any falsy values at all. Consider the following example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// empty string evaluates to false in JavaScript:</span>
<span class="hljs-keyword">let</span> firstName = <span class="hljs-string">""</span>;
<span class="hljs-keyword">let</span> username = firstName ?? <span class="hljs-string">"Guest"</span>;
<span class="hljs-built_in">console</span>.log(username); <span class="hljs-comment">// ""</span>

<span class="hljs-comment">// When you use OR operator:</span>
username = firstName || <span class="hljs-string">"Guest"</span>;
<span class="hljs-built_in">console</span>.log(username); <span class="hljs-comment">// "Guest"</span>
</code></pre>
<p>By using the nullish coalescing operator, you will only replace <strong>exactly</strong> <code>null</code> and <code>undefined</code> values with the right-hand value.</p>
<p>The nullish coalescing operator can be used with any type of value, including numbers, strings, and objects.</p>
<h3 id="heading-nullish-coalescing-operator-use-cases">Nullish Coalescing Operator Use Cases</h3>
<p>The nullish coalescing operator is useful in a variety of situations where you need to check for <code>null</code> or <code>undefined</code> values and provide a default value.</p>
<p>Here are several examples of common use cases:</p>
<h4 id="heading-handling-missing-function-arguments">Handling Missing Function Arguments</h4>
<p>When a function is called, it’s possible that some of the arguments may be omitted.</p>
<p>The Nullish Coalescing Operator can be used to provide default values for a missing argument as follows:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name ?? <span class="hljs-string">"Guest"</span>}</span>!`</span>);
}

greet(); <span class="hljs-comment">// 'Hello, Guest!'</span>
greet(<span class="hljs-string">"John"</span>); <span class="hljs-comment">// 'Hello, John!'</span>
</code></pre>
<h4 id="heading-accessing-object-properties">Accessing Object Properties</h4>
<p>When working with objects, it’s possible that a property may not exist or is <code>undefined</code>.</p>
<p>The Nullish Coalescing Operator can be used to safely access object properties and provide a default value when the property is missing:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> user = { <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span> };
<span class="hljs-keyword">let</span> email = user.email ?? <span class="hljs-string">"N/A"</span>;
<span class="hljs-built_in">console</span>.log(email); <span class="hljs-comment">// 'N/A'</span>
</code></pre>
<h4 id="heading-choosing-between-a-variable-and-a-constant">Choosing Between a Variable and a Constant</h4>
<p>You may want to select a value from a variable or a constant if the variable is <code>null</code> or <code>undefined</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> value = <span class="hljs-literal">null</span>;
<span class="hljs-keyword">const</span> DEFAULT_VALUE = <span class="hljs-string">'Default'</span>;

<span class="hljs-keyword">let</span> result = value ?? DEFAULT_VALUE;

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// 'Default'</span>
</code></pre>
<p>As you can see, the Nullish Coalescing Operator is a great feature that can make your code more concise and reliable.</p>
<h3 id="heading-using-with-the-and-ampamp-operators">Using <code>??</code> with the <code>||</code> and <code>&amp;&amp;</code> Operators</h3>
<p>For safety reasons, the double question mark can’t be used together with JavaScript OR (<code>||</code>) and AND (<code>&amp;&amp;</code>) operators without parentheses <code>()</code> separating the operators.</p>
<p>For example, the following code tries to see if either <code>firstName</code> or <code>lastName</code> variable can be used as the value of <code>username</code> before using <code>"Guest"</code> as its value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> firstName = <span class="hljs-string">"John"</span>;
<span class="hljs-keyword">let</span> lastName = <span class="hljs-string">"Stone"</span>;
<span class="hljs-keyword">let</span> username = firstName || lastName ?? <span class="hljs-string">"Guest"</span>;
<span class="hljs-comment">// Error: Unexpected token '??'</span>

<span class="hljs-built_in">console</span>.log(username);
</code></pre>
<p>This is because JavaScript won’t be able to determine which operator it needs to evaluate first. You need to use parentheses to clearly indicate the priority of the evaluations.</p>
<p>The following code will first evaluate the expressions inside the parentheses:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> firstName = <span class="hljs-literal">null</span>;
<span class="hljs-keyword">let</span> lastName = <span class="hljs-literal">undefined</span>;
<span class="hljs-keyword">let</span> username = (firstName || lastName) ?? <span class="hljs-string">"Guest"</span>;

<span class="hljs-built_in">console</span>.log(username); <span class="hljs-comment">// "Guest"</span>
</code></pre>
<p>And that’s how you combine the nullish coalescing operator with either AND or OR operator.</p>
<h2 id="heading-the-optional-chaining-operator">The Optional Chaining Operator</h2>
<p>Like the nullish coalescing operator, the optional chaining operator is a modern addition to JavaScript that offers a better way to do things.</p>
<p>The optional chaining operator <code>?.</code> gives you a safe way to access properties and methods of an object, avoiding an error in the process.</p>
<p>One of the most common problems in JavaScript is that you can get an error when you access a property of an <code>undefined</code> value.</p>
<p>For example, suppose you have a <code>car</code> object as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {};

<span class="hljs-built_in">console</span>.log(car.manufacturer); <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(car.manufacturer.address); <span class="hljs-comment">// ❌ TypeError!</span>
</code></pre>
<p>In the example above, accessing the <code>manufacturer</code> property returns <code>undefined</code>, but when you try to access the <code>address</code> property of the <code>manufacturer</code> property, JavaScript returns an error.</p>
<p>Even though this is how JavaScript works, a better way to handle the non-existent property would be to just return an <code>undefined</code> back, just like when we try to access the <code>manufacturer</code> property.</p>
<p>This is why the optional chaining operator was created. The operator returns either the value of the property, or <code>undefined</code> when the property is <code>null</code> or <code>undefined</code>.</p>
<p>To use the operator, just add a question mark in front of the dot <code>.</code> notation:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {};

<span class="hljs-built_in">console</span>.log(car.manufacturer?.address); <span class="hljs-comment">// undefined</span>
</code></pre>
<p>The optional chaining operator can be added anytime you use the dot notation to access a property or method.</p>
<p>This operator allows you to avoid the TypeError that occurs when accessing a property or calling a method from a non-existent property:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = {};

<span class="hljs-built_in">console</span>.log(car.manufacturer?.address); <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(car.manufacturer?.drive()); <span class="hljs-comment">// undefined</span>
</code></pre>
<p>Note that the optional chaining operator only checks the value before it. If the <code>car</code> variable can be <code>null</code>, then you need to add the operator after when accessing the <code>car</code> object as well.</p>
<p>See the following example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> car = <span class="hljs-literal">null</span>;

<span class="hljs-built_in">console</span>.log(car?.manufacturer?.address); <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(car.manufacturer?.address); <span class="hljs-comment">// TypeError: Cannot read properties of null</span>
</code></pre>
<p>And that’s how the optional chaining operator works. It’s really useful when you’re working with objects in your project.</p>
<p>Next, let’s learn about the destructuring assignment.</p>
<h2 id="heading-destructuring-assignment-operator">Destructuring Assignment Operator</h2>
<p>The destructuring assignment is a special operator that allows you to "unpack" or "extract" the values of JavaScript arrays and objects. It has become one of the most useful features of JavaScript language for two reasons:</p>
<ul>
<li>It helps you to avoid code repetition.</li>
<li>It keeps your code clean and easy to understand.</li>
</ul>
<p>Let’s see how you can destructure an array and an object next.</p>
<h3 id="heading-destructuring-arrays">Destructuring Arrays</h3>
<p>Here’s how you normally assign an array values to variables:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> sampleArray = [<span class="hljs-string">'Jane'</span>, <span class="hljs-string">'John'</span>];

<span class="hljs-keyword">const</span> firstIndex = sampleArray[<span class="hljs-number">0</span>];
<span class="hljs-keyword">const</span> secondIndex = sampleArray[<span class="hljs-number">1</span>];
</code></pre>
<p>The code above works, but you need two lines of code to get two elements from an array. Using the destructuring assignment, you can assign array elements into variables in one short line:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> sampleArray = [<span class="hljs-string">'Jane'</span>, <span class="hljs-string">'John'</span>];

<span class="hljs-keyword">const</span> [firstIndex, secondIndex] = sampleArray;
</code></pre>
<p>The above code will return the same value for <code>firstIndex</code> and <code>secondIndex</code> variable. No matter how many elements you have, the destructuring will start from the zero index.</p>
<p>To create a destructuring assignment, you need to add square brackets <code>[]</code> after the <code>let</code>/ <code>const</code> keyword. When you add square brackets after the assignment (<code>=</code>) operator, it’s an array. If you add them before the assignment operator, it’s a destructuring assignment.</p>
<p>You can also use the rest operator <code>…​</code> to copy the rest of the values after your assignment. Take a look at the following example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> sampleArray = [<span class="hljs-string">'Jane'</span>, <span class="hljs-string">'John'</span>, <span class="hljs-string">'Jack'</span>, <span class="hljs-string">'Aston'</span>];

<span class="hljs-keyword">const</span> [one, two, ...rest] = sampleArray;
</code></pre>
<p>The <code>rest</code> variable will contain an array with values of <code>['Jack','Aston']</code>.</p>
<p>You can also put default values for these variables when the extracted value is undefined:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [a = <span class="hljs-string">'Martin'</span>, b = <span class="hljs-number">10</span>] = [<span class="hljs-literal">true</span>];

<span class="hljs-comment">// a will return true</span>
<span class="hljs-comment">// b will return 10</span>
</code></pre>
<p>You can also immediately assign the return of a function into assignments. This is frequently used in libraries like React:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> [a, b] = myFunction();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> [<span class="hljs-string">'John'</span>, <span class="hljs-string">'Jack'</span>];
}
</code></pre>
<p>The variable <code>a</code> will return "John" and <code>b</code> will return "Jack".</p>
<p>Finally, you can also ignore some variables by skipping the assignment for that index:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [a, , b] = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];

<span class="hljs-comment">// a will return 1</span>
<span class="hljs-comment">// b will return 3</span>
</code></pre>
<p>Destructuring assignment makes unpacking array values easier and shorter, with less repetition.</p>
<h3 id="heading-object-destructuring">Object Destructuring</h3>
<p>Just like arrays, you can destructure objects the same way, but instead of using the square brackets (<code>[]</code>) you need to use the curly brackets (<code>{}</code>):</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">'Jack'</span>,
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Smith'</span>,
};

<span class="hljs-keyword">const</span> { firstName, lastName } = user;
</code></pre>
<p>You can use the colon delimiter (<code>:</code>) to assign the property into a different name. The example below assign the value of <code>firstName</code> into <code>name</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">'Jack'</span>,
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Smith'</span>,
};

<span class="hljs-keyword">const</span> { <span class="hljs-attr">firstName</span>: name, lastName } = user;
</code></pre>
<p>Note that you still only create two variables: <code>name</code> and <code>lastName</code>. The <code>firstName</code> is assigned to <code>name</code>, so it won’t create a separate variable.</p>
<p>Just like arrays, you can destructure an object returned by a function immediately:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> { <span class="hljs-attr">firstName</span>: <span class="hljs-string">'Jack'</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Austin'</span> };
}

<span class="hljs-keyword">const</span> { firstName, lastName } = myFunction();
</code></pre>
<p>Also, you can destructure an object from the function parameters, exactly when you define the function:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params">{ firstName, lastName }</span>) </span>{
  <span class="hljs-keyword">return</span> firstName + <span class="hljs-string">' '</span> + lastName;
}

<span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">'Jack'</span>,
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Austin'</span>,
};

<span class="hljs-keyword">const</span> name = myFunction(user);
</code></pre>
<p>The destructuring assignment is a useful addition to JavaScript that makes it easier to unpack values from objects and arrays. You’re going to use it frequently when you code using a library like React.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>JavaScript is constantly improving every year, and the three operators explained in this article are a great addition that can help you produce more concise and readable code.</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G">here</a>.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>Until next time!  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Async/Await in JavaScript – Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Hello friends! In this article, I'm going to show you how to use the “async/await” special syntax when handling JavaScript Promises. If you don't know or need a refresher on JavaScript promises, you can read my previous article: How JavaScript Promis... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-async-await/</link>
                <guid isPermaLink="false">66bd91766d46d5e73b73e91d</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Fri, 15 Dec 2023 15:33:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/js-async-await.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hello friends! In this article, I'm going to show you how to use the “async/await” special syntax when handling JavaScript Promises.</p>
<p>If you don't know or need a refresher on JavaScript promises, you can read my previous article: <a target="_blank" href="https://www.freecodecamp.org/news/javascript-promise-object-explained/">How JavaScript Promises Work – Tutorial for Beginners</a>.</p>
<p>You'll need to understand JavaScript promises well before learning the async/await syntax.</p>
<h2 id="heading-how-asyncawait-works">How async/await Works</h2>
<p>The async/await syntax is a special syntax created to help you work with promise objects. It makes your code cleaner and clearer.</p>
<p>When handling a <code>Promise</code>, you need to chain the call to the function or variable that returns a <code>Promise</code> using <code>then/catch</code> methods.</p>
<p>When you have many promises, you will also need lots of <code>then</code> method chains. For example, here's how you might retrieve data using the <code>fetch()</code> function:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">json</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(json))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(error));
</code></pre>
<p>In the code above, the <code>fetch()</code> function returns a <code>Promise</code>, which we handle using the <code>then()</code> method. Inside the first <code>then()</code> method, we accept the <code>response</code> from the request and convert it into an object using the <code>json()</code> method.</p>
<p>In the second <code>then()</code> method, we receive the returned <code>json</code> data from the call to the <code>json()</code> method, then log that data to the console.</p>
<p>We also add the <code>catch()</code> method to handle any error that might happen when running the request.</p>
<p>The code is really not hard to understand, but we can make it even prettier by removing the <code>.then()</code> and <code>.catch()</code> chains, which also removes the callback functions.</p>
<h3 id="heading-the-await-keyword">The Await Keyword</h3>
<p>The <code>await</code> keyword basically makes JavaScript wait until the <code>Promise</code> object is resolved or rejected. Instead of having to use the callback pattern inside the <code>then()</code> method, you can assign the fulfilled promise into a variable like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>);
<span class="hljs-keyword">const</span> json = <span class="hljs-keyword">await</span> response.json();
<span class="hljs-built_in">console</span>.log(json)
</code></pre>
<p>The <code>await</code> keyword is placed before the call to a function or variable that returns a promise. It makes JavaScript wait for the promise object to settle before running the code in the next line.</p>
<p>Now if you run the code above, you might get an error like this:</p>
<pre><code class="lang-txt">SyntaxError: await is only valid in async functions and the top level bodies of modules
</code></pre>
<p>This error occurs because the <code>await</code> keyword must be used inside an asynchronous function or a module.</p>
<h3 id="heading-the-async-keyword">The Async Keyword</h3>
<p>To create an asynchronous function, you need to add the <code>async</code> keyword before your function name. Take a look at line 1 in the example below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">runProcess</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>);
  <span class="hljs-keyword">const</span> json = <span class="hljs-keyword">await</span> response.json();
  <span class="hljs-built_in">console</span>.log(json)
}

runProcess();
</code></pre>
<p>Here, we created an asynchronous function called <code>runProcess()</code> and put the code that uses the <code>await</code> keyword inside it. We can then run the asynchronous function by calling it, just like a regular function.</p>
<h2 id="heading-how-to-handle-errors-in-asyncawait">How to Handle Errors in Async/Await</h2>
<p>To handle an error that might occur from the async/await syntax, you can use the try/catch block to catch any rejection from your promise.</p>
<p>See the example below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">runProcess</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>);
    <span class="hljs-keyword">const</span> json = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(json);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(error);
  }
}

runProcess();
</code></pre>
<p>The try/catch block, put inside the <code>runProcess()</code> function, will handle the rejection that comes from the promise objects.</p>
<p>Now we have a complete async/await version of the standard Promise code we created earlier. Here's a comparison between the two:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/PROMISE---ASYNC.png" alt="Image" width="600" height="400" loading="lazy">
<em>Promise vs Async/Await Code Comparison</em></p>
<p>In the async/await version, the result of the promise is directly assigned to a variable. In the standard promise version, the result of the promise is passed as an argument to the <code>.then()</code> method. </p>
<p>Most developers prefer the async/await version as it looks more straightforward.</p>
<h2 id="heading-how-to-use-asyncawait-in-iife-and-arrow-functions">How to Use Async/Await in IIFE and Arrow Functions</h2>
<p>An Immediately Invoked Function Expression (IIFE) is a technique used to execute a function immediately as soon as you define it.</p>
<p>Unlike regular functions and variables, IIFEs will be removed from the running process once they are executed.</p>
<p>Aside from the standard function, you can also make an asynchronous IIFE. This is useful when you need to run the asynchronous function only once:</p>
<pre><code class="lang-js">(<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>);
    <span class="hljs-keyword">const</span> json = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(json);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(error);
  }
})();
</code></pre>
<p>You can also use the arrow syntax when creating an asynchronous function as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> runProcess = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>);
    <span class="hljs-keyword">const</span> json = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-built_in">console</span>.log(json);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(error);
  }
};

runProcess();
</code></pre>
<p>Feel free to use the syntax you want in your code.</p>
<h2 id="heading-why-use-the-asyncawait-syntax">Why Use the async/await Syntax?</h2>
<p>The async/await syntax enables you to handle promises without using <code>.then()</code> and <code>.catch()</code> method chaining, which also removes the need for nested callbacks.</p>
<p>This benefit is significant when you have a complex process after the promise is settled. </p>
<p>Going back to our example above, suppose you have a conditional statement inside the <code>.then()</code> method as follows:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">json</span> =&gt;</span> {
    <span class="hljs-keyword">if</span> (json.userId == <span class="hljs-number">1</span>) {
      json.completed == <span class="hljs-literal">false</span>;
    } <span class="hljs-keyword">else</span> {
      json.completed == <span class="hljs-literal">true</span>;
    }
  })
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(error));
</code></pre>
<p>Here, you can see that the callback function that accepts the <code>json</code> data has an if/else block inside it. </p>
<p>This code is hard to reason with and modify when compared to the async/await version as follows:</p>
<pre><code class="lang-js">(<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/todos/1'</span>);
    <span class="hljs-keyword">const</span> json = <span class="hljs-keyword">await</span> response.json();
    <span class="hljs-keyword">if</span> (json.userId == <span class="hljs-number">1</span>) {
      json.completed == <span class="hljs-literal">false</span>;
    } <span class="hljs-keyword">else</span> {
      json.completed == <span class="hljs-literal">true</span>;
    }
    <span class="hljs-built_in">console</span>.log(json);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.log(error);
  }
})();
</code></pre>
<p>By using the async/await syntax, you reduce the need for method chaining and nested callbacks. This impact the readability of your code, especially when you have nested code like if/else and a for loop block.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Now you've learned how the async/await syntax works. The syntax makes working with promises much easier by removing the need for <code>.then()</code> and <code>.catch()</code> method chaining, which also removes the need for nested callbacks.</p>
<p>Even though the <code>await</code> keyword can only be used inside an <code>async</code> function, you can use an IIFE to invoke the async function only once.</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G">here</a>.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Manipulate the DOM in JavaScript – Most Commonly Used Techniques ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this article, I’m going to cover everything you need to know about manipulating the DOM. Basically, each Element object in the DOM has properties and methods that you can use to interact with that element. The following are the most c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-document-object-model-explained/</link>
                <guid isPermaLink="false">66bd9178621c718d60a3106d</guid>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Thu, 07 Dec 2023 22:19:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/js-dom-manipulation-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this article, I’m going to cover everything you need to know about manipulating the DOM.</p>
<p>Basically, each <code>Element</code> object in the DOM has properties and methods that you can use to interact with that element.</p>
<p>The following are the most common and practical ways you might want to manipulate the <code>Element</code> object:</p>
<ol>
<li><a class="post-section-overview" href="#heading-change-the-content-of-an-element">Change the Content of an Element</a></li>
<li><a class="post-section-overview" href="#heading-manipulate-the-class-attribute">Manipulate the Class Attribute</a></li>
<li><a class="post-section-overview" href="#heading-setting-css-styles-using-javascript">Setting CSS Styles Using JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-create-add-and-remove-elements">Create, Add, and Remove Elements</a></li>
<li><a class="post-section-overview" href="#heading-insert-element-at-a-specific-position">Insert Element at a Specific Position</a></li>
<li><a class="post-section-overview" href="#heading-manipulating-element-attributes">Manipulating Element Attributes</a></li>
<li><a class="post-section-overview" href="#heading-manipulating-data-attributes">Manipulating Data Attributes</a></li>
</ol>
<p>Manipulating the DOM seems complex in theory, but as you’ll see in this article, there are a few methods that you’ll use over and over again in many scenarios.</p>
<p>Once you know about these methods, you will have leveled up your skill in DOM manipulation. Let’s begin!</p>
<h2 id="heading-change-the-content-of-an-element">Change the Content of an Element</h2>
<p>You can change the value or content of an element by setting the <code>innerText</code> property of that element.</p>
<p>For example, suppose you have a paragraph element as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"myParagraph"</span>&gt;</span>This is a paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>Next, you select the element and change its <code>innerText</code> value like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.myParagraph'</span>);

p.innerText = <span class="hljs-string">'A new day is dawning'</span>;
</code></pre>
<p>The <code>p</code> element would have its value changed as you see below:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"myParagraph"</span>&gt;</span>A new day is dawning<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>And that’s how you change the value of an element.</p>
<h2 id="heading-manipulate-the-class-attribute">Manipulate the Class Attribute</h2>
<p>You can add a new <code>class</code> attribute to an <code>Element</code> by using the <code>add()</code> method of the <code>classList</code> object:</p>
<pre><code class="lang-js">Element.classList.add(<span class="hljs-string">'myClass'</span>);
</code></pre>
<p>You can remove a class using the <code>remove()</code> method:</p>
<pre><code class="lang-js">Element.classList.remove(<span class="hljs-string">'myClass'</span>);
</code></pre>
<p>The <code>classList</code> object is a collection object that you can use to manipulate the <code>class</code> attribute of an <code>Element</code>.</p>
<p>You can’t directly edit the <code>classList</code> property because it’s a read-only property. But you can use its methods to change the element classes.</p>
<p>To replace an existing class with a new class, use the <code>replace()</code> method:</p>
<pre><code class="lang-js">Element.classList.replace(<span class="hljs-string">'oldClass'</span>, <span class="hljs-string">'newClass'</span>);
</code></pre>
<p>There’s also the <code>toggle()</code> method, which works like a switch: adds a class if it’s not there, removes a class if it’s there.</p>
<pre><code class="lang-js">Element.classList.toggle(<span class="hljs-string">'myClass'</span>);
</code></pre>
<p>To check if an element contains a specific class, use the <code>contains()</code> method and pass the class you want to check as a string:</p>
<pre><code class="lang-js">Element.classList.contains(<span class="hljs-string">'myClass'</span>);
</code></pre>
<p>The method returns <code>true</code> when the class is specified. Otherwise it returns <code>false</code>.</p>
<h2 id="heading-setting-css-styles-using-javascript">Setting CSS Styles Using JavaScript</h2>
<p>Since you’ve learned how to set and remove classes from an element, you can control the style of an element by adding or removing classes that change the style rules applied to an element.</p>
<p>For example, you might have the following style rules in your CSS code:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.color-primary</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#007bff</span>;
}

<span class="hljs-selector-class">.color-secondary</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#6c757d</span>;
}

<span class="hljs-selector-class">.bold</span> {
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">700</span>;
}
</code></pre>
<p>If you have an element with the <code>color-primary</code> class applied, you can replace it with <code>color-secondary</code> class, or add the <code>bold</code> class. </p>
<p>Suppose you have a paragraph element as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"myParagraph"</span>&gt;</span>A new day is dawning<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>Here’s how you change the style using classes:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.myParagraph'</span>);

<span class="hljs-comment">// add a class to the element</span>
p.classList.add(<span class="hljs-string">'color-primary'</span>);

<span class="hljs-comment">// replace a class</span>
p.classList.replace(<span class="hljs-string">'color-primary'</span>, <span class="hljs-string">'color-secondary'</span>);

<span class="hljs-comment">// remove a class</span>
p.classList.remove(<span class="hljs-string">'color-secondary'</span>);
</code></pre>
<p>At times, you might need to apply CSS directly to the DOM element you selected.</p>
<p>The <code>Element</code> object provides you with the <code>style</code> property which controls the inline style of the element.</p>
<p>For example, you can change the font weight of an element using the <code>Element.style.fontWeight</code> property like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.myParagraph'</span>);

p.style.fontWeight = <span class="hljs-string">'700'</span>; <span class="hljs-comment">// set font weight</span>
p.style.textTransform = <span class="hljs-string">'uppercase'</span>; <span class="hljs-comment">// set to uppercase</span>
p.style.color = <span class="hljs-string">'#007bff'</span>; <span class="hljs-comment">// set color</span>
</code></pre>
<p>You can change the border style of an element as follows:</p>
<pre><code class="lang-js">p.style.border = <span class="hljs-string">'1px solid black'</span>;
</code></pre>
<p>The <code>style</code> property uses the camelCase instead of the hyphen-case, so <code>font-weight</code> becomes <code>fontWeight</code> and <code>text-transform</code> becomes <code>textTransform</code>.</p>
<p>And now you know how to set CSS styles using JavaScript. I would recommend that you change element styles by adding and removing classes because it’s more maintainable and follows the common approach.</p>
<p>Only access the <code>style</code> property if you won’t use the same style anywhere else.</p>
<h2 id="heading-create-add-and-remove-elements">Create, Add, and Remove Elements</h2>
<p>Besides creating a DOM tree out of your HTML file, you also have the ability to create DOM elements programmatically using JavaScript.</p>
<p>This is possible because the <code>document</code> object also has the <code>createElement()</code> method, which allows you to create any <code>Element</code> object, which is essentially the tags you write in your HTML file.</p>
<p>For example, you can create a paragraph element like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'p'</span>);
</code></pre>
<p>After you create that element, you can add some content to it using the <code>innerText</code> property:</p>
<pre><code class="lang-js">p.innerText = <span class="hljs-string">'This paragraph is created using JavaScript'</span>;
</code></pre>
<p>Now you need to add it to the existing DOM tree so that it appears on the screen. You can attach the element anywhere inside your existing tree structure.</p>
<p>Suppose you want to add the paragraph to the <code>body</code> tag. Then you need to use the <code>querySelector()</code> method to select the <code>body</code>, and call the <code>append()</code> method on the element:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'p'</span>);

p.innerText = <span class="hljs-string">'This paragraph is created using JavaScript'</span>;

<span class="hljs-keyword">const</span> body = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'body'</span>);

body.append(p);
</code></pre>
<p>The paragraph will be added as a child of the <code>body</code> tag as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This paragraph is created using JavaScript<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>If you want to remove an element, you can call the <code>remove()</code> method from the element you want to remove.</p>
<p>This code will remove the paragraph element:</p>
<pre><code class="lang-js">p.remove();
</code></pre>
<h2 id="heading-insert-element-at-a-specific-position">Insert Element at a Specific Position</h2>
<p>The <code>append()</code> method that we explored above will insert a new element as the last child of the parent element.</p>
<p>If you want to insert the element at a specific position, you can use the <code>insertBefore()</code> method.</p>
<p>Let’s see an easy example. Suppose you have an HTML content as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"first"</span>&gt;</span>The first paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>To insert an element before the first paragraph, you need to call the <code>insertBefore()</code> method from the parent element (which is the <code>body</code> tag) and pass two arguments to it:</p>
<ol>
<li>The new element you want to add</li>
<li>The sibling element before which the new element is inserted</li>
</ol>
<p>Here’s an example of creating a second paragraph and inserting it before the first paragraph:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> p2 = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'p'</span>);

p2.innerText = <span class="hljs-string">'The second paragraph'</span>;

<span class="hljs-keyword">let</span> body = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'body'</span>);
<span class="hljs-keyword">let</span> p1 = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#first'</span>);

body.insertBefore(p2, p1);
</code></pre>
<p>As a result of running the script above, the second paragraph will be inserted before the first paragraph:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The second paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"first"</span>&gt;</span>The first paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>Keep in mind that the DOM doesn’t provide an <code>insertAfter</code> method, because it’s not needed.</p>
<p>You use the <code>append()</code> method to insert an element at the last position, and if you want to control the position, use the <code>insertBefore()</code> method.</p>
<h2 id="heading-manipulating-element-attributes">Manipulating Element Attributes</h2>
<p>The <code>classList</code> object only provide methods to change the <code>class</code> of an element. If you want to change other attributes like <code>id</code>, <code>href</code>, or <code>src</code>, you can use the <code>setAttribute()</code> method.</p>
<p>The <code>setAttribute()</code> method accepts two arguments:</p>
<ol>
<li>The name of the attribute to set</li>
<li>The value of the attribute to set</li>
</ol>
<p>For example, here’s how to set the <code>src</code> attribute of an <code>img</code> tag:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"profile-pic"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"feature-image.png"</span> /&gt;</span>
</code></pre>
<p>Select the <code>img</code> element using <code>querySelector()</code>, then call the <code>setAttribute()</code> method on the element:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> img = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#profile-pic'</span>);

img.setAttribute(<span class="hljs-string">'src'</span>, <span class="hljs-string">'new-image.jpg'</span>);
</code></pre>
<p>The <code>src</code> attribute value would be changed as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"profile-pic"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"new-image.jpg"</span> /&gt;</span>
</code></pre>
<p>If you want to the an attribute’s value, you can use the <code>getAttribute()</code> method.</p>
<p>Pass the attribute you want to check as an argument to the method. If the attribute is set, the method returns the value of that attribute as a string. If not, it returns <code>null</code>:</p>
<pre><code class="lang-js">img.getAttribute(<span class="hljs-string">'src'</span>); <span class="hljs-comment">// new-image.jpg</span>
img.getAttribute(<span class="hljs-string">'href'</span>); <span class="hljs-comment">// null</span>
</code></pre>
<p>You can use both <code>setAttribute()</code> and <code>getAttribute()</code> methods to interact with any HTML attributes.</p>
<p>If you want to delete an attribute, use the <code>removeAttribute()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> img = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#profile-pic'</span>);

<span class="hljs-comment">// Delete the src attribute</span>
img.removeAttribute(<span class="hljs-string">'src'</span>);
</code></pre>
<h2 id="heading-manipulating-data-attributes">Manipulating Data Attributes</h2>
<p>The data attribute is used to store extra information on HTML elements. How you use the data is up to you.</p>
<p>Suppose you have an HTML tag as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"intro"</span> <span class="hljs-attr">data-attribute-theme</span>=<span class="hljs-string">"light"</span> <span class="hljs-attr">data-session</span>=<span class="hljs-string">"2022"</span>&gt;</span>
  Hello World!
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>You can access the data attributes from the <code>dataset</code> property of the element above like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Select the div</span>
<span class="hljs-keyword">let</span> myDiv = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#intro'</span>);

<span class="hljs-comment">// Access the dataset property</span>
<span class="hljs-built_in">console</span>.log(myDiv.dataset.session) <span class="hljs-comment">// 2022</span>

<span class="hljs-comment">// Use camelCase when your data attribute is more than one word</span>
<span class="hljs-built_in">console</span>.log(myDiv.dataset.attributeTheme) <span class="hljs-comment">// light</span>
</code></pre>
<p>If you want to change the attribute value, you can reassign the right <code>dataset</code> property to a new value directly:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Select the div</span>
<span class="hljs-keyword">let</span> myDiv = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#intro'</span>);

<span class="hljs-comment">// Change the value of a data attribute</span>
myDiv.dataset.session = <span class="hljs-string">'2023'</span>
</code></pre>
<p>If you want to delete the data attribute, use the <code>removeAttribute()</code> method similar to how you delete a regular attribute:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myDiv = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#intro'</span>);

<span class="hljs-comment">// Remove data-session attribute</span>
myDiv.removeAttribute(<span class="hljs-string">'data-session'</span>);

<span class="hljs-comment">// Remove data-attribute-theme attribute</span>
myDiv.removeAttribute(<span class="hljs-string">'data-attribute-theme'</span>);
</code></pre>
<p>And that’s how you manipulate the data attribute using JavaScript.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>And that's all for now about DOM element manipulations. At this point, I hope you can see why JavaScript is required to build a modern web application. It allows you to interact and change the content that exists in your website.</p>
<p>This enables a whole lot of dynamic changes to the website you created.</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G">here</a>.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use JavaScript Arrow Functions – Explained in Detail ]]>
                </title>
                <description>
                    <![CDATA[ Hello everyone! In this article, I’m going to explain one of the most useful features in JavaScript: the arrow function. I’ll compare the arrow function with the regular function syntax, I'll show you how to convert a regular function into an arrow f... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-arrow-functions-in-depth/</link>
                <guid isPermaLink="false">66bd91722fbe28509b2d6ebc</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Thu, 30 Nov 2023 19:26:49 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/How-to-get-file-extension-with-PHP.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hello everyone! In this article, I’m going to explain one of the most useful features in JavaScript: the arrow function.</p>
<p>I’ll compare the arrow function with the regular function syntax, I'll show you how to convert a regular function into an arrow function easily, and I'll discuss why the arrow function syntax is recommended over the regular function.</p>
<p>Here's what we'll cover:</p>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-the-arrow-function-syntax">What Is the Arrow Function Syntax?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-convert-a-regular-function-to-an-arrow-function-easily">How to Convert a Regular Function to an Arrow Function Easily</a></li>
<li><a class="post-section-overview" href="#heading-why-arrow-functions-are-recommended-over-regular-functions">Why Arrow Functions Are Recommended Over Regular Functions</a></li>
<li><a class="post-section-overview" href="#heading-arrow-functions-are-better-for-short-functions">Arrow Functions Are Better for Short Functions</a></li>
<li><a class="post-section-overview" href="#heading-arrow-functions-have-an-implicit-return-statement">Arrow Functions Have an Implicit Return Statement</a></li>
<li><a class="post-section-overview" href="#heading-arrow-functions-dont-have-this-binding">Arrow Functions Don’t Have <code>this</code> Binding</a></li>
<li><a class="post-section-overview" href="#heading-when-you-should-not-use-arrow-functions">When You Should Not Use Arrow Functions?</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<p>Let’s dive in!</p>
<h2 id="heading-what-is-the-arrow-function-syntax">What Is the Arrow Function Syntax?</h2>
<p>When you need to create a function in JavaScript, the main method is to use the <code>function</code> keyword followed by the function name as shown below:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetings</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
}

greetings(<span class="hljs-string">'John'</span>); <span class="hljs-comment">// Hello, John!</span>
</code></pre>
<p>The arrow function syntax allows you to create a function expression that produces the same result as the code above.</p>
<p>Here’s the <code>greetings()</code> function again, but using the arrow function syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> greetings = <span class="hljs-function"><span class="hljs-params">name</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
};

greetings(<span class="hljs-string">'John'</span>); <span class="hljs-comment">// Hello, John!</span>
</code></pre>
<p>When you declare a function with the arrow function syntax, you need to assign the declaration to a variable so that the function has a name.</p>
<p>Basically, the arrow function syntax looks as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFunction = <span class="hljs-function">(<span class="hljs-params">param1, param2, ...</span>) =&gt;</span> {
  <span class="hljs-comment">// function body</span>
}
</code></pre>
<p>In the code above, the <code>myFunction</code> is the variable that holds the function. You can call the function as <code>myFunction()</code> later in your code.</p>
<p><code>(param1, param2, ...)</code> are the function parameters. You can define as many parameters as required by the function.</p>
<p>Then you have the arrow <code>=&gt;</code> to indicate the beginning of the function. After that, you can write curly brackets <code>{}</code> to indicate the function body, or remove them if you have a single-line function. More on this later.</p>
<p>At first, the arrow function may seem weird as you are used to seeing the <code>function</code> keyword. But as you start using the arrow syntax, you will see that it’s very convenient and easier to write.</p>
<p>Let me show you an easy way to convert a regular function to an arrow function next.</p>
<h2 id="heading-how-to-convert-a-regular-function-to-an-arrow-function-easily">How to Convert a Regular Function to an Arrow Function Easily</h2>
<p>You can follow these <strong>three easy steps</strong> to convert a regular function to an arrow function:</p>
<ol>
<li>Replace the <code>function</code> keyword with the variable keyword <code>const</code></li>
<li>Add the <code>=</code> symbol after the function name and before the parentheses</li>
<li>Add the <code>=&gt;</code> symbol after the parentheses</li>
</ol>
<p>Usually, a function is never changed after the declaration, so we use the <code>const</code> keyword instead of <code>let</code>.</p>
<p>The code below should help you visualize the steps:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetings</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
}

<span class="hljs-comment">// step 1: replace function with const</span>
<span class="hljs-keyword">const</span> greetings(name) {
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
}

<span class="hljs-comment">// step 2: add = after the function name</span>
<span class="hljs-keyword">const</span> greetings = (name) {
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
}

<span class="hljs-comment">// step 3: add =&gt; after the parentheses</span>
<span class="hljs-keyword">const</span> greetings = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
}
</code></pre>
<p>The three steps above are enough to convert any old JavaScript function syntax to the new arrow function syntax.</p>
<p>When you have a single line function, there’s a fourth optional step to remove the curly brackets and the <code>return</code> keyword as follows:</p>
<pre><code class="lang-js"><span class="hljs-comment">// from this</span>
<span class="hljs-keyword">const</span> greetings = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
};

<span class="hljs-comment">// to this</span>
<span class="hljs-keyword">const</span> greetings = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
</code></pre>
<p>When you have exactly one parameter, you can also remove the parentheses:</p>
<pre><code class="lang-js"><span class="hljs-comment">// from this</span>
<span class="hljs-keyword">const</span> greetings = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;

<span class="hljs-comment">// to this</span>
<span class="hljs-keyword">const</span> greetings = <span class="hljs-function"><span class="hljs-params">name</span> =&gt;</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
</code></pre>
<p>But the last two steps are optional. Only the first three steps are required to convert any JavaScript function created using the <code>function</code> keyword into the arrow function syntax.</p>
<h2 id="heading-why-arrow-functions-are-recommended-over-regular-functions">Why Arrow Functions Are Recommended Over Regular Functions</h2>
<p>The arrow function syntax offers improvements to the way you write a function in JavaScript, such as:</p>
<ul>
<li>You can write short functions in a more straightforward manner</li>
<li>For single-line functions, the <code>return</code> statement can be implicit</li>
<li>The <code>this</code> keyword is not bound to the function.</li>
</ul>
<p>Let’s see how these improvements work with practical examples next.</p>
<h3 id="heading-arrow-functions-are-better-for-short-functions">Arrow Functions Are Better for Short Functions</h3>
<p>Suppose you have a single-line function that prints a string to the console. Using the <code>function</code> keyword, here’s how you would write the function:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetings</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
}
</code></pre>
<p>If you use the arrow function syntax, you can omit the curly brackets, creating a single-line function as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> greetings = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
</code></pre>
<p>Even more, you can remove the parentheses that surround the function parameters when you have exactly one parameter:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> greetings = <span class="hljs-function"><span class="hljs-params">name</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
</code></pre>
<p>If your function has no parameter, then you need to pass empty parentheses between the assignment and the arrow syntax as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> greetings = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, World!`</span>);
</code></pre>
<p>When using the arrow function syntax, the curly brackets are required only when your function is more than a single line. For example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> greetings = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World!'</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'How are you?'</span>);
};
</code></pre>
<p>When you use the regular <code>function</code> keyword, you can’t omit the curly brackets no matter what.</p>
<p>Arrow functions are also great for situations where you don’t need to name the function, such as callbacks:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];

<span class="hljs-comment">// From this:</span>
myArray.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">item</span>) </span>{
  <span class="hljs-built_in">console</span>.log(item);
});

<span class="hljs-comment">// To this:</span>
myArray.forEach(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(item));
</code></pre>
<p>Or when you need to create an Immediately Invoked Function Expression (IIFE):</p>
<pre><code class="lang-js"><span class="hljs-comment">// From this:</span>
(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World'</span>);
})();

<span class="hljs-comment">// To this:</span>
(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World'</span>))();
</code></pre>
<p>As you can see, using the arrow function syntax makes your code much more clean and concise.</p>
<h3 id="heading-arrow-functions-have-an-implicit-return-statement">Arrow Functions Have an Implicit Return Statement</h3>
<p>When you have a single-line arrow function, the return statement will be added implicitly by JavaScript. This means you shouldn't add the <code>return</code> keyword explicitly.</p>
<p>To show you what I mean, suppose you have a function that sums two numbers as follows:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<p>When you write the function above using the arrow function syntax, you need to remove the curly brackets and the <code>return</code> keyword:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> sum = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b;
</code></pre>
<p>If you didn’t remove the <code>return</code> keyword, then JavaScript will throw an error, saying an opening curly bracket <code>{</code> is expected.</p>
<p>When you use arrow functions, only write the <code>return</code> statement explicitly when you have multi-line statements:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> sum = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> result = a + b;
  <span class="hljs-keyword">return</span> result;
};
</code></pre>
<p>When you remove the curly brackets, don’t forget to remove the <code>return</code> keyword if you use it.</p>
<h3 id="heading-arrow-functions-dont-have-this-binding">Arrow Functions Don’t Have <code>this</code> Binding</h3>
<p>One significant difference between the arrow function and the regular function syntax is in how they handle the <code>this</code> keyword.</p>
<p>In a regular function, the <code>this</code> keyword refers to the object from which you <strong>call</strong> the function. In an arrow function, the <code>this</code> keyword refers to the object from which you <strong>define</strong> the function.</p>
<p>To show you what I mean, suppose you have a <code>person</code> with the following properties and methods:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Nathan'</span>,
  <span class="hljs-attr">skills</span>: [<span class="hljs-string">'HTML'</span>, <span class="hljs-string">'CSS'</span>, <span class="hljs-string">'JavaScript'</span>],

  showSkills() {
    <span class="hljs-built_in">this</span>.skills.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">skill</span>) </span>{
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> is skilled in <span class="hljs-subst">${skill}</span>`</span>);
    });
  },
};

person.showSkills();
</code></pre>
<p>If you run the code above, the result of calling the <code>showSkills()</code> method would be:</p>
<pre><code class="lang-txt">undefined is skilled in HTML
undefined is skilled in CSS
undefined is skilled in JavaScript
</code></pre>
<p>Here, the <code>this</code> keyword refers to the global <code>Window</code> object because we called the <code>showSkills()</code> method outside of the <code>person</code> object.</p>
<p>In the global object, the <code>name</code> property is <code>undefined</code>. Now, let’s rewrite the callback function using the arrow syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Nathan'</span>,
  <span class="hljs-attr">skills</span>: [<span class="hljs-string">'HTML'</span>, <span class="hljs-string">'CSS'</span>, <span class="hljs-string">'JavaScript'</span>],

  showSkills() {
    <span class="hljs-built_in">this</span>.skills.forEach(<span class="hljs-function"><span class="hljs-params">skill</span> =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> is skilled in <span class="hljs-subst">${skill}</span>`</span>);
    });
  },
};

person.showSkills();
</code></pre>
<p>Run the code again, and the result would be:</p>
<pre><code class="lang-txt">Nathan is skilled in HTML
Nathan is skilled in CSS
Nathan is skilled in JavaScript
</code></pre>
<p>Here, the <code>this</code> keyword refers to the object from which the arrow function is defined, which is the <code>person</code> object.</p>
<p>This one behavior is what makes people prefer arrow functions, because it makes more sense to have <code>this</code> refer to the object from which you define that function rather than from which you call it.</p>
<h2 id="heading-when-you-should-not-use-arrow-functions">When You Should Not Use Arrow Functions?</h2>
<p>Arrow functions are typically preferred over standard functions, but there are a few situations when you shouldn't use the arrow function.</p>
<p>One of these situations is when you define an object method. Back to our <code>person</code> object example above, suppose you write the <code>showSkills()</code> method as an arrow function like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Nathan'</span>,
  <span class="hljs-attr">skills</span>: [<span class="hljs-string">'HTML'</span>, <span class="hljs-string">'CSS'</span>, <span class="hljs-string">'JavaScript'</span>],

  <span class="hljs-attr">showSkills</span>: <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">this</span>.skills.forEach(<span class="hljs-function"><span class="hljs-params">skill</span> =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> is skilled in <span class="hljs-subst">${skill}</span>`</span>);
    });
  },
};

person.showSkills();
</code></pre>
<p>Running the above code will cause an error:</p>
<pre><code class="lang-txt">TypeError: Cannot read properties of undefined (reading 'forEach')
</code></pre>
<p>When inside an object, the <code>this</code> keyword refers to the current object <strong>only</strong> when you declare the method using the standard syntax (<code>methodName()</code> or <code>methodName: function(){ }</code>)</p>
<p>When you declare an object method using the arrow function, the <code>this</code> keyword refers to the global object, and the <code>skills</code> property is <code>undefined</code> there.  Never use the arrow function when declaring a method.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>And that's all about arrow functions. Now you’ve learned the differences between arrow functions and regular functions, how to convert a regular function into an arrow function, as well as when the arrow functions are recommended (and not recommended!).</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G">here</a>.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use JavaScript's Array reduce() Method – Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ Hello again, friends! The reduce() method is one of the most confusing Array methods in JavaScript. So in this article, I’m going to help you clearly see how the method works.  I'm also going to show some examples that'll help you understand how and ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-javascript-array-reduce-method/</link>
                <guid isPermaLink="false">66bd9159abf0ccf74f1ce9b6</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Wed, 29 Nov 2023 18:30:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/js-reduce.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hello again, friends! The <code>reduce()</code> method is one of the most confusing Array methods in JavaScript. So in this article, I’m going to help you clearly see how the method works. </p>
<p>I'm also going to show some examples that'll help you understand how and where you may want to use the method. Don’t worry! <code>reduce()</code> is actually simple once you understand how it works.</p>
<h2 id="heading-how-the-reduce-method-works">How the <code>reduce()</code> Method Works</h2>
<p>The <code>reduce()</code> method got its name from the functionality it provides, which is to iterate and “reduce” an array's values into one value.</p>
<p>The easiest way to understand how the <code>reduce()</code> method works is through an example, so let’s see an easy one first.</p>
<p>Suppose you have an array of objects that contain a <code>name</code> and <code>price</code> property as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> items = [
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Apple'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">1</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Orange'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">2</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Mango'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">3</span> },
];
</code></pre>
<p>Next, you are tasked to get the sum of the <code>price</code> property and get the total price. You can do this using the <code>forEach()</code> method as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> items = [
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Apple'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">1</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Orange'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">2</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Mango'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">3</span> },
];

<span class="hljs-keyword">let</span> totalPrice = <span class="hljs-number">0</span>;

items.forEach(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> {
  totalPrice += item.price;
})

<span class="hljs-built_in">console</span>.log(totalPrice); <span class="hljs-comment">// 6</span>
</code></pre>
<p>First, we declare the <code>totalPrice</code> variable and assign <code>0</code> as its value. Next, we called the <code>forEach()</code> method to iterate over the <code>items</code> array, adding the price of each item to the <code>totalPrice</code>.</p>
<p>The code above works, but since we’re looking to get a single value from the array, the <code>reduce()</code> method would be more suited for the task.</p>
<p>The <code>reduce()</code> method works in a similar manner to the <code>forEach()</code> method, with the added ability to collect the result of each iteration as a single value.</p>
<p>Let’s try to get the total price using the <code>reduce()</code> method. First, you need to call the <code>reduce()</code> method and pass two parameters to the callback function: <code>accumulator</code> and <code>item</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> totalPrice = items.reduce(<span class="hljs-function">(<span class="hljs-params">accumulator ,item</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> accumulator += item.price;
}, <span class="hljs-number">0</span>)
</code></pre>
<p>The <code>accumulator</code> parameter is the single value that will be returned by the <code>reduce()</code> method. It will contain the value returned by the callback function in each iteration.</p>
<p>The <code>item</code> parameter is simply the item from the array, which will change in each iteration just like in the <code>forEach()</code> method.</p>
<p>In the first iteration, the <code>accumulator</code> parameter will contain whatever value you passed as the second argument of the <code>reduce()</code> method. In the above case, it’s <code>0</code>.</p>
<p>When we use the <code>forEach()</code> method, we do addition assignments <code>+=</code> to the <code>totalPrice</code> variable, so we declare it using the <code>let</code> keyword. But when using the <code>reduce()</code> method, you can use the <code>const</code> keyword because we only assign a value to the <code>totalPrice</code> once.</p>
<p>And that’s basically how the <code>reduce()</code> method works. It iterates over each element in your array, and each iteration returns a single value, which is the <code>accumulator</code>.</p>
<p>When the iteration is finished, the <code>accumulator</code> value will be returned from the method.</p>
<h2 id="heading-when-to-use-the-reduce-method">When to Use the <code>reduce()</code> Method</h2>
<p>As shown above, the <code>reduce()</code> method is recommended when you need to have a single value returned from iterating over your array.</p>
<p>This includes:</p>
<ul>
<li>Summarizing your values into a single value</li>
<li>Grouping similar items together</li>
<li>Removing duplicates from an array</li>
</ul>
<p>The single value returned by the method can also be an array of objects, therefore containing multiple values.</p>
<p>You’ve seen how to sum values in the previous section, so let’s see some examples of grouping items and removing duplicates next.</p>
<h3 id="heading-how-to-group-similar-items-together">How to Group Similar Items Together</h3>
<p>Suppose you have an array of objects again, but this time, the objects have <code>name</code> and <code>category</code> properties:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> items = [
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Apple'</span>, <span class="hljs-attr">category</span>: <span class="hljs-string">'Fruit'</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Onion'</span>, <span class="hljs-attr">category</span>: <span class="hljs-string">'Vegetable'</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Orange'</span>, <span class="hljs-attr">category</span>: <span class="hljs-string">'Fruit'</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Lettuce'</span>, <span class="hljs-attr">category</span>: <span class="hljs-string">'Vegetable'</span> },
];
</code></pre>
<p>Now, you want to group these items based on their <code>category</code> value. You can use the <code>reduce()</code> method and return a single object value.</p>
<p>First, you call the reduce method and pass an empty object <code>{}</code> as the initial <code>accumulator</code> value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> groupedItems = items.reduce(<span class="hljs-function">(<span class="hljs-params">accumulator, item</span>) =&gt;</span> {

}, {})
</code></pre>
<p>Next, you check if the accumulator object already has a property with the same name as the <code>category</code> from your <code>item</code> object.</p>
<p>If not, then declare that property as an empty array as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> category = item.category;
<span class="hljs-keyword">if</span> (!accumulator[category]) {
  accumulator[category] = []
}
</code></pre>
<p>After that, push the <code>item.name</code> property to the <code>accumulator[category]</code> property, and return the <code>accumulator</code> like this:</p>
<pre><code class="lang-js">accumulator[category].push(item.name);
<span class="hljs-keyword">return</span> accumulator
</code></pre>
<p>And that’s it. Now you have an object that groups the items based on the <code>category</code> value:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> items = [
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Apple'</span>, <span class="hljs-attr">category</span>: <span class="hljs-string">'Fruit'</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Onion'</span>, <span class="hljs-attr">category</span>: <span class="hljs-string">'Vegetable'</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Orange'</span>, <span class="hljs-attr">category</span>: <span class="hljs-string">'Fruit'</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Lettuce'</span>, <span class="hljs-attr">category</span>: <span class="hljs-string">'Vegetable'</span> },
];

<span class="hljs-keyword">const</span> groupedItems = items.reduce(<span class="hljs-function">(<span class="hljs-params">accumulator, item</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> category = item.category;
  <span class="hljs-keyword">if</span> (!accumulator[category]) {
    accumulator[category] = []
  }
  accumulator[category].push(item.name);
  <span class="hljs-keyword">return</span> accumulator
}, {})

<span class="hljs-built_in">console</span>.log(groupedItems);
<span class="hljs-comment">// { Fruit: [ 'Apple', 'Orange' ], Vegetable: [ 'Onion', 'Lettuce' ] }</span>
</code></pre>
<p>Next, let’s see how to remove duplicates using the <code>reducer()</code> method:</p>
<h3 id="heading-how-to-remove-duplicates-using-the-reduce-method">How to Remove Duplicates Using the <code>reduce()</code> Method</h3>
<p>To remove duplicates using the <code>reduce()</code> method, you need to declare an array as the <code>accumulator</code> value.</p>
<p>In each iteration, check if the <code>item</code> is already included in the <code>accumulator</code> using the <code>includes()</code> method.</p>
<p>If the <code>item</code> isn’t already included, push the <code>item</code> into the <code>accumulator</code>. See the example below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> items = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">7</span>];

<span class="hljs-keyword">const</span> noDuplicateItems = items.reduce(<span class="hljs-function">(<span class="hljs-params">accumulator, item</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (!accumulator.includes(item)) {
    accumulator.push(item);
  }
  <span class="hljs-keyword">return</span> accumulator;
}, []);

<span class="hljs-built_in">console</span>.log(noDuplicateItems); 
<span class="hljs-comment">// [ 1, 2, 3, 7, 8 ]</span>
</code></pre>
<p>Here, you can see that the <code>reduce()</code> method returns an array (without any duplicates) instead of a single value.</p>
<h2 id="heading-why-the-initial-accumulator-value-is-important">Why the Initial Accumulator Value is Important</h2>
<p>In all the examples above, you’ve seen how we added an initial value for the accumulator as the second argument passed to the <code>reduce()</code> method.</p>
<p>If you don’t add the initial accumulator value, then <code>reduce()</code> will take the first item in your array as the initial accumulator value.</p>
<p>You can test this by logging the <code>accumulator</code> value inside the callback function as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> items = [
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Apple'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">1</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Orange'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">2</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Mango'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">3</span> },
];

<span class="hljs-keyword">const</span> totalPrice = items.reduce(<span class="hljs-function">(<span class="hljs-params">accumulator ,item</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(accumulator); <span class="hljs-comment">// log the accumulator</span>
  <span class="hljs-keyword">return</span> accumulator += item.price;
}, <span class="hljs-number">0</span>)
</code></pre>
<p>Run the code above, and you’ll get the following result:</p>
<pre><code class="lang-txt">0
1
3
</code></pre>
<p>In the first iteration, the <code>accumulator</code> uses the initial value we passed as the second argument to the <code>reduce()</code> method, which is a <code>0</code>.</p>
<p>If you remove <code>0</code> from the code, then the output will be:</p>
<pre><code class="lang-txt">{ name: 'Apple', price: 1 }
[object Object]2
</code></pre>
<p>Because we didn’t provide an initial value for the <code>accumulator</code>, the method takes whatever value we placed at index 0 as the initial value of the <code>accumulator</code>.</p>
<p>Depending on the content of your array, the initial value can be an object, an array, or a single value. Relying on the value of the array as the initial accumulator value is considered bad practice as it can lead to bugs, so you should always define the initial accumulator value.</p>
<h2 id="heading-full-reduce-callback-parameters">Full <code>reduce()</code> Callback Parameters</h2>
<p>One more thing before we conclude the article. In all examples above, we define 2 parameters for the callback function, but the <code>reduce()</code> method actually passes 4 arguments to the callback function:</p>
<ul>
<li>The <code>accumulator</code> value</li>
<li>The <code>item</code> value</li>
<li>The <code>index</code> of the current item in iteration</li>
<li>The <code>array</code> from which you call the method itself</li>
</ul>
<p>The full syntax of the method is as follows:</p>
<pre><code class="lang-js"><span class="hljs-built_in">Array</span>.reduce(<span class="hljs-function">(<span class="hljs-params">accumulator, item, index, array</span>) =&gt;</span> {
  <span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> Define the process for each iteration here</span>
}, initialAccumulatorValue)
</code></pre>
<p>In most cases, you only need the first two parameters, but if you somehow need the index and array values, they are always available.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>And there you have it! At first sight, the <code>reduce()</code> method looks more complicated than other JavaScript array methods like <code>forEach()</code> and <code>filter()</code>. But once you understand the concept of reducer and accumulator, the method is actually quite simple.</p>
<p>In programming terms, a “reducer” function always returns a single value, so the <code>reduce()</code> method iterates over the values defined in your array and reduces them into a single value.</p>
<p>Inside the callback function of the <code>reduce()</code> method, you can do any kind of operation you need to achieve a certain result, such as summarizing and grouping certain values, or removing duplicates.</p>
<p>This is done with the help of the “accumulator”, which stores the value returned from the previous iteration. You set the initial value of the accumulator by passing a second argument to the <code>reduce()</code> method.</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G">here</a>.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How JavaScript Promises Work – Tutorial for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this article, I’m going to teach you one of the most confusing JavaScript topics, which is the Promise object. Promises may seem difficult at first, but they're actually quite simple once you understand how they work. Here's what we'l... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-promise-object-explained/</link>
                <guid isPermaLink="false">66bd918c621c718d60a3106f</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Wed, 29 Nov 2023 15:55:31 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/js-promise.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this article, I’m going to teach you one of the most confusing JavaScript topics, which is the Promise object. Promises may seem difficult at first, but they're actually quite simple once you understand how they work.</p>
<p>Here's what we'll cover:</p>
<ol>
<li><a class="post-section-overview" href="#heading-how-a-promise-works">How a Promise Works</a></li>
<li><a class="post-section-overview" href="#heading-callbacks-vs-promises">Callbacks vs Promises</a></li>
<li><a class="post-section-overview" href="#heading-when-to-use-promises-instead-of-callbacks">When to Use Promises Instead of Callbacks</a></li>
<li><a class="post-section-overview" href="#heading-promises-and-the-fetch-api">Promises and the Fetch API</a></li>
<li><a class="post-section-overview" href="#heading-the-promiseall-method">The <code>Promise.all()</code> Method</a></li>
<li><a class="post-section-overview" href="#heading-the-promiseallsettled-method">The <code>Promise.allSettled()</code> Method</a></li>
<li><a class="post-section-overview" href="#heading-the-promiseany-method">The <code>Promise.any()</code> Method</a></li>
<li><a class="post-section-overview" href="#heading-the-promiserace-method">The <code>Promise.race()</code> Method</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-how-a-promise-works">How a Promise Works</h2>
<p>Basically, a <code>Promise</code> object represents a “pending state” in the most common sense: the promise will eventually be fulfilled at a later date.</p>
<p>To give you an illustration, suppose you want to buy a new phone to replace your old phone, so you open a messaging app to contact a phone store. This is similar to how you access a variable or a function that returns a promise:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/access-a-promise.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration 1: Sending a message to a store is like how you access a Promise object in JavaScript</em></p>
<p>After you send a message explaining what you want, you get an automated message saying that a representative will answer your message shortly. This is similar to receiving a Promise object:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/promise-pending-state.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration 2: An automated message from the store you contacted before. This is the Promise object that you receive in JavaScript</em></p>
<p>A minute later, you get a new message from a human representative, saying that the phone model you want to buy is available for purchase. This is when the Promise was resolved:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/promise-resolved.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration 3: A store representative replied to your message. This is like when a Promise gets resolved</em></p>
<p>Or, in a completely different scenario, the representative tells you that the store doesn’t sell phones, because the store is a food store and not a phone store. This means the Promise was rejected:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/promise-rejected.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration 4: The representative replied that the store doesn't sell phones. This is like when a Promise gets rejected</em></p>
<p>This illustration shows how the <code>Promise</code> object in JavaScript works:</p>
<ul>
<li>A Promise is like the automated message that we saw earlier. It represents a pending state that must be fulfilled at some point later.</li>
<li>The human representative saying that the phone model is available is similar to the <code>resolve()</code> method, which shows that the Promise is fulfilled.</li>
<li>The representative telling you that you’re contacting the wrong store is like the <code>reject()</code> method, which is the method used to show that the Promise can’t be fulfilled because of an error.</li>
</ul>
<p>A typical promise implementation looks like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> p = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> isTrue = <span class="hljs-literal">true</span>;
  <span class="hljs-keyword">if</span> (isTrue) {
    resolve(<span class="hljs-string">'Promise resolved'</span>);
  } <span class="hljs-keyword">else</span> {
    reject(<span class="hljs-string">'Promise rejected'</span>);
  }
});
</code></pre>
<p>When creating a new Promise object, we need to pass a callback function that will be called immediately with two arguments: the <code>resolve()</code> and <code>reject()</code> functions.</p>
<p>Depending on the result of the <code>Promise</code>, either the <code>resolve()</code> or the <code>reject()</code> function will be called to end the pending state.</p>
<p>To handle the <code>Promise</code> object, you need to chain the function call with the <code>then()</code> and <code>catch()</code> functions as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> p = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> isTrue = <span class="hljs-literal">true</span>;
  <span class="hljs-keyword">if</span> (isTrue) {
    resolve(<span class="hljs-string">'Success'</span>);
  } <span class="hljs-keyword">else</span> {
    reject(<span class="hljs-string">'Error'</span>);
  }
});

p
.then(<span class="hljs-function"><span class="hljs-params">message</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Promise resolved: <span class="hljs-subst">${message}</span>`</span>))
.catch(<span class="hljs-function"><span class="hljs-params">message</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Promise rejected: <span class="hljs-subst">${message}</span>`</span>));
</code></pre>
<p>The <code>resolve()</code> function corresponds to the <code>then()</code> function, while <code>reject()</code> corresponds to the <code>catch()</code> function. You can change the <code>isTrue</code> value to <code>false</code> to test this.</p>
<p>Here’s an illustration of the promise process:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/promise-object--1-.png" alt="Image" width="600" height="400" loading="lazy">
<em>The Process happening inside a Promise. Depending on the code run inside the Promise, it will settle as resolved or rejected.</em></p>
<p>Using the promise pattern, you can call your functions sequentially by placing the next process inside the <code>then()</code> or <code>catch()</code> methods.</p>
<h2 id="heading-callbacks-vs-promises">Callbacks vs Promises</h2>
<p>The promise pattern was created to replace the use of callbacks in certain situations. By using promises, the code we write is more intuitive and maintainable.</p>
<p>Going back to the messaging illustration, let’s create an example of using callbacks to handle the situation. </p>
<p>First, we declare the two variables required for this situation, called <code>isPhoneStore</code> and <code>isPhoneAvailable</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> isPhoneStore = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> isPhoneAvailable = <span class="hljs-literal">true</span>;
</code></pre>
<p>Next, we write a function that will process incoming messages. This function will mimic the promise pattern, and it will resolve only when <code>isPhoneStore</code> and <code>isPhoneAvailable</code> are <code>true</code>:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processMessage</span>(<span class="hljs-params">resolveCallback, rejectCallback</span>) </span>{
  <span class="hljs-keyword">if</span> (!isPhoneStore) {
    rejectCallback({
      <span class="hljs-attr">name</span>: <span class="hljs-string">'Wrong store'</span>,
      <span class="hljs-attr">message</span>: <span class="hljs-string">'Sorry, this is a food store!'</span>,
    });
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (!isPhoneAvailable) {
    rejectCallback({
      <span class="hljs-attr">name</span>: <span class="hljs-string">'Out of stock'</span>,
      <span class="hljs-attr">message</span>: <span class="hljs-string">'Sorry, the X phone is out of stock!'</span>,
    });
  } <span class="hljs-keyword">else</span> {
    resolveCallback({
      <span class="hljs-attr">name</span>: <span class="hljs-string">'OK'</span>,
      <span class="hljs-attr">message</span>: <span class="hljs-string">'The X phone is available! How many you want to buy?'</span>,
    });
  }
}
</code></pre>
<p>Here, you can see that the function <code>processMessage</code> accepts two callback functions: <code>resolveCallback</code> and <code>rejectCallback</code>.</p>
<p>When we call the function, we need to provide the callback functions, similar to how we need to chain the <code>then()</code> and <code>catch()</code> methods when accessing a promise:</p>
<pre><code class="lang-js">processMessage(
  <span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(value),
  <span class="hljs-function"><span class="hljs-params">reason</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(reason)
);
</code></pre>
<p>In the call to <code>processMessage</code> above, the first argument is the <code>resolveCallback()</code> function, and the second argument is the <code>rejectCallback()</code> function.</p>
<p>If you run the code above, then the <code>resolveCallback()</code> function will be called. You can change one of the two variables to <code>false</code> to trigger the <code>rejectCallback()</code> function.</p>
<p>Now that we have a working callback example, let’s rewrite the code using a promise as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> isPhoneStore = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> isPhoneAvailable = <span class="hljs-literal">true</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processMessage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (!isPhoneStore) {
      reject({
        <span class="hljs-attr">name</span>: <span class="hljs-string">'Wrong store'</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">'Sorry, this is a food store!'</span>,
      });
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (!isPhoneAvailable) {
      reject({
        <span class="hljs-attr">name</span>: <span class="hljs-string">'Out of stock'</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">'Sorry, the X phone is out of stock!'</span>,
      });
    } <span class="hljs-keyword">else</span> {
      resolve({
        <span class="hljs-attr">name</span>: <span class="hljs-string">'OK'</span>,
        <span class="hljs-attr">message</span>: <span class="hljs-string">'The X phone is available! How many you want to buy?'</span>,
      });
    }
  });
}

processMessage()
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(error));
</code></pre>
<p>Here, you can see that the <code>processMessage()</code> function returns a <code>Promise</code> object that gets resolved only when both <code>isPhoneStore</code> and <code>isPhoneAvailable</code> are <code>true</code>.</p>
<p>When one of the two variables is <code>false</code>, then the <code>Promise</code> object will be rejected.</p>
<p>Here you can see that you don’t need to add two extra parameters to the <code>processMessage()</code> function just for the callbacks. Also, when calling the function, you use the <code>then()</code> and <code>catch()</code> methods to handle the result of the promise.</p>
<p>The use of a promise makes the code easier to understand. Here’s the comparison of the two side by side:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/11/callback-vs-promise.png" alt="Image" width="600" height="400" loading="lazy">
<em>Callbacks vs Promises code comparison</em></p>
<p>I don’t know about you, but I sure love writing and reading the promise pattern more than the callback pattern. 😉</p>
<h3 id="heading-when-to-use-promises-instead-of-callbacks">When to Use Promises Instead of Callbacks</h3>
<p>As I've mentioned before, the promise object is created to replace callback functions in certain situations.</p>
<p>And if you examine the code for the promise object above closely, you'll see that even promises use callbacks inside the <code>then()</code> and <code>catch()</code> methods. This means Promises don't eliminate the need for callbacks.</p>
<p>Promises are used when you need to wait for a certain task to finish before running the next process.</p>
<p>For example, suppose you have three functions that need to run sequentially from one to three.</p>
<p>Each function runs for a few seconds. We simulate this using the <code>setTimeout()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepOne</span>(<span class="hljs-params">value</span>)</span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(value);
  }, <span class="hljs-number">3000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepTwo</span>(<span class="hljs-params">value</span>)</span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(value);
  }, <span class="hljs-number">2000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepThree</span>(<span class="hljs-params">value</span>)</span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(value);
  }, <span class="hljs-number">1000</span>);
}
</code></pre>
<p>Using callbacks, you can define parameters on the <code>stepOne()</code> and <code>stepTwo()</code> functions, then call those functions sequentially like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepOne</span>(<span class="hljs-params">value, callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(value);
    callback();
  }, <span class="hljs-number">3000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepTwo</span>(<span class="hljs-params">value, callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(value);
    callback();
  }, <span class="hljs-number">2000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepThree</span>(<span class="hljs-params">value, callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(value);
    callback();
  }, <span class="hljs-number">1000</span>);
}

<span class="hljs-comment">// Run the functions sequentially with callbacks</span>
stepOne(<span class="hljs-number">1</span>, <span class="hljs-function">() =&gt;</span> {
  stepTwo(<span class="hljs-number">2</span>, <span class="hljs-function">() =&gt;</span> {
    stepThree(<span class="hljs-number">3</span>, <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"All steps completed."</span>);
    });
  });
});
</code></pre>
<p>The nested callbacks where you pass the next function inside the previous function is famously known as the "callback hell". This code pattern is hard to read and it's messy.</p>
<p>With promises, you can rewrite the code above as follows:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepOne</span>(<span class="hljs-params">value</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(value);
      resolve();
    }, <span class="hljs-number">3000</span>);
  });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepTwo</span>(<span class="hljs-params">value</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(value);
      resolve();
    }, <span class="hljs-number">2000</span>);
  });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">stepThree</span>(<span class="hljs-params">value</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(value);
      resolve();
    }, <span class="hljs-number">1000</span>);
  });
}

<span class="hljs-comment">// Run the functions sequentially with Promises</span>
stepOne(<span class="hljs-number">1</span>)
  .then(<span class="hljs-function">() =&gt;</span> stepTwo(<span class="hljs-number">2</span>))
  .then(<span class="hljs-function">() =&gt;</span> stepThree(<span class="hljs-number">3</span>))
  .then(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"All steps completed."</span>);
  });
</code></pre>
<p>Here, you can see that each function returns a promise that resolves when the timeout is finished. The function calls using <code>then()</code> methods maintain a clear order of steps.</p>
<p>In a real-world project where you have many lines of code inside the callback functions, using Promises provides a massive gain in your ability to read, extend, and maintain the code.</p>
<p>But if you're running code that doesn't have to wait for certain processes, then you can use callbacks just fine.</p>
<p>For example, the array methods like <code>forEach()</code> use callbacks, so there's no need for promises there:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];

myArray.forEach(<span class="hljs-function"><span class="hljs-params">value</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(value + <span class="hljs-number">5</span>));
</code></pre>
<p>Another use of promises is when you use the Fetch API, which is used to run network requests. Let's see how that works now.</p>
<h2 id="heading-promises-and-the-fetch-api">Promises and the Fetch API</h2>
<p>The Fetch API always returns a <code>Promise</code> object, so you need to handle it using the <code>then()</code> and <code>catch()</code> methods as shown below:</p>
<pre><code class="lang-js">fetch(<span class="hljs-string">'&lt;Your API URL&gt;'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(error));
</code></pre>
<p>If you run a <code>fetch()</code> function and assign the result to a variable, the variable will contain a <code>Promise</code> object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> response = fetch(<span class="hljs-string">'&lt;Your API URL&gt;'</span>);
<span class="hljs-built_in">console</span>.log(response); <span class="hljs-comment">// Promise {&lt;pending&gt;}</span>
</code></pre>
<p>As you can see, the <code>Promise</code> object is assigned to the <code>response</code> variable in a pending state. If you wait a while and then log the object again, the output will be fulfilled:</p>
<pre><code class="lang-txt">Promise {&lt;fulfilled&gt;: Response}
</code></pre>
<p>The Fetch API will return a <code>Response</code> object when the promise is fulfilled. This is also why I usually name the parameter inside the <code>then()</code> method as <code>response</code> . Feel free to name the response as <code>message</code> , <code>value</code> , or anything your team agreed on.</p>
<p>Now that you’ve learned how the <code>Promise</code> object works, it’s time to learn some extra methods related to this object.</p>
<h3 id="heading-the-promiseall-method">The <code>Promise.all()</code> method</h3>
<p>More than just replacing the callback pattern, JavaScript also provides some methods that you can use to work with <code>Promise</code> objects. For example, suppose you deal with three different promises in your project like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p1 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">'Success'</span>);
<span class="hljs-keyword">const</span> p2 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">200</span>);
<span class="hljs-keyword">const</span> p3 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">'Finished'</span>);
</code></pre>
<p>Now, suppose you need all three promises to resolve before moving to the next step. Knowing what we know about promises, we can chain the promises using the <code>then()</code> method like this:</p>
<pre><code class="lang-js">p1.then(<span class="hljs-function"><span class="hljs-params">message1</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> p2.then(<span class="hljs-function"><span class="hljs-params">message2</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> p3.then(<span class="hljs-function"><span class="hljs-params">message3</span> =&gt;</span> {
      <span class="hljs-keyword">return</span> [message1, message2, message3];
    });
  });
}).then(<span class="hljs-function"><span class="hljs-params">messages</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(messages);
});
</code></pre>
<p>In this example, each <code>then()</code> method returns another promise, creating nested callbacks. When the <code>p3</code> promise is resolved, the messages are returned as a single array.</p>
<p>The last <code>then()</code> method would then log the <code>messages</code> array returned by the promises. This approach works, but this is exactly the type of code we want to avoid when using promises.</p>
<p>Instead of using nested callbacks, we can use the <code>Promise.all()</code> method instead. See the example below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p1 = <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">'Error From Promise One'</span>);
<span class="hljs-keyword">const</span> p2 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">200</span>);
<span class="hljs-keyword">const</span> p3 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">'Finished'</span>);

<span class="hljs-built_in">Promise</span>.all([p1, p2, p3])
  .then(<span class="hljs-function"><span class="hljs-params">messages</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(messages))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(error));
</code></pre>
<p>The <code>Promise.all()</code> method accepts an array of promises, and when all promises are resolved, the method will pass the <code>messages</code> returned by the promises as an array and pass it to the <code>then()</code> method.</p>
<p>If one of the promises is rejected, then the method returns the first rejection it encounters and stops any further process.</p>
<p>This method enables you to work with many promises without having to create nested callbacks. You should use this method when you need all promises to resolve.</p>
<h3 id="heading-the-promiseallsettled-method">The <code>Promise.allSettled()</code> method</h3>
<p>The <code>Promise.allSettled()</code> method is similar to the <code>Promise.all()</code> method, but instead of  proceeding to <code>catch()</code> when one of the promises got rejected, the method will store the reject result and continue processing other promises.</p>
<p>When all promises are settled, the method will return an array of objects that contains the details of each promise. For example, suppose you run the following code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p1 = <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">'Error From Promise One'</span>);
<span class="hljs-keyword">const</span> p2 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">200</span>);
<span class="hljs-keyword">const</span> p3 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">'Finished'</span>);

<span class="hljs-built_in">Promise</span>.allSettled([p1, p2, p3]).then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(response);
});
</code></pre>
<p>Then the result would be:</p>
<pre><code class="lang-txt">[
  { status: 'rejected', reason: 'Error From Promise One' },
  { status: 'fulfilled', value: 200 },
  { status: 'fulfilled', value: 'Finished' }
]
</code></pre>
<p>As you can see, the <code>response</code> variable is an array of objects showing the status and the value or reason for that status. When calling this method, you don't need to chain the <code>catch()</code> method.</p>
<p>You should use this method when you always need to know the result of each promise.</p>
<h3 id="heading-the-promiseany-method">The <code>Promise.any()</code> method</h3>
<p>The <code>Promise.any()</code> method is similar to the <code>Promise.all()</code> method, except that it returns only a single value from any promise that calls the <code>resolve()</code> function first. If you try the method as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p1 = <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">'Error From Promise One'</span>);
<span class="hljs-keyword">const</span> p2 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">200</span>);
<span class="hljs-keyword">const</span> p3 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">'Finished'</span>);

<span class="hljs-built_in">Promise</span>.any([p1, p2, p3]).then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(response);
});
</code></pre>
<p>The output will be:</p>
<pre><code class="lang-txt">200
</code></pre>
<p>This is because the first promise is rejected, and once the second promise is resolved, the <code>any()</code> method stops any further execution of promises and returns the resolved value.</p>
<p>This method returns an error only when all promises are rejected. You should use this method only when you need to get a single promise resolved out of many promises.</p>
<h3 id="heading-the-promiserace-method">The <code>Promise.race()</code> method</h3>
<p>The <code>Promise.race()</code> method is like the <code>Promise.any()</code> method, with one difference: the promise is settled when any promise is resolved or rejected:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p1 = <span class="hljs-built_in">Promise</span>.reject(<span class="hljs-string">'Error From Promise One'</span>);
<span class="hljs-keyword">const</span> p2 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-number">200</span>);
<span class="hljs-keyword">const</span> p3 = <span class="hljs-built_in">Promise</span>.resolve(<span class="hljs-string">'Finished'</span>);

<span class="hljs-built_in">Promise</span>.race([p1, p2, p3])
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response))
  .catch(<span class="hljs-function"><span class="hljs-params">reason</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(reason));
</code></pre>
<p>Since <code>p1</code> returns a rejection, then the <code>Promise.race()</code> method returns the rejection instead of continuing the process:</p>
<pre><code class="lang-txt">Error From Promise One
</code></pre>
<p>You should use this method only when you need to get a single promise to settle, no matter if the result is resolved or rejected.</p>
<p>As you can see, these four methods of the <code>Promise</code> object provides you with a powerful composition tool that helps you decide how to handle multiple promises in your project.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>And now you’ve learned how the <code>Promise</code> object works in JavaScript. A promise is easy to understand when you grasp the three states that can be generated by the promise: pending, resolved, and rejected.</p>
<p>You’ve also learned how promises can be used to replace callbacks, when to use promises instead of callbacks, and how to use promise methods when you need to handle many promises in your project.</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G">here</a>.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Array Handbook – Learn How JS Array Methods Work With Examples and Cheat Sheet ]]>
                </title>
                <description>
                    <![CDATA[ In programming, an array is a data structure that contains a collection of elements. Arrays are very useful because you can store, access, and manipulate multiple elements in a single array. In this handbook, you'll learn how to work with arrays in J... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-array-handbook/</link>
                <guid isPermaLink="false">66bd916cffb0fc5947cc9137</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Thu, 31 Aug 2023 14:22:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/JavaScript-Array-for-Beginners-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In programming, an array is a data structure that contains a collection of elements. Arrays are very useful because you can store, access, and manipulate multiple elements in a single array.</p>
<p>In this handbook, you'll learn how to work with arrays in JavaScript. We'll cover the specific rules you need to follow when creating an array, as well as how to use array methods to manipulate and transform your array as desired.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-how-arrays-work-in-javascript">How Arrays Work in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-an-array-in-javascript">How to Create an Array in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-how-to-access-an-arrays-elements">How to Access an Array's Elements</a></li>
<li><a class="post-section-overview" href="#heading-the-array-length-property">The Array length Property</a></li>
<li><a class="post-section-overview" href="#heading-how-to-add-elements-to-an-array">How to Add Elements to an Array</a></li>
<li><a class="post-section-overview" href="#heading-how-to-remove-an-element-from-an-array">How to Remove an Element from an Array</a></li>
<li><a class="post-section-overview" href="#heading-how-to-check-if-a-variable-is-an-array">How To Check If a Variable is an Array</a></li>
<li><a class="post-section-overview" href="#heading-how-to-iterate-or-loop-over-an-array">How to Iterate or Loop Over an Array</a></li>
<li><a class="post-section-overview" href="#heading-how-to-convert-an-array-into-a-string">How to Convert an Array into a String</a></li>
<li><a class="post-section-overview" href="#heading-how-to-compare-two-arrays">How to Compare Two Arrays</a></li>
<li><a class="post-section-overview" href="#heading-how-to-copy-an-array">How to Copy an Array</a></li>
<li><a class="post-section-overview" href="#how-to-merge-two-arrays-as-one">How to Merge Two Arrays as One</a></li>
<li><a class="post-section-overview" href="#heading-how-to-search-an-array">How to Search an Array</a></li>
<li><a class="post-section-overview" href="#heading-how-to-sort-an-array">How to Sort an Array</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-multi-dimensional-arrays">How to Create Multi-dimensional Arrays</a></li>
<li><a class="post-section-overview" href="#heading-javascript-array-methods-cheat-sheet">JavaScript Array Methods Cheat Sheet</a></li>
<li><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></li>
</ol>
<h2 id="heading-how-arrays-work-in-javascript">How Arrays Work in JavaScript</h2>
<p>In JavaScript, an array is implemented as an object that can have a group of items, elements, or values as an ordered collection. This means you can access an array's element using its position in the collection. You'll see why this is important in the next section.</p>
<p>An array can hold elements of different data types, and the size of the array is not fixed. This means that you can add as many elements to an array as you want.</p>
<h2 id="heading-how-to-create-an-array-in-javascript">How to Create an Array in JavaScript</h2>
<p>There are two ways you can create an array in JavaScript:</p>
<ul>
<li>Using the square brackets <code>[]</code></li>
<li>Using the <code>Array()</code> constructor</li>
</ul>
<p>The square brackets <code>[]</code> is a literal notation used to create an array. The array elements are defined inside the brackets, with each element separated using a comma <code>,</code>.</p>
<p>The following example shows how to create an array named <code>myArray</code> that has three elements of different types: a Number, a String, and a Boolean.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">29</span>, <span class="hljs-string">'Nathan'</span>, <span class="hljs-literal">true</span>];
</code></pre>
<p>And here's how to create an array with 3 number elements:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myNumbers = [<span class="hljs-number">5</span>, <span class="hljs-number">10</span>, <span class="hljs-number">15</span>];
</code></pre>
<p>You can specify as many elements as you want inside the square brackets.</p>
<p>Another way to create an array is to use the <code>Array()</code> constructor, which works like the square brackets:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myArray = <span class="hljs-built_in">Array</span>(<span class="hljs-number">29</span>, <span class="hljs-string">'Nathan'</span>, <span class="hljs-literal">true</span>);

<span class="hljs-comment">// or</span>
<span class="hljs-keyword">let</span> myNumbers = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>, <span class="hljs-number">15</span>);
</code></pre>
<p>Note that the constructor function can be called with or without the <code>new</code> operator. Both create an array object just fine.</p>
<p>In most code examples and codebases, you'll most likely see developers use the square brackets to create an array instead of using the constructor. This is because it's faster to type <code>[]</code> instead of <code>Array()</code>.</p>
<h2 id="heading-how-to-access-an-arrays-elements">How to Access an Array's Elements</h2>
<p>As I've said before, an array is an ordered collection, so you can access an element from its position (also known as index number) in the array.</p>
<p>To access an array's element, you need to specify the array name followed by square brackets. Inside the square brackets, specify the index of the element you want to access.</p>
<p>For example, here's how you access the first element of <code>myArray</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">29</span>, <span class="hljs-string">'Nathan'</span>, <span class="hljs-literal">true</span>];

<span class="hljs-built_in">console</span>.log(myArray[<span class="hljs-number">0</span>]); <span class="hljs-comment">// 29</span>
<span class="hljs-built_in">console</span>.log(myArray[<span class="hljs-number">1</span>]); <span class="hljs-comment">// Nathan</span>
<span class="hljs-built_in">console</span>.log(myArray[<span class="hljs-number">2</span>]); <span class="hljs-comment">// true</span>
</code></pre>
<p>The array index number starts from 0 and increases by 1 for each element added to the array.</p>
<p>If you try to access an index number that hasn't been assigned any value yet, JavaScript will return <code>undefined</code> as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">29</span>, <span class="hljs-string">'Nathan'</span>, <span class="hljs-literal">true</span>];

<span class="hljs-built_in">console</span>.log(myArray[<span class="hljs-number">3</span>]); <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(myArray[<span class="hljs-number">4</span>]); <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(myArray[<span class="hljs-number">100</span>]); <span class="hljs-comment">// undefined</span>
</code></pre>
<p>You can also replace an element on a certain index number with a new element by using the assignment <code>=</code> operator.</p>
<p>The following example shows how to replace the third element (boolean) with a string:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">29</span>, <span class="hljs-string">'Nathan'</span>, <span class="hljs-literal">true</span>];

<span class="hljs-comment">// Replace the third element</span>
myArray[<span class="hljs-number">2</span>] = <span class="hljs-string">'Sebhastian'</span>;

<span class="hljs-built_in">console</span>.log(myArray); <span class="hljs-comment">// [ 29, 'Nathan', 'Sebhastian' ]</span>
</code></pre>
<p>In the example above, you can see that the <code>true</code> boolean value is replaced with the string 'Sebhastian'. Next, let's take a look at the <code>length</code> property.</p>
<h2 id="heading-the-array-length-property">The Array <code>length</code> Property</h2>
<p>The <code>length</code> property shows how many elements an array has. You can access this property using the dot <code>.</code> notation as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">29</span>, <span class="hljs-string">'Nathan'</span>, <span class="hljs-literal">true</span>];

<span class="hljs-built_in">console</span>.log(myArray.length); <span class="hljs-comment">// 3</span>

<span class="hljs-keyword">let</span> animals = [<span class="hljs-string">'Dog'</span>, <span class="hljs-string">'Cat'</span>];

<span class="hljs-built_in">console</span>.log(animals.length); <span class="hljs-comment">// 2</span>
</code></pre>
<p>The <code>length</code> property is updated each time you add or remove elements from an array.</p>
<h2 id="heading-how-to-add-elements-to-an-array">How to Add Elements to an Array</h2>
<p>To add one or more elements to an array, you can use the array <code>push()</code> and <code>unshift()</code> methods.</p>
<p>The <code>push()</code> method adds new elements to the end of the array, while the <code>unshift()</code> method inserts new elements at the start of the array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [<span class="hljs-string">'Dog'</span>, <span class="hljs-string">'Cat'</span>];

animals.push(<span class="hljs-string">'Horse'</span>, <span class="hljs-string">'Fish'</span>);

<span class="hljs-built_in">console</span>.log(animals);
<span class="hljs-comment">// [ 'Dog', 'Cat', 'Horse', 'Fish' ]</span>

animals.unshift(<span class="hljs-string">'Bird'</span>);

<span class="hljs-built_in">console</span>.log(animals);
<span class="hljs-comment">// [ 'Bird', 'Dog', 'Cat', 'Horse', 'Fish' ]</span>
</code></pre>
<p>Here, notice that you can use a comma to separate the elements you want to add to the array.</p>
<p>Next, let's see how you can remove elements from an array.</p>
<h2 id="heading-how-to-remove-an-element-from-an-array">How to Remove an Element from an Array</h2>
<p>To remove an element from an array, you can use the <code>shift()</code> and <code>pop()</code> methods, depending on the position of the element you want to remove.</p>
<p>Use the <code>shift()</code> method to remove the first element, and use <code>pop()</code> to remove the last element in the array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [<span class="hljs-string">'Dog'</span>, <span class="hljs-string">'Cat'</span>, <span class="hljs-string">'Horse'</span>, <span class="hljs-string">'Fish'</span>];

animals.shift();

<span class="hljs-built_in">console</span>.log(animals);
<span class="hljs-comment">// [ 'Cat', 'Horse', 'Fish' ]</span>

animals.pop();

<span class="hljs-built_in">console</span>.log(animals);
<span class="hljs-comment">// [ 'Cat', 'Horse' ]</span>
</code></pre>
<p>Both <code>shift()</code> and <code>pop()</code> can only remove one element at a time. If you want to remove an element in the middle of an array, you need to use the <code>splice()</code> method.</p>
<h3 id="heading-how-to-use-splice-to-remove-or-add-elements">How to Use <code>splice()</code> to Remove or Add Element(s)</h3>
<p>The array <code>splice()</code> method is used to remove or add elements at specific positions. You use this method when <code>push</code>, <code>pop</code>, <code>shift</code>, and <code>unshift</code> can't get the job done.</p>
<p>To remove elements using the <code>splice()</code> method, you need to specify two arguments: the index number to start array manipulation, and the number of elements to delete.</p>
<p>For example, suppose you want to delete two elements at index 1 and 2 in the <code>animals</code> array. Here's how you do it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [<span class="hljs-string">'Dog'</span>, <span class="hljs-string">'Cat'</span>, <span class="hljs-string">'Horse'</span>, <span class="hljs-string">'Fish'</span>];

animals.splice(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);

<span class="hljs-built_in">console</span>.log(animals);
<span class="hljs-comment">// [ 'Dog', 'Fish' ]</span>
</code></pre>
<p>The <code>splice(1, 2)</code> means start array manipulation at index 1, then delete 2 elements from there.</p>
<p>To add elements using <code>splice()</code>, you need to specify the elements to add after the second argument.</p>
<p>For example, here I add a string value 'Bird' and 'Squid' at index 1:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [<span class="hljs-string">'Dog'</span>, <span class="hljs-string">'Cat'</span>];

animals.splice(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'Bird'</span>, <span class="hljs-string">'Squid'</span>);

<span class="hljs-built_in">console</span>.log(animals);
<span class="hljs-comment">// [ 'Dog', 'Bird', 'Squid', 'Cat' ]</span>
</code></pre>
<p>If you don't want to delete any elements, you can pass <code>0</code> as the second argument to the <code>splice()</code> method. You then specify the elements you want to add.</p>
<p>The <code>splice()</code> method can be confusing the first time you see it, but don't worry! You'll memorize how it works with more practice.</p>
<h2 id="heading-how-to-check-if-a-variable-is-an-array">How to Check if a Variable is an Array</h2>
<p>To check if a variable is an array, you can use the <code>Array.isArray()</code> method which tests whether the argument given to the method is an array or not.</p>
<p>This method returns <code>true</code> when you pass an array to it, and <code>false</code> for anything else:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myArray = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> notAnArray = <span class="hljs-string">'Hello!'</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Array</span>.isArray(myArray)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Array</span>.isArray(notAnArray)); <span class="hljs-comment">// false</span>
</code></pre>
<p>Note that you need to specify the <code>Array</code> class when calling the <code>isArray()</code> method.</p>
<p>This is because <code>isArray()</code> is a static method, so you can only call it directly from the class that defines the method.</p>
<h2 id="heading-how-to-iterate-or-loop-over-an-array">How to Iterate or Loop Over an Array</h2>
<p>There are 4 ways you can iterate over an array in JavaScript, depending on the method you use:</p>
<ol>
<li>Using a <code>for</code> loop</li>
<li>Using a <code>while</code> loop</li>
<li>Using the <code>for...in</code> loop</li>
<li>Using the <code>for...of</code> loop</li>
<li>Using the <code>forEach()</code> method</li>
</ol>
<p>Let's learn how to use these 4 methods with examples.</p>
<h3 id="heading-1-how-to-use-a-for-loop">1. How to use a for loop</h3>
<p>To iterate over an array using a <code>for</code> loop, you need to use the array <code>length</code> as the condition expression.</p>
<p>In the following example, a <code>for</code> loop will continue to run as long as the variable <code>i</code> is less than the array's length:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [<span class="hljs-string">'dog'</span>, <span class="hljs-string">'bird'</span>, <span class="hljs-string">'cat'</span>, <span class="hljs-string">'horse'</span>];

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; animals.length; i++) {
  <span class="hljs-built_in">console</span>.log(animals[i]);
}
</code></pre>
<p>You can manipulate the elements of the array inside the <code>for</code> loop's body.</p>
<h3 id="heading-2-how-to-use-a-while-loop">2. How to use a while loop</h3>
<p>Another way to iterate over an array is to use a <code>while</code> loop. You need to use a variable and the array's length to control when the iteration stops, like the <code>for</code> loop previously:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [<span class="hljs-string">'dog'</span>, <span class="hljs-string">'bird'</span>, <span class="hljs-string">'cat'</span>, <span class="hljs-string">'horse'</span>];

<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>;

<span class="hljs-keyword">while</span> (i &lt; animals.length) {
  <span class="hljs-built_in">console</span>.log(animals[i]);
  i++;
}
</code></pre>
<p>Inside the while loop, you need to increment the <code>i</code> variable by one to avoid an infinite loop.</p>
<h3 id="heading-3-how-to-use-a-forin-loop">3. How to use a for...in loop</h3>
<p>The <code>for...in</code> loop is another syntax that you can use to iterate over an array. This loop returns the index position of the array, so you can use it like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [<span class="hljs-string">'dog'</span>, <span class="hljs-string">'bird'</span>, <span class="hljs-string">'cat'</span>, <span class="hljs-string">'horse'</span>];

<span class="hljs-keyword">for</span> (i <span class="hljs-keyword">in</span> animals) {
  <span class="hljs-built_in">console</span>.log(animals[i]);
}
</code></pre>
<p>The <code>for...in</code> loop is more concise when compared to a <code>for</code> or <code>while</code> loop, but it's better to use a <code>for...of</code> loop when iterating over an array.</p>
<h3 id="heading-4-how-to-use-a-forof-loop">4. How to use a for...of loop</h3>
<p>The <code>for...of</code> loop can be used to iterate over an array. It returns the array's element in each iteration:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [<span class="hljs-string">'dog'</span>, <span class="hljs-string">'bird'</span>, <span class="hljs-string">'cat'</span>, <span class="hljs-string">'horse'</span>];

<span class="hljs-keyword">for</span> (element <span class="hljs-keyword">of</span> animals) {
  <span class="hljs-built_in">console</span>.log(element);
}
</code></pre>
<p>While the <code>for...in</code> loop returns the index position, the <code>for...of</code> loop returns the element directly.</p>
<h3 id="heading-5-how-to-use-the-foreach-method">5. How to use the <code>forEach()</code> method</h3>
<p>The JavaScript array object itself has a method called <code>forEach()</code> that you can use to iterate over an array from position 0 to the last position.</p>
<p>The method accepts a callback function that gets executed in each iteration. For each iteration, the method also passes the array's element and index position. Here's an example of using the method:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> animals = [<span class="hljs-string">'dog'</span>, <span class="hljs-string">'bird'</span>, <span class="hljs-string">'cat'</span>, <span class="hljs-string">'horse'</span>];

animals.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">element, index</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${index}</span>: <span class="hljs-subst">${element}</span>`</span>);
});
</code></pre>
<p>The output will be:</p>
<pre><code class="lang-txt">0: dog
1: bird
2: cat
3: horse
</code></pre>
<p>And that's how you iterate over an array using the <code>forEach()</code> method. You can use any method you like best.</p>
<h2 id="heading-how-to-convert-an-array-into-a-string">How to Convert an Array into a String</h2>
<p>To convert an array into a string, you can use the <code>toString()</code> or <code>join()</code> method.</p>
<p>The <code>toString()</code> method converts a given array into a string, with the elements separated by a comma:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> animals = [<span class="hljs-string">'cat'</span>, <span class="hljs-string">'bird'</span>, <span class="hljs-string">'fish'</span>];

<span class="hljs-built_in">console</span>.log(animals.toString()); <span class="hljs-comment">// "cat,bird,fish"</span>
</code></pre>
<p>The <code>join()</code> method also converts an array into a string, but you can pass a specific string separator as its argument.</p>
<p>The following example shows how to use a slash <code>/</code> and an empty string as the string separator:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> animals = [<span class="hljs-string">'cat'</span>, <span class="hljs-string">'bird'</span>, <span class="hljs-string">'fish'</span>];

<span class="hljs-built_in">console</span>.log(animals.join()); <span class="hljs-comment">// "cat,bird,fish"</span>

<span class="hljs-built_in">console</span>.log(animals.join(<span class="hljs-string">'/'</span>)); <span class="hljs-comment">// "cat/bird/fish"</span>

<span class="hljs-built_in">console</span>.log(animals.join(<span class="hljs-string">''</span>)); <span class="hljs-comment">// "catbirdfish"</span>
</code></pre>
<p>Behind the scenes, the <code>toString()</code> method actually calls the <code>join()</code> method to create the string.</p>
<h2 id="heading-how-to-compare-two-arrays">How to Compare Two Arrays</h2>
<p>JavaScript arrays are treated as objects. So when you compare two arrays, the comparison will look to the reference — that is, the address to the memory location that stores that array — instead of the actual values.</p>
<p>The comparison of two arrays will return <code>false</code> even when they contain the same elements:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> arrayOne = [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>];
<span class="hljs-keyword">let</span> arrayTwo = [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>];

<span class="hljs-built_in">console</span>.log(arrayOne === arrayTwo); <span class="hljs-comment">// false</span>
</code></pre>
<p>This is because <code>arrayOne</code> and <code>arrayTwo</code> are different objects stored in different memory locations.</p>
<p>The only way an array comparison would return <code>true</code> is when both variables refer to the same array object. In the example below, the <code>arrayTwo</code> variable is a reference to <code>arrayOne</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> arrayOne = [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>];
<span class="hljs-keyword">let</span> arrayTwo = arrayOne;

<span class="hljs-built_in">console</span>.log(arrayOne === arrayTwo); <span class="hljs-comment">// true</span>
</code></pre>
<p>But this won't work when you need to compare two arrays from different references. One way to compare arrays is by converting the array to a JSON object.</p>
<h3 id="heading-compare-arrays-by-converting-them-to-json-object">Compare arrays by converting them to JSON object</h3>
<p>Before comparing two different arrays, you need to convert them into JSON objects by calling the <code>JSON.stringify()</code> method.</p>
<p>You can then compare the two serialized strings as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> arrayOne = [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>];
<span class="hljs-keyword">let</span> arrayTwo = [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>];

<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">JSON</span>.stringify(arrayOne) === <span class="hljs-built_in">JSON</span>.stringify(arrayTwo)); <span class="hljs-comment">// true</span>
</code></pre>
<p>But this solution compares the arrays indirectly, and having the same values in different orders will return <code>false</code> instead of <code>true</code>.</p>
<p>To compare the elements of two arrays programmatically, you need to use another solution.</p>
<h3 id="heading-how-to-compare-arrays-with-the-every-method">How to compare arrays with the <code>every()</code> method</h3>
<p>Another way you can compare two arrays is by using the combination of the <code>length</code> property and the <code>every()</code> method.</p>
<p>First, you compare the length of the arrays so the comparison doesn't return <code>true</code> when the second array contains more elements than the first array.</p>
<p>After that, you test if the element on the first array is equal to the element on the second array, at the same index position. Use the <code>&amp;&amp;</code> operator to join the comparison as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> arrayOne = [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>];
<span class="hljs-keyword">let</span> arrayTwo = [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>];

<span class="hljs-keyword">let</span> result =
  arrayOne.length === arrayTwo.length &amp;&amp;
  arrayOne.every(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">element, index</span>) </span>{
    <span class="hljs-comment">// compare if the element matches in the same index</span>
    <span class="hljs-keyword">return</span> element === arrayTwo[index];
  });

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// true</span>
</code></pre>
<p>This way, you compare if the element at a specific index is really equal or not.</p>
<p>Still, this solution requires both arrays to have equal elements at a certain index in order to return <code>true</code>.</p>
<p>If you don't care about the order and only want both arrays to have the same elements, you need to use the <code>includes()</code> method instead of the equality <code>===</code> operator.</p>
<h3 id="heading-how-to-compare-arrays-with-the-includes-method">How to compare arrays with the <code>includes()</code> method</h3>
<p>In order to compare array elements that are out of order, you can use the combination of the <code>every()</code> and <code>includes()</code> methods.</p>
<p>The <code>includes()</code> method tests whether an array has a specific element you specified as its argument:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> arrayOne = [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>];
<span class="hljs-keyword">let</span> arrayTwo = [<span class="hljs-number">9</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>];

<span class="hljs-keyword">let</span> result =
  arrayOne.length === arrayTwo.length &amp;&amp;
  arrayOne.every(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">element</span>) </span>{
    <span class="hljs-keyword">return</span> arrayTwo.includes(element);
  });

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// true</span>
</code></pre>
<p>Another alternative to the <code>includes()</code> method is to use the <code>indexOf()</code> method, which returns the index of the specified element.</p>
<p>When the element isn't found, the <code>indexOf()</code> method returns <code>-1</code>. This means you need to make <code>every()</code> return <code>true</code> when <code>indexOf(element) !== -1</code> as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> arrayOne = [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>];
<span class="hljs-keyword">let</span> arrayTwo = [<span class="hljs-number">9</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>];

<span class="hljs-keyword">let</span> result =
  arrayOne.length === arrayTwo.length &amp;&amp;
  arrayOne.every(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">element</span>) </span>{
    <span class="hljs-keyword">return</span> arrayTwo.indexOf(element) !== <span class="hljs-number">-1</span>;
  });

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// true</span>
</code></pre>
<p>As you can see, comparing arrays is not straightforward. You need to use the methods provided by the array object creatively.</p>
<p>But don't worry! Most of the time you don't need to compare array objects when developing a web application. Next, let's learn how you can copy an array.</p>
<h2 id="heading-how-to-copy-an-array">How to Copy an Array</h2>
<p>One way to copy an array is to use the <code>slice()</code> method, which is provided exactly for copying an array.</p>
<p>You only need to call the method and assign the returned array to a new variable like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> arrayOne = [<span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>];
<span class="hljs-keyword">let</span> arrayTwo = arrayOne.slice();

<span class="hljs-built_in">console</span>.log(arrayOne); <span class="hljs-comment">// [ 7, 8, 9 ]</span>
<span class="hljs-built_in">console</span>.log(arrayTwo); <span class="hljs-comment">// [ 7, 8, 9 ]</span>
</code></pre>
<p>But keep in mind that the <code>slice()</code> method returns a shallow copy, which means that the values of the copy are references to the original array.</p>
<p>A shallow copy won't cause a problem when your array contains primitive values like strings, numbers, or booleans. But it might become an issue when you copy an array of objects. </p>
<p>To show you what I mean, see the example below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> arrayOne = [{ <span class="hljs-attr">name</span>: <span class="hljs-string">'Jack'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> }];
<span class="hljs-keyword">let</span> arrayTwo = arrayOne.slice();

<span class="hljs-built_in">console</span>.log(arrayOne); <span class="hljs-comment">// [ { name: 'Jack', age: 25 } ]</span>
<span class="hljs-built_in">console</span>.log(arrayTwo); <span class="hljs-comment">// [ { name: 'Jack', age: 25 } ]</span>

arrayTwo[<span class="hljs-number">0</span>].name = <span class="hljs-string">'Nathan'</span>;

<span class="hljs-built_in">console</span>.log(arrayOne); <span class="hljs-comment">// [ { name: 'Nathan', age: 25 } ]</span>
<span class="hljs-built_in">console</span>.log(arrayTwo); <span class="hljs-comment">// [ { name: 'Nathan', age: 25 } ]</span>
</code></pre>
<p>Do you notice what's wrong? The code above modifies only the <code>name</code> property of <code>arrayTwo</code>, but it changes both arrays!</p>
<p>This is because <code>arrayTwo</code> is a shallow copy of <code>arrayOne</code>. To prevent this behavior, you need to perform a deep copy so that <code>arrayTwo</code> values are disconnected from the original array.</p>
<h3 id="heading-how-to-create-a-deep-copy-of-an-array">How to create a deep copy of an array</h3>
<p>To create a deep copy of an array, you need to copy the array by using the <code>JSON.parse()</code> and <code>JSON.stringify()</code> methods instead of using the <code>slice()</code> method.</p>
<p>The <code>JSON.stringify()</code> transforms the array into a JSON string, and <code>JSON.parse()</code> converts that string back into an array.</p>
<p>Because the copy is created from a JSON string, there's no connection to the original array anymore:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> arrayOne = [{ <span class="hljs-attr">name</span>: <span class="hljs-string">'Jack'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> }];
<span class="hljs-keyword">let</span> arrayTwo = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">JSON</span>.stringify(arrayOne));

<span class="hljs-built_in">console</span>.log(arrayOne); <span class="hljs-comment">// [ { name: 'Jack', age: 25 } ]</span>
<span class="hljs-built_in">console</span>.log(arrayTwo); <span class="hljs-comment">// [ { name: 'Jack', age: 25 } ]</span>

arrayTwo[<span class="hljs-number">0</span>].name = <span class="hljs-string">'Nathan'</span>;

<span class="hljs-built_in">console</span>.log(arrayOne); <span class="hljs-comment">// [ { name: 'Jack', age: 25 } ]</span>
<span class="hljs-built_in">console</span>.log(arrayTwo); <span class="hljs-comment">// [ { name: 'Nathan', age: 25 } ]</span>
</code></pre>
<p>Here, you can see that changing the property of <code>arrayTwo</code> doesn't change the same property in <code>arrayOne</code>. Nice work!</p>
<h2 id="heading-how-to-merge-two-arrays-into-one">How to Merge Two Arrays into One</h2>
<p>JavaScript provides the <code>concat()</code> method that you can use to merge two or more arrays into one. The following example shows how to merge the <code>cats</code> and <code>birds</code> arrays as one array named <code>animals</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> cats = [<span class="hljs-string">'tiger'</span>, <span class="hljs-string">'cat'</span>];
<span class="hljs-keyword">let</span> birds = [<span class="hljs-string">'owl'</span>, <span class="hljs-string">'eagle'</span>];

<span class="hljs-keyword">let</span> animals = cats.concat(birds);

<span class="hljs-built_in">console</span>.log(animals); <span class="hljs-comment">// [ 'tiger', 'cat', 'owl', 'eagle' ]</span>
<span class="hljs-built_in">console</span>.log(cats); <span class="hljs-comment">// [ 'tiger', 'cat' ]</span>
<span class="hljs-built_in">console</span>.log(birds); <span class="hljs-comment">// [ 'owl', 'eagle' ]</span>
</code></pre>
<p>At first glance, the syntax of the <code>concat()</code> method seems to merge the <code>birds</code> array into the <code>cats</code> array. But as you can see from the console logs, the <code>cats</code> array is actually unchanged.</p>
<p>To make the code more intuitive, you can call the <code>concat()</code> method from an empty array instead of from the <code>cats</code> array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> cats = [<span class="hljs-string">'tiger'</span>, <span class="hljs-string">'cat'</span>];
<span class="hljs-keyword">let</span> birds = [<span class="hljs-string">'owl'</span>, <span class="hljs-string">'eagle'</span>];

<span class="hljs-keyword">let</span> animals = [].concat(cats, birds);
</code></pre>
<p>Although this syntax is more intuitive, you will most likely encounter the <code>cats.concat(birds)</code> syntax in many JavaScript source code. Which syntax to use? That's for you and your team to decide.</p>
<p>The <code>concat()</code> method allows you to merge as many arrays as you need. The following example merges three arrays as one:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> cats = [<span class="hljs-string">'tiger'</span>, <span class="hljs-string">'cat'</span>];
<span class="hljs-keyword">let</span> birds = [<span class="hljs-string">'owl'</span>, <span class="hljs-string">'eagle'</span>];
<span class="hljs-keyword">let</span> dogs = [<span class="hljs-string">'wolf'</span>, <span class="hljs-string">'dog'</span>];

<span class="hljs-keyword">let</span> animals = [].concat(cats, birds, dogs);
<span class="hljs-built_in">console</span>.log(animals); <span class="hljs-comment">// [ 'tiger', 'cat', 'owl', 'eagle', 'wolf', 'dog' ]</span>
</code></pre>
<p>You've now learned how to merge arrays using the <code>concat()</code> method. Let's look at how you can merge arrays with the spread operator next.</p>
<h3 id="heading-how-to-merge-arrays-with-the-spread-operator">How to merge arrays with the spread operator</h3>
<p>The spread operator <code>...</code> can be used to expand elements of the arrays you want to merge. You need to put the expanded elements in one new array as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> cats = [<span class="hljs-string">'tiger'</span>, <span class="hljs-string">'cat'</span>];
<span class="hljs-keyword">let</span> birds = [<span class="hljs-string">'owl'</span>, <span class="hljs-string">'eagle'</span>];

<span class="hljs-keyword">let</span> animals = [...cats, ...birds];
<span class="hljs-built_in">console</span>.log(animals); <span class="hljs-comment">// [ 'tiger', 'cat', 'owl', 'eagle' ]</span>
</code></pre>
<p>Here, you can see that the elements from <code>cats</code> and <code>birds</code> arrays are expanded into another array, and that array is assigned as the value of the <code>animals</code> variable.</p>
<p>Both the <code>concat()</code> method and the spread operator can be used to merge multiple arrays just fine.</p>
<h2 id="heading-how-to-search-an-array">How to Search an Array</h2>
<p>There are three ways you can search an array, depending on the result you want to achieve:</p>
<ol>
<li>Find whether an element exists in an array</li>
<li>Find the index position of an element in an array</li>
<li>Find the value that meets certain criteria in an array</li>
</ol>
<p>Let's learn all three ways to search an array together. Don't worry, they are simple.</p>
<h3 id="heading-1-how-to-find-whether-an-element-exists-in-an-array">1. How to find whether an element exists in an array</h3>
<p>If you only want to know if a certain element exists in an array, you can use the <code>includes()</code> method. The following example searches for the string value 'e' in an array of strings:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> letters = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>, <span class="hljs-string">'d'</span>];

<span class="hljs-built_in">console</span>.log(letters.include(<span class="hljs-string">'e'</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<p>The <code>includes()</code> method returns <code>true</code> when the element is found, or <code>false</code> when it isn't.</p>
<h3 id="heading-2-how-to-find-the-index-position-of-an-element-in-an-array">2. How to find the index position of an element in an array</h3>
<p>Other times, you might want to get the index position of the element. You need to use the <code>indexOf()</code> method in that case:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> letters = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>, <span class="hljs-string">'d'</span>];

<span class="hljs-built_in">console</span>.log(letters.indexOf(<span class="hljs-string">'c'</span>)); <span class="hljs-comment">// 2</span>
</code></pre>
<p>Here, the <code>indexOf()</code> method is called on the <code>letters</code> array to search for the index of the value 'c'. The method returns <code>-1</code> when the element isn't found, but in this case it returns <code>2</code> as the letter c is at the 2nd index (remember, JS uses zero-based indexing, meaning the count starts from 0, not 1).</p>
<h3 id="heading-3-how-to-find-elements-that-meet-certain-criteria-in-an-array">3. How to find elements that meet certain criteria in an array</h3>
<p>To find elements that meet certain criteria, you need to use the <code>filter()</code> method.</p>
<p>The <code>filter()</code> method is a built-in method available for JavaScript array objects that can help you in filtering an array. The syntax of the method is as follows:</p>
<pre><code class="lang-js">arrayObject.filter(callback, thisContext);
</code></pre>
<p>The method has two parameters:</p>
<ul>
<li><code>callback</code> (<strong>Required</strong>) – The filtering function that will be executed for each array value</li>
<li><code>thisContext</code> (<strong>Optional</strong>) – The value of <code>this</code> keyword inside the <code>callback</code></li>
</ul>
<p>The <code>thisContext</code> parameter is optional and usually not needed. You only need to define the <code>callback</code> function, which will accept three arguments:</p>
<ul>
<li>The <code>currentElement</code> being processed into the method</li>
<li>The <code>index</code> of the element that starts from <code>0</code></li>
<li>and the <code>array</code> object where you call <code>filter()</code></li>
</ul>
<pre><code class="lang-js">filterCallback(currentElement, index, array){
  <span class="hljs-comment">// ...</span>
}
</code></pre>
<p>The callback function must include a validation pattern that returns either <code>true</code> or <code>false</code>.</p>
<h4 id="heading-filter-method-examples">Filter method examples</h4>
<p>Let's see an example of <code>filter()</code> in action. Let's say you have an array called <code>stockPrices</code> as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> stockPrices = [<span class="hljs-number">3</span>, <span class="hljs-number">7</span>, <span class="hljs-number">2</span>, <span class="hljs-number">15</span>, <span class="hljs-number">4</span>, <span class="hljs-number">9</span>, <span class="hljs-number">21</span>, <span class="hljs-number">14</span>];
</code></pre>
<p>You want to filter the prices to include only those greater than 5.</p>
<p>Here's how you do it with the <code>filter()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> stockPrices = [<span class="hljs-number">3</span>, <span class="hljs-number">7</span>, <span class="hljs-number">2</span>, <span class="hljs-number">15</span>, <span class="hljs-number">4</span>, <span class="hljs-number">9</span>, <span class="hljs-number">21</span>, <span class="hljs-number">14</span>];

<span class="hljs-keyword">let</span> filteredPrices = stockPrices.filter(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">currentElement</span>) </span>{
  <span class="hljs-keyword">return</span> currentElement &gt; <span class="hljs-number">5</span>;
});

<span class="hljs-built_in">console</span>.log(filteredPrices); <span class="hljs-comment">// [7, 15, 9, 21, 14]</span>
</code></pre>
<p>The <code>filter()</code> method evaluates the <code>currentElement</code> and returns either <code>true</code> or <code>false</code>.</p>
<p>If your callback function returns <code>true</code>, the <code>currentElement</code> will be added to the result array:</p>
<ul>
<li>During the first iteration, the <code>currentElement</code> is <code>3</code> so the callback returns <code>false</code></li>
<li>During the second iteration, the <code>currentElement</code> is <code>7</code> so the callback returns <code>true</code> and the value is pushed into the result array</li>
<li>The iteration will continue to the last element</li>
<li>The resulting array is assigned to the <code>filteredPrices</code> variable</li>
</ul>
<p>And that's how the method works. Next, let's see how to use the <code>filter()</code> method to filter an array of objects.</p>
<h4 id="heading-how-to-filter-an-array-of-objects">How to filter an array of objects</h4>
<p>The <code>filter()</code> method can also be used on an array of objects.</p>
<p>Suppose you have an array of objects containing imaginary stock prices and their symbols as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> stocks = [
  {
    <span class="hljs-attr">code</span>: <span class="hljs-string">'GOOGL'</span>,
    <span class="hljs-attr">price</span>: <span class="hljs-number">1700</span>,
  },
  {
    <span class="hljs-attr">code</span>: <span class="hljs-string">'AAPL'</span>,
    <span class="hljs-attr">price</span>: <span class="hljs-number">130</span>,
  },
  {
    <span class="hljs-attr">code</span>: <span class="hljs-string">'MSFT'</span>,
    <span class="hljs-attr">price</span>: <span class="hljs-number">219</span>,
  },
  {
    <span class="hljs-attr">code</span>: <span class="hljs-string">'TSLA'</span>,
    <span class="hljs-attr">price</span>: <span class="hljs-number">880</span>,
  },
  {
    <span class="hljs-attr">code</span>: <span class="hljs-string">'FB'</span>,
    <span class="hljs-attr">price</span>: <span class="hljs-number">267</span>,
  },
  {
    <span class="hljs-attr">code</span>: <span class="hljs-string">'AMZN'</span>,
    <span class="hljs-attr">price</span>: <span class="hljs-number">3182</span>,
  },
];
</code></pre>
<p>Now you need to filter the array to contain only stocks with <code>price</code> value less than 1000. Here's how you do it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> filteredStocks = stocks.filter(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">currentElement</span>) </span>{
  <span class="hljs-keyword">return</span> currentElement.price &lt; <span class="hljs-number">1000</span>;
});
</code></pre>
<p>The value of <code>filteredStocks</code> will be as follows:</p>
<pre><code class="lang-txt">0: {code: "AAPL", price: 130}
1: {code: "MSFT", price: 219}
2: {code: "TSLA", price: 880}
3: {code: "FB", price: 267}
</code></pre>
<p>Finally, you can also write the callback function using the arrow function syntax like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> filteredStocks = stocks.filter(
  <span class="hljs-function"><span class="hljs-params">currentElement</span> =&gt;</span> currentElement.price &lt; <span class="hljs-number">1000</span>
);
</code></pre>
<p>When you have simple filter criteria, using the arrow function syntax can help you write cleaner code.</p>
<h2 id="heading-how-to-sort-an-array">How to Sort an Array</h2>
<p>To sort an array, you can use the provided <code>sort()</code> method, which sorts an array in ascending order by default:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">5</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">1</span>];

numbers.sort();

<span class="hljs-built_in">console</span>.log(numbers); <span class="hljs-comment">// [ 1, 2, 4, 5 ]</span>
</code></pre>
<p>If you want to sort an array in descending order, you can call the <code>reverse()</code> method after the <code>sort()</code> method as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">5</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">1</span>];

numbers.sort().reverse();

<span class="hljs-built_in">console</span>.log(numbers); <span class="hljs-comment">// [ 5, 4, 2, 1 ]</span>
</code></pre>
<p>The <code>reverse()</code> method will reverse the array, so the first array element becomes the last, the last becomes the first, and so on.</p>
<h2 id="heading-how-to-create-multi-dimensional-arrays">How to Create Multi-dimensional Arrays</h2>
<p>A multi-dimensional array is an array that contains another array. To create one, you need to write an array inside an array literal (the square bracket)</p>
<p>The following example shows how you can create a two-dimensional array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> numbers = [[<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>]];
</code></pre>
<p>To access the array, you just need to call the variable with two array indices. The first index is for the outer array, and the second index is for the inner array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> numbers = [[<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>]];
<span class="hljs-built_in">console</span>.log(numbers[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>]); <span class="hljs-comment">// 5</span>
<span class="hljs-built_in">console</span>.log(numbers[<span class="hljs-number">0</span>][<span class="hljs-number">1</span>]); <span class="hljs-comment">// 6</span>
<span class="hljs-built_in">console</span>.log(numbers[<span class="hljs-number">0</span>][<span class="hljs-number">2</span>]); <span class="hljs-comment">// 7</span>
</code></pre>
<p>As you can see from the example above, the array <code>[5, 6, 7]</code> is stored inside index <code>0</code> of the outer <code>[]</code> array. You can add more elements inside the array as follows:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> numbers = [[<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>], [<span class="hljs-number">10</span>], [<span class="hljs-number">20</span>]];
<span class="hljs-built_in">console</span>.log(numbers[<span class="hljs-number">1</span>][<span class="hljs-number">0</span>]); <span class="hljs-comment">// 10</span>
<span class="hljs-built_in">console</span>.log(numbers[<span class="hljs-number">2</span>][<span class="hljs-number">0</span>]); <span class="hljs-comment">// 20</span>
</code></pre>
<p>A multi-dimensional array is not required to have the same array length, as can be seen above. Although you can create even a three or four-dimensional array, it's not recommended to create more than a two-dimensional array because it will be confusing.</p>
<p>Notice how difficult it is to read and access the value <code>[23]</code> inside the three-dimensional array below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> numbers = [[<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, [<span class="hljs-number">23</span>]]];
<span class="hljs-built_in">console</span>.log(numbers[<span class="hljs-number">0</span>][<span class="hljs-number">3</span>][<span class="hljs-number">0</span>]); <span class="hljs-comment">// 23</span>
</code></pre>
<p>Finally, you can still use JavaScript <code>Array</code> object methods like <code>push()</code>, <code>shift()</code>, and <code>unshift()</code> to manipulate the multi-dimensional array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> numbers = [[<span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, [<span class="hljs-number">23</span>]]];
numbers.push([<span class="hljs-number">50</span>]);
<span class="hljs-built_in">console</span>.log(numbers); <span class="hljs-comment">// [[5, 6, 7, [23]], [50]]</span>

numbers.shift();
<span class="hljs-built_in">console</span>.log(numbers); <span class="hljs-comment">// [[50]]</span>

numbers.unshift(<span class="hljs-string">'13'</span>);
<span class="hljs-built_in">console</span>.log(numbers); <span class="hljs-comment">// ["13", [50]]</span>
</code></pre>
<p>A multi-dimensional array has no unique methods compared to a one-dimensional array. Often, it's used to store a group of related data as one array.</p>
<p>The following example shows how to group <code>name</code> and <code>age</code> values under a multi-dimensional array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> users = [
  [<span class="hljs-string">'Nathan'</span>, <span class="hljs-number">28</span>],
  [<span class="hljs-string">'Jack'</span>, <span class="hljs-number">23</span>],
  [<span class="hljs-string">'Alex'</span>, <span class="hljs-number">30</span>],
];
</code></pre>
<p>Unless you have to use an array, it's better to use an array of objects to store a group of related data:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> users = [
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Nathan'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">28</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Jack'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">23</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Alex'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> },
];
</code></pre>
<p>Ideally, you should use only one-dimensional arrays in your project. Use two-dimensional structure if you really need to, but never go beyond that or you'll have a hard time manipulating the array later.</p>
<h2 id="heading-javascript-array-methods-cheat-sheet">JavaScript Array Methods Cheat Sheet</h2>
<p>Beginners are usually overwhelmed by the number of methods an array has, so I've prepared a cheat sheet that can help you get a quick lookup at what a method does.</p>
<p>The cheat sheet contains a short description and a quick example of what a method does. You can download it here:</p>
<div class="embed-wrapper">
        <blockquote class="twitter-tweet">
          <a href="https://twitter.com/nsebhastian/status/1696034185398645024"></a>
        </blockquote>
        <script defer="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></div>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Congratulations on finishing this JavaScript Array Guide. I hope this tutorial has helped you understand how to create, copy, and manipulate an array in JavaScript.</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G">here</a>.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JS Date Validations – How To Validate a Date in JavaScript (With Examples) ]]>
                </title>
                <description>
                    <![CDATA[ There are times when you need to validate a date input in your JavaScript applications. This article will show you how to perform the following date validations: Check if a string is a valid date Validate a string in the DD/MM/YYYY format Check if t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-validate-a-date-in-javascript/</link>
                <guid isPermaLink="false">66bd9164abdea6b5b115fefd</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Tue, 22 Aug 2023 19:08:29 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/js-date-validations.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>There are times when you need to validate a date input in your JavaScript applications.</p>
<p>This article will show you how to perform the following date validations:</p>
<ol>
<li>Check if a string is a valid date</li>
<li>Validate a string in the <code>DD/MM/YYYY</code> format</li>
<li>Check if the date is in the past or future</li>
</ol>
<p>Validating a date value helps you prevent users from entering an incorrect date. Let's start with validating the input itself.</p>
<h2 id="heading-how-to-check-if-a-string-is-a-valid-date-with-javascript">How to Check if a String is a Valid Date with JavaScript</h2>
<p>To validate if a string is a valid date input, you need to call the <code>Date()</code> constructor and pass the string as its argument.</p>
<p>If the string is a valid date, the constructor returns a <code>Date</code> object holding the same value as the string:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dateInput = <span class="hljs-string">"2019/05/15"</span>; <span class="hljs-comment">// YYYY/MM/DD format</span>

<span class="hljs-keyword">let</span> dateObj = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(dateInput);

<span class="hljs-built_in">console</span>.log(dateObj); <span class="hljs-comment">// 2019-05-15T00:00:00.000Z</span>
</code></pre>
<p>If you pass an invalid date, the constructor returns an <code>Invalid Date</code> object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dateInput = <span class="hljs-string">"2019/15/15"</span>; <span class="hljs-comment">// YYYY/MM/DD format</span>

<span class="hljs-keyword">let</span> dateObj = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(dateInput);

<span class="hljs-built_in">console</span>.log(dateObj); <span class="hljs-comment">// Invalid Date</span>
</code></pre>
<p>Note that the <code>Date()</code> constructor requires you to pass a date in the format of <code>YYYY/MM/DD</code> or <code>MM/DD/YYYY</code>. If you pass a date in <code>DD/MM/YYYY</code> format, the contructor also returns an <code>Invalid Date</code>.</p>
<p>Now that you have a <code>Date</code> object representing the string, you can use the <code>isNaN()</code> function to check if the object is valid.</p>
<p>You can create a function to check the validity of the <code>Date</code> object as follows:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isDateValid</span>(<span class="hljs-params">dateStr</span>) </span>{
  <span class="hljs-keyword">return</span> !<span class="hljs-built_in">isNaN</span>(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(dateStr));
}

<span class="hljs-comment">// DD/MM/YYYY</span>
<span class="hljs-built_in">console</span>.log(isDateValid(<span class="hljs-string">"15/05/2019"</span>)); <span class="hljs-comment">// false</span>

<span class="hljs-comment">// MM/DD/YYYY</span>
<span class="hljs-built_in">console</span>.log(isDateValid(<span class="hljs-string">"05/15/2019"</span>)); <span class="hljs-comment">// true</span>

<span class="hljs-comment">// YYYY/MM/DD</span>
<span class="hljs-built_in">console</span>.log(isDateValid(<span class="hljs-string">"2019/05/15"</span>)); <span class="hljs-comment">// true</span>
</code></pre>
<p>Here, we reverse the value returned by the <code>isNaN()</code> function so that a valid Date returns <code>true</code>. You can call the <code>isDateValid()</code> function anytime you need to check if a string returns a valid date.</p>
<p>Next, let's see how to handle a date string in <code>DD/MM/YYYY</code> format.</p>
<h2 id="heading-how-to-validate-a-date-and-convert-it-to-ddmmyyyy-format">How to Validate a Date and Convert it to DD/MM/YYYY Format</h2>
<p>If you want to format the date as a <code>DD/MM/YYYY</code> string, you need to use a combination of <code>getDate()</code>, <code>getMonth()</code>, and <code>getFullYear()</code> methods to manually create the date string.</p>
<p>First, you validate the string in the <code>YYYY/MM/DD</code> format by passing it to the <code>Date()</code> constructor.</p>
<p>Next, you check if the <code>Date</code> value is not NaN using an <code>if</code> statement:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dateInput = <span class="hljs-string">"2019/05/15"</span>; <span class="hljs-comment">// YYYY/MM/DD format</span>

<span class="hljs-keyword">let</span> dateObj = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(dateInput);

<span class="hljs-keyword">if</span> (!<span class="hljs-built_in">isNaN</span>(dateObj)) {
  <span class="hljs-comment">// Convert dateObj to DD/MM/YYYY</span>
}
</code></pre>
<p>When the <code>Date</code> isn't a NaN, you can extract the date, month, and year of the object using the <code>getDate()</code>, <code>getMonth()</code>, and <code>getFullYear()</code> methods:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dateInput = <span class="hljs-string">"2019/05/15"</span>; <span class="hljs-comment">// YYYY/MM/DD format</span>

<span class="hljs-keyword">let</span> dateObj = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(dateInput);

<span class="hljs-keyword">if</span> (!<span class="hljs-built_in">isNaN</span>(dateObj)) {
  <span class="hljs-keyword">let</span> day = dateObj.getDate();
  day = day &lt; <span class="hljs-number">10</span> ? <span class="hljs-string">"0"</span> + day : day;
  <span class="hljs-keyword">let</span> month = dateObj.getMonth() + <span class="hljs-number">1</span>;
  month = month &lt; <span class="hljs-number">10</span> ? <span class="hljs-string">"0"</span> + month : month;
  <span class="hljs-keyword">const</span> year = dateObj.getFullYear();

  <span class="hljs-keyword">const</span> resultDate = <span class="hljs-string">`<span class="hljs-subst">${day}</span>/<span class="hljs-subst">${month}</span>/<span class="hljs-subst">${year}</span>`</span>;
  <span class="hljs-built_in">console</span>.log(resultDate);  <span class="hljs-comment">// 15/05/2019</span>
}
</code></pre>
<p>Here, you can see that the date "2019/05/15" is converted into "15/05/2019". Notice how you need to modify the <code>day</code> and <code>month</code> variables to add <code>0</code> in front of the values if those values are single digits.</p>
<p>The <code>getMonth()</code> method returns a number between 0 and 11 that represents the month of the date. You need to increment the returned value by 1 to get the correct date.</p>
<h2 id="heading-what-if-i-get-the-date-in-ddmmyyyy-format">What if I get the Date in DD/MM/YYYY Format?</h2>
<p>As I said before, JavaScript doesn't support converting a string in <code>DD/MM/YYYY</code> format into a valid <code>Date</code> object.</p>
<p>If you have a date string in <code>DD/MM/YYYY</code> format, then you need to swap the date and year position before calling the <code>Date()</code> constructor. </p>
<p>You can do so by using the <code>split()</code> method to convert the string into an array, then swap the position of date and year at index 0 and 2.</p>
<p>Pass the separator <code>/</code> as the argument to the split method as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> dateInput = <span class="hljs-string">"15/05/2019"</span>; <span class="hljs-comment">// DD/MM/YYYY format</span>

<span class="hljs-keyword">let</span> dateArray = dateInput.split(<span class="hljs-string">"/"</span>);

<span class="hljs-keyword">let</span> newDate = <span class="hljs-string">`<span class="hljs-subst">${dateArray[<span class="hljs-number">2</span>]}</span>/<span class="hljs-subst">${dateArray[<span class="hljs-number">1</span>]}</span>/<span class="hljs-subst">${dateArray[<span class="hljs-number">0</span>]}</span>`</span>;

<span class="hljs-built_in">console</span>.log(newDate); <span class="hljs-comment">// 2019/05/15 (YYYY/MM/DD)</span>
</code></pre>
<p>The <code>newDate</code> variable has the value of <code>dateInput</code> but in <code>YYYY/MM/DD</code> format. You can pass <code>newDate</code> into the <code>Date()</code> constructor to see if it's a valid date.</p>
<h2 id="heading-how-to-check-if-a-date-is-in-the-past-or-future">How to Check if a Date is in the Past or Future</h2>
<p>To check if a date is in the past or future, you can use the less than <code>&lt;</code> operator to compare the input date with the current date.</p>
<p>When the result is <code>true</code>, then the input date is in the past:</p>
<pre><code class="lang-js"><span class="hljs-comment">// The date you want to check</span>
<span class="hljs-keyword">const</span> inputDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2023-08-20'</span>); 

<span class="hljs-comment">// Get the current date</span>
<span class="hljs-keyword">const</span> currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();

<span class="hljs-comment">// Compare the input date with the current date</span>
<span class="hljs-keyword">if</span> (inputDate &lt; currentDate) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The input date is in the past.'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The input date is in the future.'</span>);
}
</code></pre>
<p>JavaScript knows how to compare <code>Date</code> objects, so you don't need to extract the values and compare them manually.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Now you've learned how to validate if a string is a valid date, how to convert a date into a <code>DD/MM/YYYY</code> format, and how to check if a date is in the past or future.</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G">here</a>.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
