<?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[ Benjamin Semah - 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[ Benjamin Semah - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 26 May 2026 22:46:49 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/benjaminSemah/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use LocalStorage in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ In modern web development, having a way to persist data helps developers improve performance and create a better user experience. And using local storage is an effective way of persisting data in an application. In this article, you will learn what l... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/use-local-storage-in-modern-applications/</link>
                <guid isPermaLink="false">66d45dedc7632f8bfbf1e417</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ localstorage ]]>
                    </category>
                
                    <category>
                        <![CDATA[ storage ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Tue, 20 Feb 2024 21:37:46 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/JavaScript-localStorage-freeCodeCamp-Benjamin-Semah.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In modern web development, having a way to persist data helps developers improve performance and create a better user experience. And using local storage is an effective way of persisting data in an application.</p>
<p>In this article, you will learn what local storage is and how to use it in modern web applications. You will also learn the advantages of using local storage, as well as some of its limitations.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#what-is-local-storage">What is Local Storage?</a></p>
</li>
<li><p><a class="post-section-overview" href="#differences-between-local-storage-and-session-storage">Differences Between Local Storage and Session Storage</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-use-local-storage">How to Use Local Storage</a></p>
</li>
<li><p><a class="post-section-overview" href="#a-practical-example">A Practical Example</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-view-local-storage-in-devtools">How to View Local Storage in DevTools</a></p>
</li>
<li><p><a class="post-section-overview" href="#benefits-of-using-local-storage">Benefits of Using Local Storage</a></p>
</li>
<li><p><a class="post-section-overview" href="#limitations-of-using-local-storage">Limitations of Local Storage</a></p>
</li>
<li><p><a class="post-section-overview" href="#conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-local-storage">What is Local Storage?</h2>
<p>Local storage is a feature in web browsers that allows developers to save data in the user’s browser. It’s part of the web storage API, together with session storage.</p>
<p>Local storage works by accepting data in key-value pairs. It retains the data even when the user refreshes the page or closes the tab or browser.</p>
<h2 id="heading-differences-between-local-storage-and-session-storage">Differences Between Local Storage and Session Storage</h2>
<p>As I mentioned earlier, the web storage API in modern browsers provides two main features for data storage. These are local storage and session storage.</p>
<p>The key differences between the two are the lifespan of the stored data and their scope.</p>
<p>Data in local storage remains available even when the tab/browser is closed. But closing the tab/browser clears any data stored in session storage.</p>
<p>Also, data in local storage is accessible across multiple browser tabs and windows. On the other hand, data in session storage is only accessible within specific browser tabs and is not shared.</p>
<h2 id="heading-how-to-use-local-storage">How to Use Local Storage</h2>
<p>The local storage object provides different methods you can use to interact with it. With these methods, you can add, read, and delete data from local storage.</p>
<h3 id="heading-how-to-store-data-in-local-storage">How to Store Data in Local Storage</h3>
<p>To store data in local storage, you use the <code>setItem()</code> method. This method takes in two arguments, a key and a value.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">localStorage</span>.setItem(key, value)
</code></pre>
<p>If the key does not exist in local storage, the <code>setItem()</code> method will create a new key and assign the given value to it. But if a key with the same name exists in local storage, it will update the value of the key with the provided value.</p>
<h3 id="heading-how-to-read-data-from-local-storage">How to Read Data From Local Storage</h3>
<p>To retrieve and use data from local storage, you use the <code>getItem()</code> method. This method takes in a key as an argument.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">localStorage</span>.getItem(key)
</code></pre>
<p>If the given key exists in local storage, the method returns the value of that key. If it doesn’t, the method returns <code>null</code>.</p>
<h3 id="heading-how-to-store-and-read-complex-data-values-in-local-storage">How to Store and Read Complex Data Values in Local Storage</h3>
<p>Local storage can only store strings. This means if you need to store values like objects or arrays, you first need to get a string representation of the value. You do this using the <code>JSON.stringify()</code> method.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> userObj = {
  username = <span class="hljs-string">"Maria"</span>,
  <span class="hljs-attr">email</span>: <span class="hljs-string">"maria@mail.com"</span>
}

<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'user'</span>, <span class="hljs-built_in">JSON</span>.stringify(userObj))
</code></pre>
<p>The <code>JSON.stringify()</code> method converts the <code>userObj</code> object into a string representation before sending it to local storage.</p>
<p>Now, when you want to retrieve the data back from local storage, you also need to change it from its string representation back to the original form. And you do that using the <code>JSON.parse()</code> method.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> storedUserData = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'user'</span>)

<span class="hljs-keyword">if</span> (storedUserData) {
  <span class="hljs-keyword">const</span> userData = <span class="hljs-built_in">JSON</span>.parse(storedUserData)
  <span class="hljs-comment">// You can use userData here...</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User data not found in local storage'</span>)
}
</code></pre>
<p>In the example above, we first check if there is data for ‘user’ in local storage before using the <code>JSON.parse()</code> method. This is important because if it does not exist in local storage, <code>JSON.parse()</code> will be applied to a <code>null</code> value (which will result in an error).</p>
<h3 id="heading-how-to-delete-data-from-local-storage">How to Delete Data from Local Storage</h3>
<p>There are two methods available for deleting data from local storage. One is the <code>removeItem()</code> method and the other is the <code>clear()</code> method.</p>
<p>You use the <code>removeItem()</code> method when you want to delete a single item from local storage. The method takes in a key as an argument and deletes the corresponding key-value pair from local storage.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">localStorage</span>.removeItem(key)
</code></pre>
<p>But what if, instead of deleting a single key-value pair, you want to clear all data from the local storage? Well, local storage has a method for that - the <code>clear()</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">localStorage</span>.clear()
</code></pre>
<p>The <code>clear()</code> method deletes all key-value pairs in the local storage for the current domain.</p>
<h3 id="heading-how-to-get-the-name-of-a-key-in-local-storage">How to Get the Name of a Key in Local Storage</h3>
<p>If you want to get the name of a key at a particular index in local storage, you can use the <code>key()</code> method. It takes in a number as an argument and returns the name of the key at that specified index.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">localStorage</span>.key(<span class="hljs-number">0</span>)
</code></pre>
<p>The example above will return the name of the key at index 0. If there is no key at the specified index, the method will return null.</p>
<h2 id="heading-a-practical-example">A Practical Example</h2>
<p>The following shows a practical demo of the difference between local storage and session storage.</p>
<p>In this example, we'll save the user's name in local storage and save the age in session storage.</p>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- HTML --&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> <span class="hljs-attr">class</span>=<span class="hljs-string">"userName"</span>&gt;</span><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">class</span>=<span class="hljs-string">"userAge"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

  <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">class</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter name here"</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"saveNameBtn"</span>&gt;</span>Save Name<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">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"age"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter age here"</span>/&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"saveAgeBtn"</span>&gt;</span>Save Age<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>The markup includes two header elements. One for <code>userName</code> and the other for <code>userAge</code>. It also includes two input elements for name and age. Each input has an associated button we'll use for saving the data.</p>
<p>Now, let's use the <code>querySelector</code> method to select the various elements.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> userNameText = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".userName"</span>)
<span class="hljs-keyword">const</span> userAgeText = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".userAge"</span>)

<span class="hljs-keyword">const</span> saveNameButton = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".saveNameBtn"</span>)
<span class="hljs-keyword">const</span> saveAgeButton = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".saveAgeBtn"</span>)
</code></pre>
<h3 id="heading-code-example-for-local-storage">Code Example for Local Storage</h3>
<pre><code class="lang-javascript">saveNameButton.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> userName = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".name"</span>).value
  userNameText.textContent = userName
  <span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"name"</span>, userName)
})
</code></pre>
<p>First, we get the value of the name input, set it as the <code>textContent</code> of <code>userNameText</code>. And then use the <code>setItem()</code> of local storage to save the <code>userName</code> value in local storage.</p>
<p>Next, let's see how we can get the name value from local storage when we need it.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayUserName</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> nameFromLocalStorage = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"name"</span>)

  <span class="hljs-keyword">if</span> (nameFromLocalStorage) {
    userNameText.textContent = nameFromLocalStorage
  } <span class="hljs-keyword">else</span> {
    userNameText.textContent = <span class="hljs-string">"No name data in local storage"</span>
  }
}

displayUserName()
</code></pre>
<p>The <code>displayUserName</code> function gets <code>nameFromLocalStorage</code> using the <code>getItem()</code> method. If the value exists in local storage, we set it as the <code>textContent</code> of the <code>userNameText</code> element. If it's <code>null</code> or doesn't exist, then we set <code>textContent</code> to the string <em>"No name data in local storage"</em>.</p>
<h3 id="heading-code-example-for-session-storage">Code Example for Session Storage</h3>
<p>Now, let's do the same thing for the <code>age</code> value. The only difference here will be using session storage instead of local storage.</p>
<pre><code class="lang-javascript">
saveAgeButton.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> userAge = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".age"</span>).value
  userAgeText.textContent = userAge
  sessionStorage.setItem(<span class="hljs-string">"age"</span>, userAge)
})

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayUserAge</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> ageFromSessionStorage = sessionStorage.getItem(<span class="hljs-string">"age"</span>)

  <span class="hljs-keyword">if</span> (ageFromSessionStorage) {
    userAgeText.textContent = ageFromSessionStorage
  } <span class="hljs-keyword">else</span> {
    userAgeText.textContent = <span class="hljs-string">"No age data in session storage"</span>
  }
}

displayUserAge()
</code></pre>
<p>The <code>setItem</code> and <code>getItem</code> methods also works for session storage.</p>
<h3 id="heading-demo">Demo:</h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/demo.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Local storage and session storage demo.</em></p>
<p>As you can see from the demo above, when you close and reopen the page, the <code>name</code> data from local storage persists. But the <code>age</code> data from session storage is cleared once the page closes.</p>
<p><a target="_blank" href="https://stackblitz.com/edit/vitejs-vite-hb86sa?file=index.html,main.js&amp;terminal=dev">Try your hands on the code sample on StackBlitz</a></p>
<h2 id="heading-how-to-view-local-storage-in-devtools">How to View Local Storage in DevTools</h2>
<p>You can follow the steps below to inspect the contents of local storage in your browser's developer tools.</p>
<p>First, open DevTools. You can do that by right clicking on the web page and selecting "Inspect".</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/STEP-ONE.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Demo of how to open the DevTools.</em></p>
<p>Then, select the "Application" tab on the DevTools panel. Depending on your browser, this panel may have a different name. For example, it's called "Storage" in Safari and Firefox.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/STEP-TWO.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Demo of how to open the "Application" panel in DevTools.</em></p>
<p>Locate the "Storage" section on the sidebar showing a list of the various web storage options.</p>
<p>Click on "Local Storage" to expand and view its contents.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/STEP-THREE.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Demo of how to open the local storage tab in the storage panel.</em></p>
<p>You can click on individual items to view the corresponding key-value pair.</p>
<h2 id="heading-benefits-of-using-local-storage">Benefits of Using Local Storage</h2>
<p>The following are some of the benefits local storage has over other storage mechanisms in modern web development.</p>
<ol>
<li><p><strong>Persistent data:</strong> When you use local storage, the stored data remains even when the user closes the tab or the browser. This is useful for saving user preferences, settings, and other relevant data. It can help create a seamless user experience.</p>
</li>
<li><p><strong>Offline access:</strong> You can use local storage as a means to cache data which can be accessed even with limited or no internet. This makes it a useful feature for apps that rely on caching data for offline use like news readers, productivity apps, and so on.</p>
</li>
<li><p><strong>More storage capacity:</strong> Compared to other storage means, local storage has a relatively high capacity. For example, cookies are limited to 4 kilobytes per domain. But local storage can store up to 5 megabytes of data per domain.</p>
</li>
</ol>
<h2 id="heading-limitations-of-using-local-storage">Limitations of Using Local Storage</h2>
<ol>
<li><p><strong>Stores only strings:</strong> As you learned earlier, local storage can only store string values. You can use the JSON <code>stringify</code> and <code>parse</code> methods to work around it. But some web developers may not prefer it as it can lead to writing complex code that’s difficult to debug.</p>
</li>
<li><p><strong>Security concerns:</strong> Data in the local storage can be prone to attacks like cross-site scripting (XSS). As such, you should be cautious when working with sensitive information. It’s advisable to assess security implications and consider other alternatives where necessary.</p>
</li>
<li><p><strong>Not accessible to web workers:</strong> Local storage is part of the Window object. As such, it’s tied to the main execution thread of the web page. This means it's not accessible to web workers. So if you run any background processes, you cannot use local storage within the web worker scripts.</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Local storage is a feature in modern web browsers that makes it easy for web developers to store and persist data between browser sessions.</p>
<p>Compared to traditional cookies, it provides larger storage capacities. Also, unlike cookies, it does not rely on server-side processes. This reduces the need for frequent server requests and helps improve performance.</p>
<p>In this article, you learn about how to use local storage. We covered saving, retrieving, and deleting data from local storage. You also learned about some of the benefits of using local storage in your project, and some of its limitations too.</p>
<p>Thanks for reading. And happy coding! For more in-depth tutorials, feel free to <a target="_blank" href="https://www.youtube.com/@DevAfterHours">subscribe to my YouTube channel</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Strict Mode in JavaScript? Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ If you are a JavaScript developer, you may come across the string "use strict" at the top of your JavaScript code. This means that JavaScript's strict mode is in use. But what does this mean, and why does it matter? In this article, you'll learn what... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-strict-mode-in-javascript/</link>
                <guid isPermaLink="false">66d45ddcc7632f8bfbf1e3f1</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Tue, 06 Feb 2024 11:05:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-02-at-2.56.05-PM.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you are a JavaScript developer, you may come across the string "use strict" at the top of your JavaScript code. This means that JavaScript's strict mode is in use. But what does this mean, and why does it matter?</p>
<p>In this article, you'll learn what it means to write JavaScript code in strict mode and how you can enable it. The article also covers some benefits of using strict mode and some examples that show how it differs from regular JavaScript.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#what-is-strict-mode-in-javascript">What is Strict Mode in JavaScript?</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-use-strict-mode-in-javascript">How to Use Strict Mode in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#difference-between-strict-mode-and-regular-javascript">Difference Between Strict Mode and Regular JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#javascript-features-that-use-strict-mode-by-default">JavaScript Features that Use Strict Mode by Default</a></p>
</li>
<li><p><a class="post-section-overview" href="#conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-strict-mode-in-javascript">What is Strict Mode in JavaScript?</h2>
<p>Strict mode is a feature in JavaScript that was introduced in ECMAScript 5. It lets you write code in such a way that follows stricter rules.</p>
<p>When strict mode is enabled, the JavaScript engine enforces additional constraints. This means you may be able to catch some common errors that would have otherwise gone unnoticed. It also helps you write cleaner and more secure code.</p>
<h2 id="heading-how-to-use-strict-mode-in-javascript">How to Use Strict Mode in JavaScript</h2>
<p>You can use JavaScript strict mode in two ways. You can either enable strict mode for an entire JavaScript file, or you can enable it within the scope of a function.</p>
<p>To enable strict mode for the whole JavaScript file, you simply add the string <code>"use strict"</code> to the top of your code.</p>
<pre><code class="lang-javascript"><span class="hljs-meta">"use strict"</span>

<span class="hljs-comment">// Your code goes here...</span>
</code></pre>
<p>For functions, you can enable strict mode by placing the <code>"use strict"</code> string at the top of your function body.</p>
<pre><code class="lang-javascript"><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-meta">  "use strict"</span>
  <span class="hljs-comment">// Function body goes here...</span>

}
</code></pre>
<p>You must place the <code>"use strict"</code> string at the top of the file or function body. Otherwise, it will not work.</p>
<p>But you are allowed to add comments above the <code>"use strict"</code> string. Apart from comments, everything else should be below <code>"use strict"</code> for it to work.</p>
<h2 id="heading-difference-between-strict-mode-and-regular-javascript">Difference Between Strict Mode and Regular JavaScript</h2>
<p>Now, let's see some of the rules that strict mode enforces which aren't enforced when writing code in regular JavaScript.</p>
<h3 id="heading-using-an-undeclared-variable">Using an Undeclared Variable</h3>
<p>When writing JavaScript code in strict mode, you must declare all variables and objects before use. This is useful because it helps to prevent creating global variables by accident which can lead to bugs.</p>
<p>Here's an example</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Regular JavaScript</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">regularFunc</span>(<span class="hljs-params"></span>) </span>{
  username = <span class="hljs-string">"Marie"</span>
  <span class="hljs-built_in">console</span>.log(username)
}

regularFunc()
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-01-at-8.20.00-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Regular JS throws no error for the username variable.</em></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Strict mode</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">strictFunc</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-meta">  "use strict"</span>
  username = <span class="hljs-string">"Marie"</span>
  <span class="hljs-built_in">console</span>.log(username)
}

strictFunc()
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-02-at-7.07.08-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Strict mode throws error for undeclared variables.</em></p>
<p>In the <code>regularFunc</code> function, the browser logs the <code>username</code> to the console without any error.</p>
<p>But with the <code>strictFunc</code> function which uses strict mode, it throws a reference error.</p>
<p>That's because the <code>username</code> variable hasn't been declared. And strict mode does not allow the use of variables before they are declared.</p>
<h3 id="heading-duplicating-a-parameter-name">Duplicating a Parameter Name</h3>
<p>In non-strict mode, duplicating a parameter name in a function is allowed. Only the last instance of the duplicates is allowed whiles the others are ignored.</p>
<p>But strict mode functions do not allow this. It throws a syntax error in the case of duplicates.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNums</span> (<span class="hljs-params">num, num</span>) </span>{
  <span class="hljs-built_in">console</span>.log(num + num)
}

addNums(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>) <span class="hljs-comment">// 6</span>
</code></pre>
<p>In the example above, the first <code>num</code> parameter is ignored. Only the second one is used. This why the functions returns 6 because 3 + 3 is 6.</p>
<p>But when you define the same parameters in a function using strict mode, you cannot run it because it will throw a syntax error. Strict mode requires each parameter to have a unique name.</p>
<p>That is:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNums</span> (<span class="hljs-params">num, num</span>) </span>{
<span class="hljs-meta">  "use strict"</span>
  <span class="hljs-built_in">console</span>.log(num + num)
}

addNums(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-02-at-9.15.07-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Browser throws an error for duplicate parameter name.</em></p>
<h3 id="heading-using-reserved-future-keywords">Using Reserved Future Keywords</h3>
<p>In JavaScript, there are some keywords reserved for potential future use. And using these keywords as identifiers (such as variables or function names) may likely cause issues in future.</p>
<p>For example, <code>package</code> is one of such keywords. When you're not using strict mode, you can use it to name variables and functions.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> package = <span class="hljs-string">"This is a package"</span>
<span class="hljs-built_in">console</span>.log(package)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-02-at-9.17.36-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log result for using reserved keyword in regular JavaScript.</em></p>
<p>Strict mode doesn't allow the use of these reserved keywords. This ensures compatibility with future versions of JavaScript.</p>
<pre><code class="lang-javascript"><span class="hljs-meta">"use strict"</span>
<span class="hljs-keyword">const</span> package = <span class="hljs-string">"This is a package"</span>
<span class="hljs-built_in">console</span>.log(package)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-02-at-9.22.21-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Using a reserved keyword in strict mode results in a syntax error.</em></p>
<p>Other future reserved keywords include:</p>
<ul>
<li><p><code>implements</code></p>
</li>
<li><p><code>interface</code></p>
</li>
<li><p><code>private</code></p>
</li>
<li><p><code>protected</code></p>
</li>
<li><p><code>public</code></p>
</li>
<li><p><code>static</code></p>
</li>
<li><p><code>yield</code></p>
</li>
<li><p><code>arguments</code></p>
</li>
</ul>
<h3 id="heading-use-of-deprecated-features">Use of Deprecated Features</h3>
<p>Strict mode restricts the use of JavaScript's deprecated features like <code>arguments.caller</code>, <code>arguments.callee</code>, and so on.</p>
<p>These are disallowed due to security and performance concerns. But non-strict mode allows using them.</p>
<p>Let's see an example of using <code>arguments.caller</code> in both strict and non-strict mode.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// non-strict mode</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outerFunction</span>(<span class="hljs-params"></span>) </span>{
  innerFunction();
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">innerFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(innerFunction.caller); <span class="hljs-comment">// Example of .caller</span>
}

outerFunction();
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-02-at-10.18.11-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><code>arguments.caller</code> works in non-strict mode without any errors.</p>
<p>Using <code>.caller</code> on the <code>innerFunction</code> logs the <code>outerFunction</code> which calls the inner function to the console. It works alright in non-strict mode.</p>
<p>But using it in strict mode will cause JavaScript to throw an error like in the example below.</p>
<pre><code class="lang-javascript"><span class="hljs-meta">"use strict"</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outerFunction</span>(<span class="hljs-params"></span>) </span>{
  innerFunction();
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">innerFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(innerFunction.caller); <span class="hljs-comment">// Example of .caller</span>
}

outerFunction();
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-02-at-10.23.14-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Strict mode throws an "Uncaught TypeError" for using deprecated features.</em></p>
<h3 id="heading-assignment-to-a-read-only-property">Assignment to a Read-Only Property</h3>
<p>In non-strict mode, when you attempt to assign a new value to a read-only property, the assignment will not modify the property's value. But it will not throw any error. Instead, the assignment silently fails, and the property retains its original value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj = {}

<span class="hljs-built_in">Object</span>.defineProperty(obj, <span class="hljs-string">'key'</span>, { <span class="hljs-attr">value</span>: <span class="hljs-number">10</span>, <span class="hljs-attr">writable</span>: <span class="hljs-literal">false</span> })
obj.key = <span class="hljs-number">20</span>

<span class="hljs-built_in">console</span>.log(obj.key)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-02-at-11.23.16-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log result for</em> <code>object.key</code></p>
<p>This example defines a new empty object <code>obj</code>. And using <code>Object.defineProperty</code>, a new property <code>key</code> is added to <code>obj</code>. This <code>key</code> property is set as a read-only property.</p>
<p>As you can see from log result, there is no error when you try to update the value of <code>key</code>. And the <code>key</code> property maintains the original value of <code>10</code>.</p>
<p>In strict mode, however, attempting to update the value of the property will result in a <code>TypeError</code>. This stricter enforcement helps catch potential errors early.</p>
<pre><code class="lang-javascript"><span class="hljs-meta">"use strict"</span>
<span class="hljs-keyword">const</span> obj = {}

<span class="hljs-built_in">Object</span>.defineProperty(obj, <span class="hljs-string">'key'</span>, { <span class="hljs-attr">value</span>: <span class="hljs-number">10</span>, <span class="hljs-attr">writable</span>: <span class="hljs-literal">false</span> })
obj.key = <span class="hljs-number">20</span>

<span class="hljs-built_in">console</span>.log(obj.key)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-02-at-11.43.54-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Strict mode throws an error when assigning a new value to read-only property.</em></p>
<h2 id="heading-javascript-features-that-use-strict-mode-by-default">JavaScript Features that Use Strict Mode by Default</h2>
<p>Some JavaScript features do not require you to explicitly invoke <code>"use strict"</code>. By default, strict mode is applied to prevent common errors and ensure compatibility with future JavaScript versions.</p>
<p>Examples of such contexts include the following:</p>
<ul>
<li><p>ES6 classes</p>
</li>
<li><p>ES6 modules</p>
</li>
<li><p>Arrow functions</p>
</li>
<li><p>Tagged template literals</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>JavaScript started off as a language for adding simple interactivity to web pages. But has since evolved to become one of the most-used programming language for creating both simple and complex applications.</p>
<p>As the language evolves, some of its old defects still remain. The strict mode feature helps JavaScript developers deal with some of the issues these defects cause.</p>
<p>In this article, you've learned about the strict mode, how to use it, and how it differs from writing JavaScript code in non-strict mode. You've also learned various contexts in JavaScript where strict mode rules are enforced by default.</p>
<p>Thanks for reading. And happy coding! For more in-depth tutorials, feel free to <a target="_blank" href="https://www.youtube.com/@DevAfterHours">subscribe to my YouTube channel</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are Falsy Values in JavaScript? Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript, every value has a boolean equivalent. This means it can either be evaluated as true (truthy value) or false (falsy value) when used in a boolean context. But what is a boolean context? It's a situation where a boolean value is expected... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-falsey-values-in-javascript/</link>
                <guid isPermaLink="false">66d45defd7a4e35e38434955</guid>
                
                    <category>
                        <![CDATA[ Conditionals ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Tue, 30 Jan 2024 15:27:25 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-29-at-12.22.42-AM.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript, every value has a boolean equivalent. This means it can either be evaluated as true (truthy value) or false (falsy value) when used in a boolean context.</p>
<p>But what is a boolean context? It's a situation where a boolean value is expected. Examples include if statements, logical operators, and so on. When you use a non-boolean value in a boolean context, JavaScript will convert the value to its boolean equivalent.</p>
<p>In this article, you will learn about falsy values in JavaScript and how to check if a value is falsy. The article also covers some best practices to consider when checking the boolean equivalent of a value.</p>
<p>Let's get started!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#the-six-falsy-values-in-javascript">The Six Falsy Values in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-check-if-a-value-is-falsy-in-javascript">How to Check if a Value is Falsy</a></p>
</li>
<li><p><a class="post-section-overview" href="#truthy-values-that-may-appear-as-falsy-values">Truthy Values That May Appear as Falsy Values</a></p>
</li>
<li><p><a class="post-section-overview" href="#best-practices-when-checking-boolean-equivalent">Best Practices When Checking Boolean Equivalent</a></p>
</li>
<li><p><a class="post-section-overview" href="#conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-the-six-falsy-values-in-javascript">The Six Falsy Values in JavaScript</h2>
<p>Falsy values in JavaScript are unique because there are only six of them. Apart from these six, all other values are truthy values.</p>
<p>You can commit these falsy values to memory. That way, when you come across any value that isn't one of the six, you know it's a <code>truthy</code> value.</p>
<p>Here are the six falsy values in JavaScript:</p>
<ul>
<li><p><code>false</code>: The boolean value <code>false</code>.</p>
</li>
<li><p><code>0</code>: The number zero.</p>
</li>
<li><p><code>""</code> or <code>''</code> or ````: An empty string.</p>
</li>
<li><p><code>null</code>: The null keyword, representing the absence of any object value.</p>
</li>
<li><p><code>undefined</code>: The undefined keyword, representing an uninitialized value.</p>
</li>
<li><p><code>NaN</code>: Stands for "Not a Number". It represents a special value returned from an operation that should return a numeric value but doesn't.</p>
</li>
</ul>
<p>Now, let's see some practical examples of these falsys valsues in JavaScript.</p>
<h3 id="heading-example-1-the-boolean-value-false">Example 1 – The boolean value <code>false</code>.</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> isOnline = <span class="hljs-literal">false</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkStatus</span>(<span class="hljs-params">status</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Boolean</span>(status) ? <span class="hljs-string">"ONLINE"</span> : <span class="hljs-string">"OFFLINE"</span>
}

checkStatus(isOnline) <span class="hljs-comment">// "OFFLINE"</span>
</code></pre>
<p>When you pass the <code>isOnline</code> variable to the <code>checkStatus</code> function, it returns the string <code>"OFFLINE"</code>. And this is because the value is <code>false</code> in this context. Here, we are using a tenary operator based on the boolean value of the <code>status</code> argument.</p>
<h3 id="heading-example-2-the-number-zero">Example 2 – The number zero.</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> unreadMessages = <span class="hljs-number">0</span>
<span class="hljs-keyword">let</span> hasUnreadMessages = <span class="hljs-built_in">Boolean</span>(unreadMessages)
<span class="hljs-built_in">console</span>.log(hasUnreadMessages) <span class="hljs-comment">// false</span>
</code></pre>
<p>This examples checks whether a user has unread messages or not. We use the in built <code>Boolean</code> function to get the boolean value of the <code>unreadMessages</code> variable. This means anytime the number of <code>unreadMessages</code> is zero, <code>hasUnreadMessages</code> will be <code>false</code>.</p>
<h3 id="heading-example-3-an-empty-string">Example 3 – An empty string.</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> userInput = <span class="hljs-string">""</span>;
<span class="hljs-keyword">let</span> defaultText = <span class="hljs-string">"No input provided"</span>;

<span class="hljs-keyword">let</span> displayText = <span class="hljs-built_in">Boolean</span>(userInput) || defaultText;

<span class="hljs-built_in">console</span>.log(displayText); <span class="hljs-comment">// No input provided</span>
</code></pre>
<p>This example uses the logical OR operator <code>||</code> to determine the value of the <code>displayText</code>. It will assign the value of <code>userInput</code> to <code>displayText</code> if it's a truthy value. Or it will assign the <code>defaultText</code> to <code>displayText</code> if <code>userInput</code> is a falsy value as it is in this case.</p>
<h3 id="heading-example-4-null">Example 4 – <code>null</code></h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> user = <span class="hljs-literal">null</span>;

<span class="hljs-keyword">if</span> (user &amp;&amp; user.name) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Welcome, "</span> + user.name + <span class="hljs-string">"!"</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Please log in to access the website."</span>);
}
</code></pre>
<p>The following example assumes the <code>user</code> isn't logged in and so the value of <code>user</code> object is <code>null</code>. This means the <code>if</code> statement will evaluate to <code>false</code>. The expected behaviour then will be that the code executes the <code>else</code> block.</p>
<h3 id="heading-example-5-undefined">Example 5 – <code>undefined</code></h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age;
<span class="hljs-keyword">if</span> (age === <span class="hljs-literal">undefined</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The age is undefined."</span>);
}
</code></pre>
<p>When a variable is declared but not initialized with a value, JavaScript assigns it the value <code>undefined</code> by default. In the code example above, since the <code>age</code> variable is declared but not assigned a value, its value is <code>undefined</code>. This means the code in the <code>if</code> statement will run.</p>
<h3 id="heading-example-6-nan">Example 6 – <code>NaN</code></h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> value1 = <span class="hljs-string">"Ten"</span>
<span class="hljs-keyword">let</span> value2 = <span class="hljs-number">10</span>

<span class="hljs-keyword">let</span> result = value1 / value2

<span class="hljs-keyword">if</span> (<span class="hljs-built_in">isNaN</span>(result)) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The result is not a number."</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(result);
}
</code></pre>
<p>This example divides <code>value1</code> (a string) by <code>value2</code> (a number). This will result in a <code>NaN</code> value because you cannot divide a string by a number. This means the code in the <code>if</code> block will run. And log <code>The result is not a number</code> to the console.</p>
<h2 id="heading-how-to-check-if-a-value-is-falsy-in-javascript">How to Check if a Value is Falsy in JavaScript</h2>
<p>A safe way to check whether a value is falsy or not is to use the <code>Boolean</code> function. The <code>Boolean</code> function returns the boolean value of the value of the argument passed to it.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-literal">false</span>))
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-number">0</span>))
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-string">""</span>))
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-literal">null</span>))
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-literal">undefined</span>))
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-literal">NaN</span>))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-23-at-6.16.42-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Boolean log results for all six falsy values.</em></p>
<p>Here, we are checking the boolean value of all six falsy values. And as expected, each returns <code>false</code>.</p>
<p>When you pass any other value that's not one of these six falsy values to the Boolean function, it will return <code>true</code>.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-string">'hello'</span>))
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-number">24</span>))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-23-at-6.24.35-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example boolean log results for truthy values.</em></p>
<h2 id="heading-truthy-values-that-may-appear-as-falsy-values">Truthy Values that May Appear as Falsy Values</h2>
<p>There are some truthy values that, at a glance, may appear to be falsy values but aren't. As already mentioned, only six values in JavaScript are falsy values. Anything else is a truthy value.</p>
<p>The following are some of those values that aren't falsy but may appear as such.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-string">'false'</span>)) <span class="hljs-comment">// An empty object</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-string">' '</span>)) <span class="hljs-comment">// An empty object</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>(<span class="hljs-string">'0'</span>)) <span class="hljs-comment">// An empty object</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>([])) <span class="hljs-comment">// An empty array</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Boolean</span>({})) <span class="hljs-comment">// An empty object</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-24-at-8.09.17-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log results for truthy values that appear as falsy.</em></p>
<p>The first three strings contains text that may look like falsy values. First is the string with the text <code>"false"</code>, another one with some whitespace, and the third with zero.</p>
<p>Remember that the only string considered a falsy value is an empty string. All non-empty strings in JavaScript are truthy values including strings with only whitespace.</p>
<p>Also, note that unlike strings, both an empty array and an empty object return <code>true</code> in a boolean context.</p>
<h2 id="heading-best-practices-when-checking-boolean-equivalent">Best Practices When Checking Boolean Equivalent</h2>
<p>The following tips will help make your code more readable and easier to maintain.</p>
<h3 id="heading-1-use-the-boolean-function">1. Use the Boolean function</h3>
<p>It's always better to use the built-in <code>Boolean</code> function when you want to check whether a value is truthy or falsy. The function works by coercing any value into its corresponding boolean. It also makes your intention clear to anyone reading the code.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example without the Boolean function</span>
<span class="hljs-keyword">const</span> value = <span class="hljs-string">''</span>; 

<span class="hljs-keyword">if</span> (value) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'It is a TRUTHY value'</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'It is a FALSY value'</span>);
}

<span class="hljs-comment">// Example with the Boolean function</span>
<span class="hljs-keyword">const</span> value = <span class="hljs-string">''</span>

<span class="hljs-keyword">if</span> (<span class="hljs-built_in">Boolean</span>(value)) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'It is a TRUTHY value'</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'It is a FALSY value'</span>);
}
</code></pre>
<p>Both examples do the same thing. But in the second example, it's explicit that you're checking the boolean representation of the given value.</p>
<h3 id="heading-2-use-strict-equality-instead-of-loose-equality">2. Use strict equality <code>===</code> instead of loose equality <code>==</code></h3>
<p>When you're comparing values for truthiness or falsiness, it's recommended to use strict equality (<code>===</code>) over loose equality (<code>==</code>). Strict equality compares both the value and the type. Loose equality performs type coercion before comparing the values, and this can lead to unexpected results.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Strict Equality Example</span>

<span class="hljs-keyword">if</span> (<span class="hljs-number">1</span> === [<span class="hljs-number">1</span>]) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'EQUAL'</span>)
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'NOT EQUAL'</span>)
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-28-at-11.31.28-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log result for strict equality example.</em></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Loose Equality Example</span>
<span class="hljs-keyword">if</span> (<span class="hljs-number">1</span> == [<span class="hljs-number">1</span>]) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'EQUAL'</span>)
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'NOT EQUAL'</span>)
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-28-at-11.32.20-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log result for loose equality example.</em></p>
<p>Both examples above compare the same values. But the strict equality example logs "NOT EQUAL". This is because the number 1 is not equal to an array containing the number 1. With the loose equality, it coerces the type of the values to make them of the same type. That is why it logs "EQUAL" to the console.</p>
<h3 id="heading-3-add-comments-to-document-your-code">3. Add comments to document your code</h3>
<p>To make your code more readable and easier to maintain, consider adding comments when necessary to explain your logic when dealing with truthy and falsy values.</p>
<p>Documenting your code is a good practice to help developers on your team (or your future self) understand the intended behaviour of a piece of code.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> selectedUser = USER_OBJ

<span class="hljs-comment">// Check if no user is selected</span>
<span class="hljs-keyword">if</span> (!selectedUser) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Please select a user."</span>);
} <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"User address: "</span> + selectedUser.address);
}
</code></pre>
<p>In the example above, the comment added before the <code>if</code> statement makes it clear that the code is checking if no user has been selected.</p>
<p>Using the logical NOT operator (<code>!</code>) can make it seem like you're checking if a user is selected rather than checking if no user is selected. So a comment in an instance like helps provide clarity.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you have learned about the six falsy values in JavaScript and how they differ from truthy values. You also learned about some truthy values that may appear as falsy, but actually aren't. And you also saw some best practices to consider when working with falsy values.</p>
<p>A good understanding of the concept of falsy and truthy values and how they affect comparisons and conditional statement will come in handy when debugging JavaScript applications.</p>
<p>Thanks for reading. And happy coding! For more in-depth tutorials, feel free to <a target="_blank" href="https://www.youtube.com/@DevAfterHours">subscribe to my YouTube channel</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Arrow Functions vs Regular Functions ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript, there are two main ways of writing functions. You can create functions using the regular function syntax. Or you can use the arrow function syntax. In this article, you will learn how to use both options. You'll also learn about the di... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/regular-vs-arrow-functions-javascript/</link>
                <guid isPermaLink="false">66d45de3182810487e0ce10a</guid>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Tue, 16 Jan 2024 22:19:05 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-6.53.58-PM.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript, there are two main ways of writing functions. You can create functions using the regular function syntax. Or you can use the arrow function syntax.</p>
<p>In this article, you will learn how to use both options. You'll also learn about the differences between the two and when it's appropriate to use each of them.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#regular-function-syntax-vs-arrow-function-syntax">Regular Function Syntax vs Arrow Function Syntax</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-access-the-arguments-passed-to-functions">How to Access the Arguments Passed to Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#duplicate-named-parameters">Duplicate Named Parameters</a></p>
</li>
<li><p><a class="post-section-overview" href="#function-hoisting">Function Hoisting</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-handle-this-binding-in-functions">How to Handle "this" Binding in Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-use-functions-as-constructors">How to Use Functions as Constructors</a></p>
</li>
<li><p><a class="post-section-overview" href="#so-which-one-should-you-use">So Which One Should You Use?</a></p>
</li>
</ul>
<h2 id="heading-regular-function-syntax-vs-arrow-function-syntax">Regular Function Syntax vs Arrow Function Syntax</h2>
<p>To understand the difference between the two options, let's begin by looking at their syntax.</p>
<h3 id="heading-regular-function-syntax">Regular function syntax</h3>
<p>The ordinary way of declaring functions in JavaScript is to use the <code>function</code> keyword. Here is an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello '</span> + name
}
</code></pre>
<p>To return a value from a regular function, you have to explicitly use the <code>return</code> keyword. Otherwise the function will return <code>undefined</code>.</p>
<h3 id="heading-arrow-function-syntax">Arrow function syntax</h3>
<p>Arrow functions were introduced with ECMAScript 6 (ES6). They give you a more concside way of defining functions in JavaScript.</p>
<p>Using the same <code>sayHello</code> function from the previous example, let's see how to create it with the arrow function syntax.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sayHello = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello '</span> + name
}
</code></pre>
<p>Unlike regular functions, you don't have to use an explicit return if there's only one statement like the above example. You can write the function on a single line like so.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sayHello = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> <span class="hljs-string">'Hello '</span> + name
</code></pre>
<p>Note how the curly braces are also removed to implicitly return the result of the expression. You can even remove the parenthesis too if there is only one argument. See the example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sayHello = <span class="hljs-function"><span class="hljs-params">name</span> =&gt;</span> <span class="hljs-string">'Hello '</span> + name
</code></pre>
<p>The <code>name</code> is the only argument the function takes. And this means you can remove the parenthesis from the argument and it will still work fine.</p>
<h2 id="heading-how-to-access-the-arguments-passed-to-functions">How to Access the Arguments Passed to Functions</h2>
<p>JavaScript provides a way to access all arguments passed to a function. But the way you acess these arguments depends on the type of function you are working with.</p>
<h3 id="heading-how-to-access-arguments-with-regular-functions">How to access arguments with regular functions</h3>
<p>You can access all the arguments passed to a regular function using the <code>arguments</code> object. The <code>arguments</code> object is an array-like object that holds all the arguments passed to the function.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logNumbers</span>(<span class="hljs-params">num1, num2</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">arguments</span>)
}

logNumbers(<span class="hljs-number">8</span>, <span class="hljs-number">24</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-11-at-5.01.51-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log results of the arguments object</em></p>
<p>As you can see from the log result, the <code>arguments</code> object contains the two numbers passed as arguments to the <code>logNumbers</code> function.</p>
<h3 id="heading-how-to-access-arguments-with-arrow-functions">How to access arguments with arrow functions</h3>
<p>The <code>arguments</code> object is not available in arrow functions. If you try to access it in arrow functions, JavaScript will throw a reference error.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> logNumbers = <span class="hljs-function">(<span class="hljs-params">num1, num2</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">arguments</span>)
}

logNumbers(<span class="hljs-number">8</span>, <span class="hljs-number">24</span>) <span class="hljs-comment">// Uncaught ReferenceError: arguments is not defined</span>
</code></pre>
<p>To access the arguments passed to an arrow function, you can use the rest parameter syntax (<code>...</code>).</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> logNumbers = <span class="hljs-function">(<span class="hljs-params">...args</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(args)
}

logNumbers(<span class="hljs-number">8</span>, <span class="hljs-number">24</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-11-at-11.13.39-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log results for the arguments from an arrow function</em></p>
<p>Using the rest parameter syntax (<code>...</code>), you get access to all the arguments passed to the <code>logNumbers</code> function.</p>
<h2 id="heading-duplicate-named-parameters">Duplicate Named Parameters</h2>
<p>Another difference between regular functions and arrow functions is how they handle duplicates in the named parameters.</p>
<h3 id="heading-duplicate-named-parameters-in-regular-functions">Duplicate named parameters in regular functions</h3>
<p>When a regular function has duplicate names in the parameters, the last parameter with the duplicate name will take precedence. Let's see an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">exampleFunction</span>(<span class="hljs-params">a, b, a</span>) </span>{
  <span class="hljs-built_in">console</span>.log(a, b)
}

exampleFunction(<span class="hljs-string">"first"</span>, <span class="hljs-string">"second"</span>, <span class="hljs-string">"third"</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-9.50.00-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log results for named duplicate parameters</em></p>
<p>In the example above, the <code>third</code> argument overrides the value of the <code>first</code> argument because the last duplicate parameter is the one that takes precedence.</p>
<p>But in "strict mode", using a duplicate named parameter will result in a syntax error.</p>
<pre><code class="lang-javascript"><span class="hljs-meta">"use strict"</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">exampleFunction</span>(<span class="hljs-params">a, b, a</span>) </span>{
  <span class="hljs-built_in">console</span>.log(a, b)
}

exampleFunction(<span class="hljs-string">"first"</span>, <span class="hljs-string">"second"</span>, <span class="hljs-string">"third"</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-10.29.11-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Strict mode doesn't allow using a parameter name more than once</em></p>
<h3 id="heading-duplicate-named-parameters-in-arrow-functions">Duplicate named parameters in arrow functions</h3>
<p>Arrow functions don't allow for the same parameter name to be used more than once in the parameter list. Doing so will result in a syntax error.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> exampleFunction = <span class="hljs-function">(<span class="hljs-params">a, b, a</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(a, b)
}

exampleFunction(<span class="hljs-string">"first"</span>, <span class="hljs-string">"second"</span>, <span class="hljs-string">"third"</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-10.29.11-AM-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Arrow functions do not allow duplicate parameter names</em></p>
<h2 id="heading-function-hoisting">Function Hoisting</h2>
<p>Hoisting in JavaScript is a behaviour where variables and functions are moved to the top of their containing scope during compilation, before the code is executed.</p>
<h3 id="heading-hosting-in-regular-functions">Hosting in regular functions</h3>
<p>Regular functions are hoisted to the top. And you can access and call them even before they are declared.</p>
<pre><code class="lang-javascript">regularFunction()

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">regularFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a regular function."</span>)
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-11.50.43-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log result of calling the regular function before it's declared</em></p>
<p>The above is an example of calling a regular function before it is declared. And it works fine without throwing any error because of function hoisting.</p>
<h3 id="heading-hoisting-in-arrow-functions">Hoisting in arrow functions</h3>
<p>Arrow functions, on the other hand, cannot be accessed before they are initialised.</p>
<pre><code class="lang-javascript">arrowFunction()

<span class="hljs-keyword">const</span> arrowFunction = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is an arrow function."</span>)
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-12.07.39-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log result of calling the arrow function before it's declared</em></p>
<p>Unlike regular functions, attempting to call an arrow function before it's declared will result in a reference error, as you can see from the output above.</p>
<h2 id="heading-how-to-handle-this-binding-in-functions">How to Handle <code>this</code> Binding in Functions</h2>
<p>Regular functions have their own <code>this</code> context. And this is determined dynamically depending on how you call or execute the function.</p>
<p>Arrow functions, on the other hand, do not have their own this context. Instead, they capture the <code>this</code> value from the surrounding lexical context in which the arrow function was created.</p>
<p>The following are two different scenarios using both regular functions and arrow functions. You'll see how the <code>this</code> context is determined.</p>
<h3 id="heading-1-setting-the-this-value-during-a-simple-function-call">1. Setting the <code>this</code> value during a simple function call</h3>
<p>For regular functions, a simple function call sets the <code>this</code> value to the <code>window</code> object (or to <code>undefined</code> if you're using the "strict mode"):</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myRegularFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>)
}

myRegularFunction()
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-4.15.11-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A simple invocation of a regular function sets</em> <code>this</code> to the window object</p>
<pre><code class="lang-javascript"><span class="hljs-meta">"use strict"</span>

<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-built_in">console</span>.log(<span class="hljs-built_in">this</span>)
}

myFunction() <span class="hljs-comment">// udefined</span>
</code></pre>
<p>With arrow functions, a simple function call sets the <code>this</code> value to the surrounding context whether you're using strict mode or not. In the example below, the surrounding context is the global window object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myArrowFunction = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
};

myArrowFunction()
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-4.15.11-PM-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A simple invocation of an arrow function sets</em> <code>this</code> to the window object</p>
<h3 id="heading-2-when-invoking-or-calling-a-method-on-an-object">2. When invoking or calling a method on an object</h3>
<p>When you invoke a method whose value is a regular function, the <code>this</code> value is set to the object on which the method is called. But when the value of the method is an arrow function, the <code>this</code> value is set to the global window object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myObject = {
  <span class="hljs-attr">regularExample</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">"REGULAR: "</span>, <span class="hljs-built_in">this</span>)
  },

  <span class="hljs-attr">arrowExample</span>: <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"ARROW: "</span>, <span class="hljs-built_in">this</span>)
  }
}

myObject.regularExample()
myObject.arrowExample()
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-5.46.04-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log result for a method with a regular function and another with an arrow function</em></p>
<p>While the method with the regular function logs the object to the console, the one with the arrow function logs the global window object instead.</p>
<h2 id="heading-how-to-use-functions-as-constructors">How to Use Functions as Constructors</h2>
<p>For regular functions, you can create a new instance using the <code>new</code> keyword. And this sets the <code>this</code> value to the new instance you've created.</p>
<p>For arrow functions, you cannot use them as constructors. This is because the value of <code>this</code> in arrow functions is lexically scoped – that is, determined by the surrounding execution context. This behaviour does not make them suitable to be used as constructors.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">RegularFuncBird</span>(<span class="hljs-params">name, color</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name
  <span class="hljs-built_in">this</span>.species = color
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>)
}

<span class="hljs-keyword">const</span> ArrowFuncBird = <span class="hljs-function">(<span class="hljs-params">name, color</span>) =&gt;</span> {
  <span class="hljs-built_in">this</span>.name = name
  <span class="hljs-built_in">this</span>.color = color
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>)
}

<span class="hljs-keyword">new</span> RegularFuncBird(<span class="hljs-string">"Parrot"</span>, <span class="hljs-string">"blue"</span>) 
<span class="hljs-keyword">new</span> ArrowFuncBird(<span class="hljs-string">"Parrot"</span>, <span class="hljs-string">"blue"</span>)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-12-at-5.53.17-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log results for attempting to use regular and arrow functions as constructors</em></p>
<p>The <code>RegularFuncBird</code> constructor works fine with the <code>new</code> keyword, but the <code>ArrowFuncBird</code> results in a type error.</p>
<h2 id="heading-so-which-one-should-you-use">So Which One Should You Use?</h2>
<p>There is no straightforward answer to this. Whether you use a regular function or arrow function depends on the specific use case.</p>
<p>It's recommended to use regular function in any of the following cases:</p>
<ul>
<li><p>when you need to use a constructor with the <code>new</code> keyword</p>
</li>
<li><p>when you need the <code>this</code> binding to be dynamically scoped</p>
</li>
<li><p>when you want to use the <code>arguments</code> object</p>
</li>
</ul>
<p>And you can use arrow functions in any of the following cases:</p>
<ul>
<li><p>when you want a more concise syntax for the function</p>
</li>
<li><p>when you need to maintain the lexical scope of <code>this</code></p>
</li>
<li><p>for non-method functions (in most cases)</p>
</li>
</ul>
<p>As you've learned from this article, both are valid ways of defining functions in JavaScript. Remember that choosing between them is not always a matter of personal preference. Rather, it's dependent on the kind of behaviour you expect from the function.</p>
<p>Thanks for reading and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JS DOM Manipulation Best Practices – with Examples ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript, you can manipulate the content of a web page using the Document Object Model (DOM). But how do you write code that is readable, easy to maintain, and not prone to performance issues? That's what we'll cover in this article. I'll discus... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/dom-manipulation-best-practices/</link>
                <guid isPermaLink="false">66d45dd6aad1510d0766b5e9</guid>
                
                    <category>
                        <![CDATA[ best practices ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Fri, 12 Jan 2024 17:41:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/freecodecamp-javascript-benjamin-semah.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript, you can manipulate the content of a web page using the Document Object Model (DOM). But how do you write code that is readable, easy to maintain, and not prone to performance issues?</p>
<p>That's what we'll cover in this article. I'll discuss some important best practices so that you can manipulate the DOM with confidence.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#">Introduction</a></p>
</li>
<li><p><a class="post-section-overview" href="#user-the-domcontentloaded-event">Use the DOMContentLoaded Event</a></p>
</li>
<li><p><a class="post-section-overview" href="#cache-selected-elements">Cache Selected Elements</a></p>
</li>
<li><p><a class="post-section-overview" href="#query-parent-elements-instead-of-document">Query Parent Instead of Document</a></p>
</li>
<li><p><a class="post-section-overview" href="#use-css-classes-to-style-elements">Use CSS Classes to Style Elements</a></p>
</li>
<li><p><a class="post-section-overview" href="#use-innerhtml-with-caution">Use innerHTML With Caution</a></p>
</li>
<li><p><a class="post-section-overview" href="#write-readable-event-listeners">Write Readable Event Listeners</a></p>
</li>
<li><p><a class="post-section-overview" href="#use-event-delegation-to-handle-dom-events">Use Event Delegation to Handle DOM Events</a></p>
</li>
<li><p><a class="post-section-overview" href="#batch-dom-updates-with-fragment">Batch DOM Updates With Fragment</a></p>
</li>
<li><p><a class="post-section-overview" href="#use-the-stoppropagation-method">Use the stopPropagation Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#test-your-dom-manipulation-code">Test your DOM Manipulation code</a></p>
</li>
<li><p><a class="post-section-overview" href="#conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-user-the-domcontentloaded-event">User the <code>DOMContentLoaded</code> Event</h2>
<p>The <code>DOMContentLoaded</code> event is fired when the HTML document is fully loaded. Using this event ensures that your DOM manipulation code runs only after the document is fully loaded.</p>
<p>To use the <code>DOMContentLoaded</code>, add an event listener to the document and listen for the <code>DOMContentLoaded</code> event. This helps prevent any issues that may come up when you try to manipulate elements that are yet to be rendered.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'DOMContentLoaded'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Your DOM manipulation code goes here...</span>
})
</code></pre>
<h2 id="heading-cache-selected-elements">Cache Selected Elements</h2>
<p>When you have frequently used elements, querying the DOM for the same element anytime over and over is inefficient. It's better to query the DOM once and store the result in variables.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> cachedElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'exampleId'</span>)
</code></pre>
<p>This way you can reference the variables anytime you want to use them. This helps improve performance as it reduces unnecessary work.</p>
<h2 id="heading-query-parent-elements-instead-of-document">Query Parent Elements Instead of Document</h2>
<p>When you cache an element, you can also query it to select any of its descendants. This can help improve performance because it limits the scope of the query and reduces the number of times the entire document is queried.</p>
<p>Example:</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">"parent"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"child"</span>&gt;</span>Example paragraph<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>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> parentElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'parent'</span>)

<span class="hljs-comment">// Options 1: Querying entire document ❌</span>
<span class="hljs-keyword">const</span> childFromDocument = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'child'</span>) 

<span class="hljs-comment">// Options 2: Query the parent element ✅</span>
<span class="hljs-keyword">const</span> childFromParent = parentElement.querySelector(<span class="hljs-string">'#child'</span>)
</code></pre>
<p>In the example above is a simple markup containing a <code>#parent</code> div and <code>.child</code> paragraph. Then there are two options for selecting the child element.</p>
<p>Technically, both options are correct and will select the same element. But the difference is in the scope of the query.</p>
<p>Example 1 queries (or searches) the entire document to find and select the child. This is less performant and not even necessary because the parent of the element you intend to select is already cached.</p>
<p>Example 2 narrows the scope of the query (or search) by querying only the parent element and not the whole document. That's why it's preferred because it's more performant – especially when the document is large.</p>
<p>Also, note that the method used for querying the parent is <code>querySelector</code>. Using <code>getElementById</code> to query the parent won't work and will result in an error.</p>
<h2 id="heading-use-css-classes-to-style-elements">Use CSS Classes to Style Elements</h2>
<p>It's best to use CSS classes to style elements instead of using inline styles. Classes are easy to maintain compared to inline styles which can be hard to manage.</p>
<p>The <code>classList</code> property has useful properties like add, remove, toggle, and others that makes it easy to modify styles.</p>
<p>Example:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.styledClass</span> {
  <span class="hljs-attribute">color</span>: red;
}
</code></pre>
<pre><code class="lang-javascript">element.classList.add(<span class="hljs-string">'styledClass'</span>)
</code></pre>
<p>This example uses the <code>.add</code> property of <code>classList</code> to add the <code>styledClass</code> to the element. Assuming you wanted to remove the class from the element, you can easily do so using the <code>.remove</code> property in place of add.</p>
<h2 id="heading-use-innerhtml-with-caution">Use <code>innerHTML</code> with Caution</h2>
<p>The <code>innerHTML</code> property reads and parses HTML markup that you pass to it. This means it can read and run code in a script tag passed to it. And this can pose a security risk to your application.</p>
<p>Where possible, use the <code>innerText</code> or <code>textContent</code> property to render strings. But if you need to use <code>innerHTML</code>, be sure you're using it to insert content from trusted sources. Or sanitize and validate the provided content with a library like DOMPurify.</p>
<p>You can read <a target="_blank" href="https://www.freecodecamp.org/news/innerhtml-vs-innertext-vs-textcontent/#what-is-the-innerhtml-property">this freeCodeCamp article</a> to learn more about <code>innerHTML</code>.</p>
<h2 id="heading-write-readable-event-listeners">Write Readable Event Listeners</h2>
<p>Often you will pass two arguments to event listeners. The first is the event you're listening to and the second is the event handler (the function that fires when the event occurs).</p>
<p>To make your code easy to read and maintain, you can define the event handler function outside of the event listener. Then you can call it within the even listener, like in example 1 below:</p>
<pre><code class="lang-javascript">Example <span class="hljs-number">1</span> ✅

MyElement.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"></span>) </span>{ 
    <span class="hljs-comment">// your logic goes here.. </span>
} 

<span class="hljs-comment">// Example 2 ❌ </span>

myElement.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{ 
    <span class="hljs-comment">// your logic goes here... </span>
})
</code></pre>
<p>Both are technically correct and will do the same thing. But example 1 is preferred because it's easier to read. Also, you can reuse the <code>handleClick</code> function if you need to. This helps you observe the DRY (Don't Repeat Yourself) principle.</p>
<h2 id="heading-use-event-delegation-to-handle-dom-events">Use Event Delegation to Handle DOM Events</h2>
<p>Event delegation is when you attach an event listener on a parent element to listen to events on its descendants. With this technique, you can reduce the number of event listeners to include in your code.</p>
<p>For example, assume you have five buttons inside a parent div:</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">"parent"</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn-1"</span>&gt;</span>1st Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn-2"</span>&gt;</span>2nd Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn-3"</span>&gt;</span>3rd Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn-4"</span>&gt;</span>4th Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn-5"</span>&gt;</span>5th Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> 
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>You can add an event listener to each of the five buttons to listen to a click. Or using event delegation, you can a single event on only the parent div:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> parentElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'parent'</span>) 

parentElement.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(event.target.id) 
}
</code></pre>
<p>In this example, the event to delegated to the parent element. And we're using <code>event.target.id</code> to get the actual button the user clicked. If you are curious, you can <a target="_blank" href="https://stackblitz.com/edit/js-r3qjyd?file=index.html,index.js">run the code on Stackblitz</a> to see how it works.</p>
<p>Event delegation help saves time improve performance. Imagine how this technique can come in handy when dealing with a large amount of dynamic content.</p>
<h2 id="heading-batch-dom-updates-with-fragment">Batch DOM Updates With Fragment</h2>
<p>Frequent updates to the DOM can affect the performance of your application. Try to reduce the number of updates where possible.</p>
<p>A useful feature you can use to batch updates is the <code>.createDocumentFragment</code> property. It allows you to group multiple updates before inserting them into the document. This reduces reflows and makes your code more effecient.</p>
<p>Example without Fragment:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> container = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'container'</span>)

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000</span>; i++) { 
    <span class="hljs-keyword">const</span> listItem = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'li'</span>)
    listItem.textContent = <span class="hljs-string">`Item <span class="hljs-subst">${i}</span>`</span>
    container.appendChild(listItem) 
}
</code></pre>
<p>This code updates with each iteration of the loop. That means the DOM will be update 1,000 times. There is a more efficient way of doing this with the code below that uses fragment.</p>
<p>Example with fragment:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> container = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'container'</span>) 
<span class="hljs-keyword">const</span> fragment = <span class="hljs-built_in">document</span>.createDocumentFragment()

<span class="hljs-comment">// Add multiple list items to the fragment </span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000</span>; i++) { 
    <span class="hljs-keyword">const</span> listItem = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'li'</span>) 
    listItem.textContent = <span class="hljs-string">`Item <span class="hljs-subst">${i}</span>`</span> 
    fragment.appendChild(listItem)
} 

container.appendChild(fragment)
</code></pre>
<p>The code above appends the <code>listItem</code> to the <code>fragment</code> with each iteration of the loop. It only appends the child to the <code>container</code> element after the loop is done running. This means the DOM is updated only once instead of 1,000 times like before.</p>
<h2 id="heading-use-the-stoppropagation-method">Use the <code>stopPropagation</code> Method</h2>
<p>The <code>stopPropagation</code> method controls the flow of events in the DOM. By default, when an event occurs on an element, it bubbles (propagates) through its ancestors.</p>
<p>This event propagating behaviour can sometimes lead to unintended results. The <code>stopPropagation</code> method provides a way to stop the event from propagating to the parent and other ancestors.</p>
<p>Let's take a situation where you have a button inside a parent div. And you want to handle a click event on the button without registering the click on the div:</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">"container"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"button"</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">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> containerDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'container'</span>)
<span class="hljs-keyword">const</span> buttonElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'button'</span>)

containerDiv.addEventListener(<span class="hljs-string">'click'</span>, handleDivClick)
buttonElement.addEventListener(<span class="hljs-string">'click'</span>, handleBtnClick)

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleDivClick</span>(<span class="hljs-params"></span>) </span>{ 
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Div clicked'</span>)
} 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleBtnClick</span>(<span class="hljs-params">event</span>) </span>{ 
    event.stopPropagation()
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Button clicked'</span>)
}
</code></pre>
<p>Without using the <code>stopPropagation</code> method, a click event on the button will also trigger a click event on the parent div. This means both event handlers will run.</p>
<p>But the <code>event.stopPropagation()</code> line in the code will prevent the <code>handleDivClick</code> function from running when a user clicks the button.</p>
<p>You can <a target="_blank" href="https://stackblitz.com/edit/js-wjmnd5?file=index.html,index.js">run the code on Stackblitz</a> to see how it works. Comment out the line with the <code>stopPropagation</code> method and see the difference.</p>
<h2 id="heading-test-your-dom-manipulation-code">Test Your DOM Manipulation Code</h2>
<p>When you write tests, you create scenarios that mimic user interactions or application states. You also verify that your application gives you the expected outcomes.</p>
<p>Testing your DOM manipulation code is a best practice because it will make your code reliable and easy to maintain. It also gives you confidence that your code behaves as expected, even as it evolves over time when you make changes and add features.</p>
<p>You can use testing frameworks and libraries available for JavaScript, such as Jest, Mocha, Jasmine, and others to automate testing your apps.</p>
<p>The following example uses the Jest framework to test DOM Manipulation code for adding a class to an element.</p>
<pre><code class="lang-javascript">test(<span class="hljs-string">'Adding a highlight class changes text color to red'</span>, <span class="hljs-function">() =&gt;</span> {
    myElement.classList.add(<span class="hljs-string">'highlight'</span>);
    expect(getComputedStyle(myElement).color).toBe(<span class="hljs-string">'red'</span>);
});
</code></pre>
<p>Adding the <code>highlight</code> class is expected to change the text color to red. If the test passes, it means your DOM manipulation code works as expected. If not, you will need to figure out what figure out what's wrong and fix the issue.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article you've learned ten best practices to keep in mind when working with the DOM. Some of them are general while others are situation specific. By using these best practices in your workflow, you will be building your web applications with a code base that is easy to maintain.</p>
<p>If you want to dive deep into DOM manipulation, <a target="_blank" href="https://www.freecodecamp.org/news/the-javascript-dom-manipulation-handbook/">I wrote a whole handbook</a> that covers the subject in depth.</p>
<p>Thanks for reading. And happy coding! For more in-depth tutorials, feel free to <a target="_blank" href="https://www.youtube.com/@DevAfterHours">subscribe to my YouTube channel</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The JavaScript DOM Manipulation Handbook ]]>
                </title>
                <description>
                    <![CDATA[ DOM Manipulation is one of the most exciting topics to learn about in JavaScript. This is because one of JavaScript's main uses is to make web pages interactive – and the Document Object Model (DOM) plays a major role in this. The DOM is a powerful t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-javascript-dom-manipulation-handbook/</link>
                <guid isPermaLink="false">66d45deb182810487e0ce114</guid>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Wed, 10 Jan 2024 15:12:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/The-JavaScript-DOM-Manipulation-Handbook-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>DOM Manipulation is one of the most exciting topics to learn about in JavaScript. This is because one of JavaScript's main uses is to make web pages interactive – and the Document Object Model (DOM) plays a major role in this.</p>
<p>The DOM is a powerful tool that allows you to interact with and manipulate the elements on a web page. And this handbook will help you understanding and become confident in working with it.</p>
<p>You will begin by learning what the DOM is and what you can do with it. Then we'll dive into how to select, modyfy, and style DOM elements. You will also learn how to create new elements and add them to your web page.</p>
<p>The handbook also cover topics like how to traverse the DOM what DOM events are, and includes some project ideas for practice.</p>
<p>Let's get started!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#what-is-the-dom">What is the DOM?</a></p>
<ul>
<li><a class="post-section-overview" href="#what-you-can-do-with-the-dom">What you can do with the DOM</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#how-to-select-dom-elements">How to Select DOM Elements</a></p>
<ul>
<li><p><a class="post-section-overview" href="#1-getelementbyid">getElementById</a></p>
</li>
<li><p><a class="post-section-overview" href="#2-getelementsbyclassname">getElementsByClassName</a></p>
</li>
<li><p><a class="post-section-overview" href="#3-getelementsbytagname">getElementsByTagName</a></p>
</li>
<li><p><a class="post-section-overview" href="#4-queryselector">querySelector</a></p>
</li>
<li><p><a class="post-section-overview" href="#5-queryselectorall">querySelectorAll</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#how-to-change-the-content-of-dom-elements">How to Change the Content of DOM Elements</a></p>
<ul>
<li><p><a class="post-section-overview" href="#the-innerhtml-property">The innerHTML Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#security-risks-with-innerhtml">Security Risks with innerHTML</a></p>
</li>
<li><p><a class="post-section-overview" href="#the-innertext-and-textcontent-properties">The innerText and textContent Properties</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#how-to-work-with-attributes-of-dom-elements">How to Work with Attributes of DOM Elements</a></p>
<ul>
<li><p><a class="post-section-overview" href="#the-getattribute-method">The getAttribute Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#the-setattribute-method">The setAttribute Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#the-removeattribute-method">The removeAttribute Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#the-hasattribute-method">The hasAttribute Method</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#how-to-change-the-styles-on-dom-elements">How to Change the Styles on DOM Elements</a></p>
<ul>
<li><p><a class="post-section-overview" href="#setting-styles-with-the-style-property">Setting Styles with the .style Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#setting-styles-with-classes">Setting Styles with Classes</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#how-to-traverse-the-dom">How to Traverse the DOM</a></p>
<ul>
<li><p><a class="post-section-overview" href="#difference-between-a-node-and-an-element">Difference Between a Node and an Element</a></p>
</li>
<li><p><a class="post-section-overview" href="#selecting-a-parent-with-parentnode-vs-parentelement">Selecting a Parent with parentNode vs parentElement</a></p>
</li>
<li><p><a class="post-section-overview" href="#selecting-elements-with-childnodes-vs-children">Selecting Elements with childNodes vs children</a></p>
</li>
<li><p><a class="post-section-overview" href="#selecting-the-first-or-last-child-element">Selecting the First or Last Child/Element</a></p>
</li>
<li><p><a class="post-section-overview" href="#selecting-a-sibling-of-nodes-in-the-dom">Selecting a Sibling of Nodes in the DOM</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#dom-events-and-event-listeners">DOM Events and Event Listeners</a></p>
<ul>
<li><p><a class="post-section-overview" href="#difference-between-event-listener-and-event-handler">Difference Between Event Listener and Event Handler</a></p>
</li>
<li><p><a class="post-section-overview" href="#three-ways-to-register-events-in-javascript">Three Ways to Register Events in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#practice-challenge">Practice Challenge</a></p>
</li>
<li><p><a class="post-section-overview" href="#solution-to-practice-challenge">Solution to Practice Challenge</a></p>
</li>
<li><p><a class="post-section-overview" href="#the-event-object">The Event Object</a></p>
</li>
<li><p><a class="post-section-overview" href="#types-of-events">Types of Events</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#event-flow-in-javascript">Event Flow in JavaScript</a></p>
<ul>
<li><p><a class="post-section-overview" href="#event-bubbling">Event Bubbling</a></p>
</li>
<li><p><a class="post-section-overview" href="#event-capturing">Event Capturing</a></p>
</li>
<li><p><a class="post-section-overview" href="#the-event-stoppropagation-method">The Event stopPropagation Method</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#js-dom-manipulation-project-ideas">JS DOM Manipulation Projects Ideas</a></p>
</li>
<li><p><a class="post-section-overview" href="#conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-the-dom">What is the DOM?</h2>
<p>DOM stands for Document Object Model. But what does that mean? Let's break it down.</p>
<p>The <strong>Document</strong> part refers to the webpage you see in the browser. Specifically, the HTML Document which handles the structure of the page's content. This includes the text, images, links, and other elements that make up the page.</p>
<p><strong>Object</strong> means the elements like images, headers, and paragraphs are treated like objects. Each object has its properties (like id, class, style) and methods. Using these properties and methods, you can manipulate the elements.</p>
<p>The <strong>Model</strong> in DOM means it's a representation or copy of the HTML document as a hierarchical tree. This tree includes all the elements. And it captures the parent-child relationships between them.</p>
<p>The DOM is always identical to the HTML document. Browsers ensure that they are in sync. So if something changes in the HTML, the DOM changes too, and vice versa.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/JavaScript--2-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A graphical representation of the HTML DOM tree</em></p>
<p>At the top of the hierarchy is the Document object. It has only one child – the <code>html</code> element. The <code>html</code> element, also known as the root element, has two children, the <code>head</code> and <code>body</code> elements. And each of them also have their own children elements.</p>
<p>The parent-child relationship between the elements is what allows you to traverse or move between and select them. More on that later.</p>
<h3 id="heading-what-you-can-do-with-the-dom">What You Can Do With the DOM</h3>
<p>DOM manipulation allows developers to interact with the structure, style, and content of web pages. The following are some of the things you can do with the DOM:</p>
<ul>
<li><p>Change and remove existing elements in the DOM.</p>
</li>
<li><p>Create and add new elements to the page.</p>
</li>
<li><p>Change the styles for elements.</p>
</li>
<li><p>Add event listeners to the elements to make them interactive.</p>
</li>
</ul>
<h2 id="heading-how-to-select-dom-elements">How to Select DOM Elements</h2>
<p>To do something with DOM elements, you first have to select or access the element in question. In this section, you will learn some common methods for selecting DOM elements.</p>
<p>Let's use the following phonebook markup to show how the various DOM selector methods work.</p>
<pre><code class="lang-html">  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"page-title"</span>&gt;</span>Phonebook<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"family"</span>&gt;</span>Marie<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">class</span>=<span class="hljs-string">"family"</span>&gt;</span>Jose<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">class</span>=<span class="hljs-string">"work"</span>&gt;</span>Anne<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">class</span>=<span class="hljs-string">"work"</span>&gt;</span>Joan<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>The markup includes a header with an id of <code>page-title</code> and four paragraphs. The first two paragraphs both have a class of <code>family</code>, and the last two have a class of <code>work</code>.</p>
<h3 id="heading-1-getelementbyid">1. getElementById</h3>
<p>You use this method to select elements with an id attribute. Ids are unique identifiers. For example, if a header element has an id attribute with a value of "page-title", no other element on the page should also have an id with the same value.</p>
<p>This means anytime you use the <code>getElementById</code> method, you are going to select only one element from the DOM.</p>
<p>Let's look at an example:</p>
<p>The <code>h1</code> header has an id value of <code>page-title</code>. Here is how you can select it using the <code>getElementById</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> titleElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"page-title"</span>)
<span class="hljs-built_in">console</span>.log(titleElement)
</code></pre>
<p>The example selects the header element and assigns it to the <code>titleElement</code> variable.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-02-at-9.01.01-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Result of accessing element with getElementById method.</em></p>
<p>If there's no element in the DOM with the given id, the <code>getElementById()</code> method will return <code>null</code>.</p>
<h3 id="heading-2-getelementsbyclassname">2. getElementsByClassName</h3>
<p>You can use this method to select more than one object. This method takes in the value of a class attribute as an argument and selects all elements in the DOM that has the given class. Unlike ids, you can give the same class value for different HTML elements.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> famContacts = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">"family"</span>)
<span class="hljs-built_in">console</span>.log(famContacts)
</code></pre>
<p>This returns an HTML collection of all elements with the given class. The log statement will print the following in the console:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-01-at-10.35.51-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The</em> <code>getElementsByClassName()</code> method returns an HTML collection.</p>
<p>Note: The HTML collection looks like an array, but it is not. You can access the elements using bracket notation just as you would with an array – but you cannot apply array methods like <code>map</code>, <code>filter</code>, and <code>forEach</code> on it.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(famContacts[<span class="hljs-number">0</span>])
</code></pre>
<p>This will get the first element in the HTML collection, which is the paragraph with the name Marie.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-02-at-9.03.35-AM-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Result of accessing HTMLCollection element with bracket notation.</em></p>
<p>But what if you wanted to loop through all the elements in the <code>famContacts</code> HTML collection? You'd first need to convert the HTML collection into an array. Then you could use any of the array methods.</p>
<p>A simple way to create an array from the HTML collection is to use the spread operator, like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> famContactsArray = [...famContacts]

famContactsArray.forEach(<span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(element))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-02-at-9.06.48-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A result of logging all elements in the HTMLCollection.</em></p>
<p>Using the <code>forEach</code> method, you can access each of the items in the <code>famContactsArray</code>. The browser will throw an error if you try to apply an array method like <code>map</code> to the HTML collection without first creating an array from it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-01-at-11.57.27-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Error message when you use array methods on an HTMLCollection.</em></p>
<h3 id="heading-3-getelementsbytagname">3. getElementsByTagName</h3>
<p>This method will select elements using their tag name. For example, <code>getElementByTagName('p')</code> will select all paragraphs on the page.</p>
<p>Like <code>getElementsByClassName</code>, this method also returns an HTML collection of the selected elements.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> allContacts = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'p'</span>)
<span class="hljs-built_in">console</span>.log(allContacts)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-02-at-8.39.36-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>An HTMLCollection containing all paragraph elements.</em></p>
<p>You can create an array from the HTML collection and use any of the array methods on it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> allContactsArray = [...allContacts]

allContactsArray.map(<span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(element))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-02-at-9.08.26-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Result of using the map method on</em> <code>allContactsArray</code>.</p>
<h3 id="heading-4-queryselector">4. querySelector</h3>
<p>You can use this method to select any HTML element in the DOM. It returns only one element: the first element that matches the given selector.</p>
<p>The <code>querySelector</code> method works like how CSS selectors work.</p>
<p>For example, what do you do when you want to select an element with an id? You use the hash <code>#</code> symbol. How about when you want to select elements with a class? You put a dot <code>.</code> in front of the class name.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> firstWorkContact = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.work'</span>)
<span class="hljs-built_in">console</span>.log(firstWorkContact)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-02-at-11.38.12-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>An example of using the</em> <code>querySelector</code> method.</p>
<p>The example above returns only the first element with a class of <code>work</code> and ignores the rest.</p>
<p>Let's see another example to show how querySelector works like CSS selectors. The following is a <code>div</code> element with four buttons:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>First button<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>Second button<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>Third button<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>Fourth button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>Assuming you wanted to select the third button, you could use <code>querySelector</code> like the one below. The code uses the CSS <code>nth-child</code> selector to get the third button inside the div.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> thirdBtn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'div button:nth-child(3)'</span>)
<span class="hljs-built_in">console</span>.log(thirdBtn)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-02-at-2.42.48-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Result of selecting the third button with</em> <code>querySelector</code> method.</p>
<p>But what if you want to select all four button elements and not only the first one? Then you could use the <code>querySelectorAll</code> method instead.</p>
<h3 id="heading-5-queryselectorall">5. querySelectorAll</h3>
<p>Like the <code>querySelector</code> method, <code>querySelectorAll</code> also selects HTML elements using CSS selectors. The difference is that it returns all elements that match the selector instead of returning only the first one.</p>
<p>Using the previous example, let's select all the buttons with <code>querySelectorAll</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> allBtns = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'button'</span>)
<span class="hljs-built_in">console</span>.log(allBtns)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-02-at-3.04.18-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The</em> <code>querySelectorAll</code> method returns a NodeList of selected elements.</p>
<p>Note: <code>querySelectorAll</code> returns a <code>NodeList</code>. A <code>NodeList</code> is slightly different from an HTML collection. You don't need to convert it to an array to apply a method like <code>forEach</code> on it.</p>
<pre><code class="lang-javascript">allBtns.forEach(<span class="hljs-function"><span class="hljs-params">btn</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(btn))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-02-at-3.00.19-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Result of using</em> <code>forEach</code> method on the NodeList.</p>
<p>But you still cannot apply array methods like <code>map</code>, <code>filter</code>, and others on a NodeList. You will need to first create an array from it.</p>
<p>You can read this <a target="_blank" href="https://www.freecodecamp.org/news/dom-manipulation-htmlcollection-vs-nodelist/">freeCodeCamp article on the difference between HTML collection and NodeList</a> to learn more.</p>
<h2 id="heading-how-to-change-the-content-of-dom-elements">How to Change the Content of DOM Elements</h2>
<p>So far you've learned about different ways to select DOM elements. But that is only the beginning. Now, let's see how you can manipulate the DOM to change the content of a webpage.</p>
<p>The first thing you need to do is to select the element. You can do that using any of the methods you learned from the previous section.</p>
<p>After selecting the element, there are several methods you can use to add or update the content.</p>
<h3 id="heading-the-innerhtml-property">The <code>innerHTML</code> Property</h3>
<p>This is a method that allows you to read or update both the structure and content and structure of elements. Let's see an example of how you can use the <code>innerHTML</code> method.</p>
<p>The following is some markup of three paragraphs, each with an id.</p>
<pre><code class="lang-html">  <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"topic"</span>&gt;</span>JS array methods<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-method"</span>&gt;</span>map<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">"second-method"</span>&gt;</span>filter<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-03-at-8.17.55-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Simple markup with three paragraph elements</em></p>
<p>You can read or get the content of the any of the paragraphs using <code>innerHTML</code>. For example, let's get the content of the first paragraph.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> topicElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#topic'</span>)
<span class="hljs-built_in">console</span>.log(topicElement.innerHTML)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-03-at-8.10.36-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log statement of the</em> <code>innerHTML</code> of the <code>topicElement</code></p>
<p>Now, let's say you want to update the topic from "JS array methods" to "JavaScript array methods". You can do that by assigning the new text to the <code>innerHTML</code> of the element.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> topicElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#topic'</span>)
topicElement.innerHTML = <span class="hljs-string">"JavaScript array methods"</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-03-at-8.16.59-AM-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The topic is updated from "JS Array methods" to "JavaScript array methods"</em></p>
<p>With <code>innerHTML</code>, you can change more than just the content. You can also change the HTML structure of the element. For example, if you want to make the word "JavaScript" bold, you could do this:</p>
<pre><code class="lang-javascript">topicElement.innerHTML = <span class="hljs-string">"&lt;b&gt;JavaScript&lt;/b&gt; array methods"</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-03-at-8.27.45-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The word "JavaScript" is made bold using innerHTML</em></p>
<h3 id="heading-security-risks-with-innerhtml">Security Risks With <code>innerHTML</code></h3>
<p>Using the <code>innerHTML</code> poses potential security risks. An example is <a target="_blank" href="https://www.freecodecamp.org/news/cross-site-scripting-what-is-xss/">cross-site scripting (XSS) attacks</a>.</p>
<p>If the content you're inserting comes from user input or any untrusted source, be sure to validate and sanitize it before using <code>innerHTML</code> to prevent XSS attacks. You can use a library like <a target="_blank" href="https://www.npmjs.com/package/dompurify">DOMPurify</a> to do this.</p>
<p>Also, if you are working with plain text content, consider using methods like <code>innerText</code> and <code>textContent</code>.</p>
<h3 id="heading-the-innertext-and-textcontent-properties">The <code>innerText</code> and <code>textContent</code> Properties</h3>
<p>Both <code>innerText</code> and <code>textContent</code> ignore HTML tags and treat them as part of a string. You can use both methods to read or update the text of DOM elements.</p>
<p>A key difference between the two is in how they treat the text. Using <code>innerText</code> returns the text as it appears on the screen. And using <code>textContent</code> returns text as it appears in the markup. Let's see an example below.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Key =<span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"display: none;"</span>&gt;</span>     ABC123<span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-03-at-10.03.41-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A paragraph element with the some text and a hidden span element inside</em></p>
<p>The example includes a paragraph element. Inside the paragraph is a span that contains a key. The key does not appear on screen because its inline style is set to a display of none.</p>
<p>Now, let's select the paragraph and print both the <code>innerText</code> value and <code>textContent</code> value to see the difference.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> paragraph = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'p'</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"innerText: "</span>, paragraph.innerText)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"textContent: "</span>, paragraph.textContent)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-03-at-10.06.11-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Result of log statement for</em> <code>innerText</code> and <code>textContent</code>.</p>
<p>Note how <code>innerText</code> returns the text as it appears on the screen (without the value of the key which is hidden with CSS). And note how <code>textContent</code> returns the text including hidden elements and whitespaces.</p>
<p>Let's see another example for adding text to an element. The following code includes two paragraphs, each with bold text and an empty span, as well as a horizontal line between them.</p>
<pre><code class="lang-html">  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">b</span>&gt;</span>innerText Example<span class="hljs-tag">&lt;/<span class="hljs-name">b</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"inner-text"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">hr</span>&gt;</span>    

  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">b</span>&gt;</span>textContent Example<span class="hljs-tag">&lt;/<span class="hljs-name">b</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"textContent"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-03-at-10.48.11-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example to demo the</em> <code>innerText</code> and <code>textContent</code> properties</p>
<p>Now, let's select the two span elements and add the same text to them. This will help you better understand the difference between <code>innerText</code> and <code>textContent</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> example1 = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#inner-text'</span>);
<span class="hljs-keyword">const</span> example2 = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#text-content'</span>);

<span class="hljs-keyword">let</span> address = <span class="hljs-string">`
  ABC Street,
  Spintex Road,
  Accra,
  Ghana.
`</span>;

example1.innerText = address;
example2.textContent = address;
</code></pre>
<p>The code gives the same variable <code>address</code> to the two examples. The first uses <code>innerText</code> and the second uses <code>textContent</code>. See the results below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-03-at-10.46.46-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Result of updating content with</em> <code>innerText</code> and <code>textContent</code>.</p>
<p>Notice how <code>innerText</code> uses the line breaks but the <code>textContent</code> example doesn't.</p>
<p>Another key difference between the two methods is how they behave when used inside loops. <code>innerText</code> can be slower than <code>textContent</code> when dealing with bulk operations or frequent updates in a loop.</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/innerhtml-vs-innertext-vs-textcontent/">Read this freeCodeCamp article</a> to learn more about the difference between <code>innerHTML</code>, <code>innerText</code>, and <code>textContent</code>.</p>
<h2 id="heading-how-to-work-with-attributes-of-dom-elements">How to Work with Attributes of DOM Elements</h2>
<p><a target="_blank" href="https://www.freecodecamp.org/news/html-attributes-explained/">HTML attributes</a> provide useful information about HTML elements. These attributes are always included in the opening tag of the element. An attribute is made up of a name and a value (though there are exceptions where only a name is present).</p>
<p>As the browser generates the DOM based on the HTML structure, it translates these attributes into dynamic properties of the DOM objects.</p>
<p>Here's an example:</p>
<p>Assume there's a button in the HTML document with the following attributes:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myBtn"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Click Here<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>For this example, the browser will create an <code>HTMLButtonElement</code> object in the DOM. And the object will have properties matching the attributes.</p>
<ul>
<li><p><code>HTMLButtonElement.id</code> with a value of <code>myBtn</code>.</p>
</li>
<li><p><code>HTMLButtonElement.type</code> with a value of <code>submit</code>.</p>
</li>
</ul>
<p>To interact with and manipulate these attributes using JavaScript, you can use methods like <code>getAttribute</code> and <code>setAttribute</code> to directly access the properties.</p>
<h3 id="heading-the-getattribute-method">The <code>getAttribute</code> Method</h3>
<p>Like the name suggests, you can use this method to get the value of an existing attribute on an element.</p>
<p>It accepts an argument (the name of the attribute) and returns the value of the attribute. If the attribute you passed to it as an argument does not exist on the element, the method will return <code>null</code>.</p>
<p>Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"image.jpg"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"An example image"</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> imageElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'img'</span>)
<span class="hljs-built_in">console</span>.log(imageElement.getAttribute(<span class="hljs-string">'src'</span>))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-09-at-9.00.25-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The</em> <code>getAttribute</code> method is used to get the value of the <code>src</code> attribute.</p>
<p>Using the <code>getAttribute</code> method is the above example, you can get the value of the <code>src</code> attribute for the image element.</p>
<h3 id="heading-the-setattribute-method">The <code>setAttribute</code> Method</h3>
<p>This is used to set or change the attribute of an element. The method takes in two arguments. The first argument is the name of attribute you want to change, and the second is the new value you want to give the attribute.</p>
<p>Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"image.jpg"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"An example image"</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> imageElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'img'</span>)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"BEFORE:"</span>, imageElement.getAttribute(<span class="hljs-string">'src'</span>))
imageElement.setAttribute(<span class="hljs-string">'src'</span>, <span class="hljs-string">'new-image.jpg'</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"AFTER:"</span>, imageElement.getAttribute(<span class="hljs-string">'src'</span>))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-09-at-9.27.14-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The</em> <code>setAttribute</code> method is used to update the value of the <code>src</code> attribute.</p>
<p>This code example logs the value of the <code>src</code> attribute before and after using <code>setAttribute</code> to change it from <code>image.jpg</code> to <code>new-image.jpg</code>.</p>
<p>When you pass an argument to the <code>setAttribute</code> method and that attribute doesn't exit on the element, it will create a new attribute. For example, you can add a height property to the image element like so:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> imageElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'img'</span>)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"BEFORE:"</span>, imageElement.getAttribute(<span class="hljs-string">'height'</span>))
imageElement.setAttribute(<span class="hljs-string">'height'</span>, <span class="hljs-string">'200'</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"AFTER:"</span>, imageElement.getAttribute(<span class="hljs-string">'height'</span>))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-09-at-9.32.53-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>An example of adding a new height attribute to the image element.</em></p>
<p>The first log statement returns <code>null</code> because the height attribute was non-existent. But after setting it with the <code>setAttribute</code> method, the second log statement returns the correct value of the height.</p>
<h3 id="heading-the-removeattribute-method">The <code>removeAttribute</code> Method</h3>
<p>In the previous section, you learned how to add a new attribute using the <code>setAttribute</code> method. What if you wanted to remove an existing attribute?</p>
<p>You can use the <code>removeAttribute</code> method. You pass in the name of the attribute you want to remove from the element as arguments to the method.</p>
<p>Here's an example:</p>
<pre><code class="lang-html">  <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"image.jpg"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"An example image"</span> <span class="hljs-attr">height</span>=<span class="hljs-string">"200"</span>&gt;</span>
</code></pre>
<p>Let's use the <code>removeAttribute</code> method to remove the <code>height</code> attribute from the image element.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> imageElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'img'</span>)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"BEFORE:"</span>, imageElement.getAttribute(<span class="hljs-string">'height'</span>))
imageElement.removeAttribute(<span class="hljs-string">'height'</span>, <span class="hljs-string">'200'</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"AFTER:"</span>, imageElement.getAttribute(<span class="hljs-string">'height'</span>))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-09-at-10.09.35-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>An example of using the</em> <code>removeAttribute</code> method.</p>
<p>Before using <code>removeAttribute</code>, the first log statement prints the value of the height attribute, <code>200</code>. But after using the <code>removeAttribute</code> method, the second log statement prints <code>null</code>, confirming the removal of the height attribute from the image element.</p>
<h3 id="heading-the-hasattribute-method">The <code>hasAttribute</code> Method</h3>
<p>Another method for working with attributes in the DOM is the <code>hasAttribute</code> method. You can use this method to check whether or not an element has a specific attribute.</p>
<p>The <code>hasAttribute</code> method returns <code>true</code> if the specified attribute exists and returns <code>false</code> if it doesn't.</p>
<p>Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"image.jpg"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"An example image"</span> <span class="hljs-attr">height</span>=<span class="hljs-string">"200"</span>&gt;</span>
</code></pre>
<p>Let's use the <code>hasAttribute</code> to check for the presence of <code>height</code> and <code>width</code> values on the image element.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> imageElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'img'</span>)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"HEIGHT"</span>, imageElement.hasAttribute(<span class="hljs-string">'height'</span>))
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"WIDTH"</span>, imageElement.hasAttribute(<span class="hljs-string">'width'</span>))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-09-at-10.20.53-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of using the</em> <code>hasAttribute</code> method to check if an attribute exists.</p>
<p>The check for height returns <code>true</code> because it's an existing attribute while the check for width returns <code>false</code> because it doesn't exist.</p>
<h2 id="heading-how-to-change-the-styles-on-dom-elements">How to Change the Styles on DOM Elements</h2>
<p>There are two main ways of styling elements when working with the DOM in JavaScript. You can use the <code>.style</code> property or you can use classes. Each has its benefits and situations it's best situated for.</p>
<h3 id="heading-setting-styles-with-the-style-property">Setting Styles With the <code>.style</code> Property</h3>
<p>You use the <code>.style</code> property when you want to make specific changes to a single element. The <code>.style</code> property allows you to set styles directly as <a target="_blank" href="https://www.freecodecamp.org/news/inline-style-in-html/">inline styles</a> for elements. This means it overrides the styles you have in your CSS stylesheet.</p>
<p>Using the <code>.style</code> property, you get access to all the individual CSS properties. See the demo below:</p>
<pre><code class="lang-html">  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Styling elements with JavaScript<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> header = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'h1'</span>)
<span class="hljs-built_in">console</span>.log(header.style)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/ezgif.com-video-to-gif--8-.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>CSSStyleDeclarations for an</em> <code>h1</code> element logged to the console.</p>
<p>The <code>console.log</code> prints the CSS style declarations with all the CSS properties for that element.</p>
<p>Now, let's see an example of how to use the <code>.style</code> property.</p>
<pre><code class="lang-html">  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>I love JavaScript<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-11-at-7.56.41-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>An example</em> <code>h1</code> header element</p>
<p>Here is an <code>h1</code> header. Now, let's add style to it using the <code>.style</code> property.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> paragraph = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'h1'</span>)

paragraph.style.color = <span class="hljs-string">'white'</span>
paragraph.style.backgroundColor = <span class="hljs-string">'green'</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-11-at-7.59.15-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The style property is used to add a background colour to the</em> <code>h1</code> element.</p>
<p>NOTE: Because this is JavaScript, you cannot use the hyphen if the CSS property name includes two or more words. For example, in CSS you would write <code>background-color</code>. But in your JavaScript code, you need to use camel case. So <code>background-color</code> becomes <code>backgroundColor</code>.</p>
<p>You can also delete a style on an element by setting the value of the property to an empty string.</p>
<pre><code class="lang-javascript">element.style.propertyName = <span class="hljs-string">""</span>
</code></pre>
<h3 id="heading-setting-styles-with-classes">Setting Styles with Classes</h3>
<p>With classes, you can create styles once and apply it to different elements. This helps make your code become more maintainable.</p>
<h4 id="heading-the-classname-property">The <code>className</code> Property</h4>
<p>The <code>className</code> property represent the class attribute of a DOM element. And you can use it to get or set the value of the class attribute.</p>
<p>Here's an example:</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">"food rice-dish"</span>&gt;</span>Jollof rice<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> jollofParagraph = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'p'</span>)

<span class="hljs-built_in">console</span>.log(jollofParagraph.className)

jollofParagraph.className = <span class="hljs-string">'favorite'</span>

<span class="hljs-built_in">console</span>.log(jollofParagraph.className)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-11-at-9.13.37-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of changing the value of a class with the</em> <code>className</code> property.</p>
<p>The <code>className</code> also reads or replace the current class. In the example above, the first log statement prints the original value of the class. And after updating the <code>className</code>, the second log statement prints the new value for class.</p>
<p>But there is a more flexible property. For example, what if instead of replacing the old class with the new class, you wanted to add another class? That's where the <code>classList</code> property comes in.</p>
<h4 id="heading-the-classlist-property">The <code>classList</code> Property</h4>
<p>With the <code>classList</code> property, you can add and remove classes. You can also toggle classes, replace existing class values with new ones, and even check if the class contains a specific value.</p>
<p>Here's an example:</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">"food"</span>&gt;</span>Jollof rice<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> jollofParagraph = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'p'</span>)
<span class="hljs-built_in">console</span>.log(jollofParagraph.classList)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-11-at-9.43.30-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Shows the current classList with only one value</em></p>
<h4 id="heading-adding-classes-with-classlistadd">Adding Classes with <code>classList.add()</code></h4>
<pre><code class="lang-javascript">jollofParagraph.classList.add(<span class="hljs-string">'fav'</span>, <span class="hljs-string">'tasty'</span>)

<span class="hljs-built_in">console</span>.log(jollofParagraph.classList)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-11-at-9.46.14-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of adding new classes with</em> <code>classList.add</code>.</p>
<p>The code adds two new classes <code>fav</code> and <code>tasty</code> to the class list.</p>
<h4 id="heading-removing-classes-with-classlistremove">Removing Classes With <code>classList.remove()</code></h4>
<pre><code class="lang-javascript">jollofParagraph.classList.remove(<span class="hljs-string">'tasty'</span>)

<span class="hljs-built_in">console</span>.log(jollofParagraph.classList)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-11-at-9.50.26-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of removing classes with</em> <code>classList.remove</code>.</p>
<p>The code removes the class <code>tasty</code> from the class list.</p>
<h4 id="heading-replacing-classes-with-classlistreplace">Replacing Classes with <code>classList.replace()</code></h4>
<pre><code class="lang-javascript">jollofParagraph.classList.replace(<span class="hljs-string">'fav'</span>, <span class="hljs-string">'favorite'</span>)

<span class="hljs-built_in">console</span>.log(jollofParagraph.classList)
</code></pre>
<p>The code replaces the class <code>fav</code> with <code>favorite</code></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-11-at-9.53.30-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of replacing classes with</em> <code>classList.replace</code>.</p>
<h4 id="heading-check-the-presence-of-a-class-with-classlistcontains">Check the Presence of a Class with <code>classList.contains()</code></h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isFavorite = jollofParagraph.classList.contains(<span class="hljs-string">'favorite'</span>)
<span class="hljs-keyword">const</span> isSoup = jollofParagraph.classList.contains(<span class="hljs-string">'soup'</span>)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Contains favorite: "</span>, isFavorite)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Contains soup: "</span>, isSoup)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-11-at-10.09.53-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example checking if a class exists with</em> <code>classList.contains</code>.</p>
<p>The code checks if the class passed to it is contained in the class list.</p>
<p>It returns <code>true</code> if it is included in the class list (for example <code>favorite</code>) and <code>false</code> if it is not included in the class list (for example <code>soup</code>)</p>
<h4 id="heading-toggling-a-class-with-the-classlisttoggle">Toggling a Class with the <code>classList.toggle()</code></h4>
<p>When you use the <code>toggle</code> property, it first checks if the class exists. If it exists, it will remove it. And if it doesn't exist, it will add it.</p>
<pre><code class="lang-javascript">jollofParagraph.classList.toggle(<span class="hljs-string">'favorite'</span>)
<span class="hljs-built_in">console</span>.log(jollofParagraph.classList)

jollofParagraph.classList.toggle(<span class="hljs-string">'favorite'</span>)
<span class="hljs-built_in">console</span>.log(jollofParagraph.classList)

jollofParagraph.classList.toggle(<span class="hljs-string">'favorite'</span>)
<span class="hljs-built_in">console</span>.log(jollofParagraph.classList)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-11-at-10.19.18-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of toggling a class value with</em> <code>classList.toggle</code>.</p>
<p>The first time the toggle runs, <code>favorite</code> exists in the class list. So, the toggle removes it.</p>
<p>The second time the toggle runs, <code>favorite</code> doesn't exist so the toggle adds <code>favorite</code> to the class list.</p>
<p>The next time the toggle runs, <code>favorite</code> now exists again. So it removes it from the class list.</p>
<p>The toggle keeps adding or removing the value from the class list depending on whether it's present or absent.</p>
<h2 id="heading-how-to-traverse-the-dom">How to Traverse the DOM</h2>
<p>To traverse the DOM means to move between the different elements/nodes within the HTML document. This may includes selecting or accessing parent, child, or sibling elements (or nodes). You do this to get information or manipulate the document structure.</p>
<p>But before we get into how to traverse the DOM, you need to understand the difference between nodes and elements.</p>
<h3 id="heading-difference-between-a-node-and-an-element">Difference Between a Node and an Element</h3>
<p>Nodes are the building blocks of the DOM. They represents different components in the HTML structure.</p>
<p>Elements are a specific type of node, but not all nodes are elements. Other types of content like attributes of elements, text content, and comments within the code are nodes too. But they are not elements.</p>
<p>An element is a specific type of node that defines the structure of the document's content. Think of elements as the familiar HTML tags you use. Examples include <code>&lt;div&gt;</code>, <code>&lt;p&gt;</code>, and <code>&lt;ul&gt;</code>. Each element can consist of attributes, text content, and other nested elements.</p>
<h3 id="heading-selecting-a-parent-with-parentnode-vs-parentelement">Selecting a Parent with <code>parentNode</code> vs <code>parentElement</code></h3>
<p>When it comes to selecting the parent of a DOM element, you can use either the <code>parentNode</code> or <code>parentElement</code>. Both will get the parent of the element you pass to it.</p>
<p>From a practical viewpoint, the parent of an element or a node will always be an element. So it doesn't matter which one you use, you will get the right parent of the selected element.</p>
<p>Let's see an example of selecting the parent of an element.</p>
<pre><code class="lang-html">  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"full-text"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"italics"</span>&gt;</span>Some italicized text<span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
    <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>
</code></pre>
<pre><code class="lang-json">const italicizedText = document.getElementById('italics')

console.log(italicizedText.parentNode)
console.log(italicizedText.parentNode.parentNode)
</code></pre>
<p>First, you select the element. Then, you chain the <code>parentNode</code> method to it to get the parent. You can also chain another <code>parentNode</code> property to get the parent of a parent element like the second log statement.</p>
<p>The screenshot below shows the output of the two log statements.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-12-at-9.44.45-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of selecting the parent of an element.</em></p>
<h3 id="heading-selecting-elements-with-childnodes-vs-children">Selecting Elements with <code>childNodes</code> vs <code>children</code></h3>
<p>You can select the contents of an element using both the <code>.childNodes</code> and <code>.children</code> properties. But they work differently.</p>
<p><code>childNodes</code>: returns a NodeList of all the child nodes within the selected elements. It will include elements and non-element nodes like text nodes, comment nodes, and so on.</p>
<p><code>.children</code>: returns an HTML collection of only the child elements (element nodes) of the selected objects. It will not include any non-element nodes like texts or comments.</p>
<p>Let's see an example that shows the difference:</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">"container"</span>&gt;</span>
    A text node
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Some paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- This is a comment --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Span Element<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>The code above has only 2 child elements (element nodes): the paragraph and the span. But there are other elements too – a text node and a comment:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> container = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'container'</span>);

<span class="hljs-keyword">const</span> containerChildNodes = container.childNodes;
<span class="hljs-keyword">const</span> containerChildren = container.children;

<span class="hljs-built_in">console</span>.log(containerChildNodes);
<span class="hljs-built_in">console</span>.log(containerChildren);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-12-at-10.29.23-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>An example of using the .childNodes property</em></p>
<p>The <code>childNodes</code> will return all the child nodes (both elements and non-elements). It also includes the whitespaces between elements as text nodes.</p>
<p>This can be confusing to work with. So, unless you have a good reason not to, you should stick with the <code>.children</code> property.</p>
<p>The <code>children</code> will only return the child elements (the paragraph and the span).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-12-at-10.34.08-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>An example of using the</em> <code>.children</code> property</p>
<h3 id="heading-selecting-the-first-or-last-childelement">Selecting the First or Last Child/Element</h3>
<p>If you need to select only the first/last child or element, you can use these four properties.</p>
<ul>
<li><p><code>firstChild</code>: Selects only the first child node of the parent element.</p>
</li>
<li><p><code>lastChild</code>: Selects only the last child node of the parent element.</p>
</li>
<li><p><code>firstElementChild</code>: Selects only the first child element of the parent.</p>
</li>
<li><p><code>lastElementChild</code>: Selects only the last child element of the parent.</p>
</li>
</ul>
<p>Let's use the same example from the previous section to see how each works:</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">"container"</span>&gt;</span>
    A text node
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Some paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- This is a comment --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Span Element<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> container = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'container'</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"FIRST CHILD:"</span>, container.firstChild)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"LAST CHILD:"</span>, container.lastChild)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"FIRST ELEMENT: "</span>, container.firstElementChild)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"LAST ELEMENT:"</span>, container.lastElementChild)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-13-at-7.43.25-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example demo selecting first child/element and last child/element</em></p>
<p>Note how <code>firstChild</code> returns the first text node but the <code>firstElementChild</code> returns the first paragraph instead. This means it ignored the text node which comes before the paragraph.</p>
<p>And also note how the <code>lastChild</code> returns a text node – even though from the markup, it looks like there's nothing after the span. That is because the <code>lastChild</code> property considers the linebreak/whitespace between the closing tag of the span and the closing tag of the div elements as a node.</p>
<p>That's why it's generally safer to stick to <code>firstElementChild</code> and <code>lastElementChild</code>.</p>
<h3 id="heading-selecting-a-sibling-of-nodes-in-the-dom">Selecting a Sibling of Nodes in the DOM</h3>
<p>You've learned how to select a parent or a child of an element. You can also select a sibling of an element. You do that using the following properties:</p>
<ul>
<li><p><code>nextSibling</code>: Selects the next node within the same parent element.</p>
</li>
<li><p><code>nextElementSibling</code>: Selects the next element, and ignores any non-element nodes.</p>
</li>
<li><p><code>previousSibling</code>: Selects the previous node within the same parent element.</p>
</li>
<li><p><code>previousElementSibling</code>: Selects the previous element, and ignores any non-element nodes.</p>
</li>
</ul>
<p>Here's an example:</p>
<pre><code class="lang-html">  <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">id</span>=<span class="hljs-string">"one"</span>&gt;</span>First paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    text node
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"two"</span>&gt;</span>Second paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    another text node
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"three"</span>&gt;</span>Third 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">"four"</span>&gt;</span>Fourth paragraph<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>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> paragraphTwo = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'two'</span>)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"nextSibling: "</span>, paragraphTwo.nextSibling)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"nextElementSibling: "</span>, paragraphTwo.nextElementSibling)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"previousSibling: "</span>, paragraphTwo.previousSibling)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"previousElementSibling: "</span>, paragraphTwo.previousElementSibling)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-13-at-7.57.18-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Examples of selecting siblings of a node.</em></p>
<p><code>nextSibling</code> and <code>previousSibling</code> select the text nodes because they consider all nodes within the parent. While <code>nextElementSibling</code> and <code>previousElementSibling</code> select only the paragraph elements because they ignore non-element nodes like text.</p>
<h2 id="heading-dom-events-and-event-listeners">DOM Events and Event Listeners</h2>
<p>DOM events are actions that take place in the browser. These events are what allows you to make websites interactive.</p>
<p>Some DOM events are user-initiated like clicking, moving the mouse, or typing on the keyboard. Others are browser-initiated like when a page finishes loading.</p>
<h3 id="heading-difference-between-event-listener-and-event-handler">Difference Between Event Listener and Event Handler</h3>
<p>An event listener is a method that lets you know when an event has taken place. It allows you to "listen" or keep an eye out for DOM events. That way, when an event happens, you can do something.</p>
<p>An event handler is a response to the event. It's a function that runs when an event occurs.</p>
<p>For example, you can attach an event listener to a button that lets you know when a user clicks that button. Then you can write an event handler (a function) that prints something on screen anytime a click event occurs.</p>
<p>In this case, the event listener is what informs your app when a click occurs and then trigger a response. And the response (the function that runs when the click occurs) is an example of an event handler.</p>
<h3 id="heading-three-ways-to-register-events-in-javascript">Three Ways to Register Events in JavaScript</h3>
<p>The following are three different ways you can listen to and respond to DOM events using JavaScript.</p>
<ul>
<li><strong>Using inline event handlers:</strong> This is when you add the event listener as an attribute to HTML elements. In the early days of JavaScript, this was the only way to use events. See the example below:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example of using an inline event handler</span>

&lt;button onclick=<span class="hljs-string">"alert('Hello')"</span>&gt;Click me!&lt;/button&gt;
</code></pre>
<ul>
<li><strong>Using on-event handlers:</strong> You use this when an element has only one event handler. When you add more than one event handler using this method, only the last event handler will run, as it will override others before it.</li>
</ul>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- An example of using an on-event handler --&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">button</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> myButton = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'button'</span>)

  myButton.onclick = <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">"Run first handler"</span>)
  }

  myButton.onclick = <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">"Run second handler"</span>)
  }
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-14-at-7.41.49-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Only the second event handler is executed.</em></p>
<p>As you can see from the result in the console, the browser runs the code for only the second event handler.</p>
<ul>
<li><strong>Using the</strong> <code>addEventListener</code> method: This method allows you to attach more than one event handlers to an element. And it will execute them in the order in which they were added.</li>
</ul>
<p>As a general rule, you should stick with the <code>addEventListener</code>, unless you have a compelling reason not to.</p>
<p>The <code>addEventListener</code> method takes two arguments. The first is the event you want to listen to, and the second is the event handler which is the function you want to run when the event occurs.</p>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- An example of using the addEventListener method --&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">button</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> myButton = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'button'</span>)

  myButton.addEventListener(<span class="hljs-string">'click'</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">"Run first handler"</span>)
  })

  myButton.addEventListener(<span class="hljs-string">'click'</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">"Run second handler"</span>)
  })
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-14-at-7.51.22-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The</em> <code>addEventListener</code> method executes both event handlers.</p>
<h3 id="heading-practice-challenge">Practice Challenge</h3>
<p>Here is a challenge for you before you move on. Try solving it on your own before you take a look at the solution.</p>
<p>Consider the HTML and CSS code below.</p>
<p>The challenge includes two elements. A <code>#gift-box</code> div and a <code>#click-btn</code> button. The gift box is hidden with the <code>.hide</code> class.</p>
<p>Your task is write JavaScript code that listens to a click event on the button, and display the hidden box when the user clicks the button.</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">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">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"gift-box"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"hide"</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">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"click-btn"</span>&gt;</span>Show the box<span class="hljs-tag">&lt;/<span class="hljs-name">button</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>
<pre><code class="lang-css"><span class="hljs-selector-class">.hide</span> {
  <span class="hljs-attribute">display</span>: none;
}

<span class="hljs-selector-id">#gift-box</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">5em</span>;
}
</code></pre>
<p>&lt;a href="https://stackblitz.com/edit/js-cywa91?file=index.html,style.css,index.js" target="_blank"</p>
<p><strong>Solve the challenge on StackBlitz</strong>  </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/ezgif.com-video-to-gif-converted.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Demo gif for the final solution of the challenge</em></p>
<h3 id="heading-solution-to-practice-challenge">Solution to Practice Challenge</h3>
<p>Congratulations if you were able to solve the challenge. If you were not, that's okay. The solution and explanation is provided below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> giftBoxElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'gift-box'</span>)
<span class="hljs-keyword">const</span> buttonElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'click-btn'</span>)

buttonElement.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  giftBoxElement.classList.remove(<span class="hljs-string">'hide'</span>)
})
</code></pre>
<p>To solve this challenge, first you need to select both the <code>#gift-box</code> and <code>#click-btn</code> element.</p>
<p>Then, you add an event listener to the button. As mentioned earlier, the <code>addEventListener</code> method takes in two arguments.</p>
<p>In this case, the first argument is the 'click' event, and the second argument is a function.</p>
<p>The goal is to display the box. The box has a class <code>hide</code> which sets <code>display</code> to <code>none</code> in the CSS. One way to display the box using JavaScript is to remove <code>hide</code> from the classList.</p>
<h3 id="heading-the-event-object">The Event Object</h3>
<p>This is a JavaScript object the browser passes as an argument to the event handler function anytime an event occurs. The object includes some useful properties and methods like the following:</p>
<ul>
<li><p><code>type</code>: the type of event that occurred (like click, mouseover, keydown, and so on)</p>
</li>
<li><p><code>target</code>: the element on which the event occurred</p>
</li>
<li><p><code>clientX</code> and <code>clientY</code>: the horizontal and vertical coordinates of the mouse pointer at the time the event occurred.</p>
</li>
<li><p><code>preventDefault()</code>: prevents default actions associated with the events like preventing a form submission on the submit event.</p>
</li>
<li><p><code>stopPropagation()</code>: prevents the event from propagating through the DOM. More on that later.</p>
</li>
</ul>
<p>You can see a full list of the properties and methods on <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Event">the MDN web docs</a>.</p>
<h3 id="heading-types-of-events">Types of Events</h3>
<p>There are many different kinds of DOM events the browsers lets you listen to. The following are few of the common ones.</p>
<p><strong>Mouse events:</strong></p>
<ul>
<li><p><code>click</code>: when the element is clicked.</p>
</li>
<li><p><code>dbclick</code>: when the element is double clicked.</p>
</li>
<li><p><code>mouseover</code>: when the mouse pointer enters the element.</p>
</li>
<li><p><code>mouseleave</code>: when the mouse pointer leaves the element.</p>
</li>
<li><p><code>mousedown</code>: when the mouse is pressed down over an element.</p>
</li>
<li><p><code>mouseup</code>: when the mouse is released over an element.</p>
</li>
</ul>
<p><strong>Keyboard events:</strong></p>
<ul>
<li><p><code>keydown</code>: when a key on the keyboard is pressed down.</p>
</li>
<li><p><code>keyup</code>: when a key on the keyboard is released.</p>
</li>
<li><p><code>keypress</code>: when a key is pressed and shows the actual key that was pressed. Note that this event is not fired for all keys, especially non-printable keys.</p>
</li>
</ul>
<p><strong>Form events:</strong></p>
<ul>
<li><p><code>submit</code>: when a form is submitted.</p>
</li>
<li><p><code>input</code>: when the value of an input field changes.</p>
</li>
<li><p><code>change</code>: when the value of a form element changes and loses focus.</p>
</li>
</ul>
<p><strong>Window events:</strong></p>
<ul>
<li><p><code>load</code>: when the browser finishes loading the page.</p>
</li>
<li><p><code>unload</code>: when the user leaves the page.</p>
</li>
<li><p><code>resize</code>: when the browser window is resized.</p>
</li>
<li><p><code>scroll</code>: when the user scrolls through the document.</p>
</li>
</ul>
<p>You can see <a target="_blank" href="https://www.w3schools.com/jsref/dom_obj_event.asp">a comprehensive list of DOM events here</a>.</p>
<h2 id="heading-event-flow-in-javascript">Event Flow in JavaScript</h2>
<p>When a JavaScript event occurs, the event is propagated or travels either from the target where the event occurred to the outermost element in the DOM or vice versa.</p>
<p>For example, let's say you click a button on a page. By clicking the button, you've also clicked its parent element and any element the button is inside within the DOM hierarchy.</p>
<h3 id="heading-event-bubbling">Event Bubbling</h3>
<p>This is when the event is first registered on the target (or specified element) on which the event happened, and then registered outwards to the parent and onwards to the outermost element.</p>
<p>Here's an example:</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>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Event bubbling DEMO<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">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"outer"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"inner"</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">'btn'</span>&gt;</span>Click Here<span class="hljs-tag">&lt;/<span class="hljs-name">button</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">div</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 example here contains a button <code>#btn</code>. With event bubbling, when an event occurs (say a click) on the button, the event goes through the following sequence.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Event bubbling in DOM Manipulation: from button to div#inner to div#outer to body to HTML to document.</em></p>
<p>The event starts to bubble up from the target element back to the outermost ancestor.</p>
<h3 id="heading-event-capturing">Event Capturing</h3>
<p>Event capturing is the opposite of event bubbling. The event starts from the outermost ancestor element and travels down the DOM tree to the target element.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/JavaScript--2-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Event capturing in DOM Manipulation</em></p>
<p>During the capturing phase, event listeners attached to elements are executed in the order of the hierarchy from the topmost ancestor to the target element.</p>
<p>In case you're wondering why this matters, let's see a practical example using the same HTML markup example from above:</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>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Event bubbling DEMO<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">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"outer"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"inner"</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">'btn'</span>&gt;</span>Click Here<span class="hljs-tag">&lt;/<span class="hljs-name">button</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">div</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>Let's add event listeners to the button, the <code>#inner</code> div, and the <code>#outer</code> div:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'btn'</span>)
<span class="hljs-keyword">const</span> innerDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'inner'</span>)
<span class="hljs-keyword">const</span> outerDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'outer'</span>)

button.addEventListener(<span class="hljs-string">'click'</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">'Click on button'</span>)
})

innerDiv.addEventListener(<span class="hljs-string">'click'</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">'Click on inner Div'</span>)
})

outerDiv.addEventListener(<span class="hljs-string">'click'</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">'Click on outer Div'</span>)
})
</code></pre>
<p>By default, browsers use the event bubbling approach. So there is no need to add any argument to the event listener. This is the order in which the event handlers will run in response to a click on the button:</p>
<ol>
<li><p><code>button</code></p>
</li>
<li><p><code>#innerDiv</code></p>
</li>
<li><p><code>#outerDiv</code></p>
</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-15-at-11.54.07-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Events are executed from the element to the outermost element in the bubbling phase.</em></p>
<p>To use the event capturing model, you need to pass a third argument <code>true</code> to the event listener.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'btn'</span>)
<span class="hljs-keyword">const</span> innerDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'inner'</span>)
<span class="hljs-keyword">const</span> outerDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'outer'</span>)

button.addEventListener(<span class="hljs-string">'click'</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">'Click on button'</span>)
}, <span class="hljs-literal">true</span>)

innerDiv.addEventListener(<span class="hljs-string">'click'</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">'Click on inner Div'</span>)
}, <span class="hljs-literal">true</span>)

outerDiv.addEventListener(<span class="hljs-string">'click'</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">'Click on outer Div'</span>)
}, <span class="hljs-literal">true</span>)
</code></pre>
<p>The order for executing the event handlers will now run in the opposite direction, like this:</p>
<ol>
<li><p><code>#outerDiv</code></p>
</li>
<li><p><code>#innerDiv</code></p>
</li>
<li><p><code>button</code></p>
</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-15-at-11.58.38-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Events are executed from the outermost element to the element in the capturing phase.</em></p>
<h3 id="heading-the-event-stoppropagation-method">The Event <code>stopPropagation()</code> Method</h3>
<p>You've learned about how the event bubbling registers an event on an element and continues registering the event all the way to the outermost ancestor element. You've also seen how event capturing does the opposite.</p>
<p>But what if you don't want the event to register on all the ancestors? That's where the <code>stopPropagation</code> method comes in. You can use this method to prevent the event from propagating through the whole DOM.</p>
<p>Let's use the <code>stopPropagation</code> method on the same example from before:</p>
<pre><code class="lang-javascript">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>{
  event.stopPropagation()
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Click on button'</span>)
})

innerDiv.addEventListener(<span class="hljs-string">'click'</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">'Click on inner Div'</span>)
})

outerDiv.addEventListener(<span class="hljs-string">'click'</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">'Click on outer Div'</span>)
})
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-15-at-2.48.37-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The</em> <code>stopPropagation</code> method allows the execution of only the first event listener.</p>
<p>Now, only the event handler on the button is fired. The ones on the <code>innerDiv</code> and <code>outerDiv</code> are not because of the <code>stopPropagation</code> method on the button.</p>
<p>Also, note that to get the event object, you need to pass it as an argument to the event handler function.</p>
<h2 id="heading-js-dom-manipulation-project-ideas">JS DOM Manipulation Project Ideas</h2>
<p>Building projects is an excellent way to improve your understanding of coding concepts. So roll up your sleeves and get ready to work!</p>
<p>Here are five JS DOM manipulation project ideas to help you practice and solidify your skills.</p>
<h3 id="heading-toggle-switch">Toggle Switch</h3>
<p>Design a toggle switch that changes its state (on/off) when clicked. Update the DOM (for example with a background color) that reflects the current state of the toggle switch.</p>
<h3 id="heading-random-color-picker">Random Color Picker</h3>
<p>Create a simple app where users can click a button to generate a random color. Include a shape on the screen that gets filled with the chosen color. Also display the color code on screen.</p>
<h3 id="heading-countdown-timer">Countdown Timer</h3>
<p>Build a timer that starts from a specified time. The app updates in real time and shows the remaining time on the screen.</p>
<h3 id="heading-word-counter">Word Counter</h3>
<p>Develop an app that provides an input field or text area for the user to type. Display the number of words in real time on the screen as the user types.</p>
<h3 id="heading-an-interactive-to-do-list">An Interactive To-Do List</h3>
<p>Create an app that allows users to add, delete, or edit tasks. You can have fun with this one and add as many advanced features as you want. For example, adding features like marking tasks as completed, filtering tasks, or sorting them.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If you've come this far, then you now have a good understanding of JavaScript DOM manipulation. With practice, you'll be confident enough to tackle advanced projects that require knowledge of these DOM manipulation concepts.</p>
<p>A good foundation of Vanilla JS DOM manipulation concepts will also come in handy when picking JavaScript libraries/frameworks like React, Angular, Vue, Svelte, and so on.</p>
<p>Thank you for reading, and happy coding! For more in-depth tutorials, feel free to <a target="_blank" href="https://www.youtube.com/@DevAfterHours">subscribe to my YouTube channel</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Template Literals in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Template literals are a feature in JavaScript that were introduced with ES6. They give you a more flexible and maintainable way of working with strings in JavaScript. By the end of this article, you will know how to use template literals. You will le... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/template-literals-in-javascript/</link>
                <guid isPermaLink="false">66d45de7d7a4e35e3843494d</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Fri, 05 Jan 2024 18:30:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/JavaScript-template-literal---freecodecamp.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Template literals are a feature in JavaScript that were introduced with ES6. They give you a more flexible and maintainable way of working with strings in JavaScript.</p>
<p>By the end of this article, you will know how to use template literals. You will learn the syntax, the benefits, and some use cases. And you will also learn about an even more powerful feature called tagged template literals.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#what-are-template-literals">What are Template Literals?</a></p>
</li>
<li><p><a class="post-section-overview" href="#template-literals-vs-regular-strings">Template Literals vs Regular Strings</a></p>
</li>
<li><p><a class="post-section-overview" href="#some-practical-use-cases-of-template-literals">Some Use Cases of Template Literals</a></p>
</li>
<li><p><a class="post-section-overview" href="#tagged-template-literals">Tagged Template Literals</a></p>
</li>
<li><p><a class="post-section-overview" href="#practical-example-of-tagged-template-literal">Examples of Tagged Template Literals</a></p>
</li>
<li><p><a class="post-section-overview" href="#conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-are-template-literals">What are Template Literals?</h2>
<p>Template literasl are a feature in JavaScript that let developers work with strings in a convenient way. You denote regular strings in JavaScript using double quotes <code>""</code> or single quotes <code>''</code>.</p>
<p>But with template literals, you denote strings using backticks ````. This lets you embed variables and expressions within your strings.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> website = <span class="hljs-string">'freeCodeCamp'</span>
<span class="hljs-keyword">const</span> message = <span class="hljs-string">`Welcome to <span class="hljs-subst">${website}</span>`</span>

<span class="hljs-built_in">console</span>.log(message)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-03-at-6.57.20-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Output of template literal example.</em></p>
<p>The value of the <code>message</code> variable is an example of a template literal. It includes backticks which are used to define the template literal. And it also includes the syntax <code>${}</code> which is used to embed variables within the string.</p>
<h2 id="heading-template-literals-vs-regular-strings">Template Literals vs Regular Strings</h2>
<p>Let's now take a look at how template literals differ from regular strings and also some of the benefits of using template literals.</p>
<h3 id="heading-string-concatenation">String Concatenation</h3>
<p>Before the introduction of template literals, you had to use the plus <code>+</code> symbol when you wanted to concatenate strings.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> userName = <span class="hljs-string">'Marie'</span>
<span class="hljs-keyword">const</span> balance = <span class="hljs-number">10</span>

<span class="hljs-comment">// Using regular string</span>
<span class="hljs-keyword">const</span> str1 = <span class="hljs-string">'Hi '</span> + userName + <span class="hljs-string">','</span> + <span class="hljs-string">' your balance is '</span> + balance + <span class="hljs-string">'.'</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Regular string: "</span>, str1)

<span class="hljs-comment">// Using template literal</span>
<span class="hljs-keyword">const</span> str2 = <span class="hljs-string">`Hi <span class="hljs-subst">${userName}</span>, your balance is <span class="hljs-subst">${balance}</span>.`</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Template literal: "</span>, str2)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-03-at-7.07.37-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The regular string and template literal produce the same output for the example.</em></p>
<p>Note how using regular strings involves adding many plus signs. And also accounting for whitespace at the right places. This can get difficult to deal with when working with lengthy strings.</p>
<p>With the template literal example, there was no need to add any plus signs. You write everything together as a single string. The variables are directly embedded using the <code>${}</code> syntax.</p>
<h3 id="heading-multi-line-strings">Multi-line Strings</h3>
<p>Another way template literals make it easier to work with strings is when dealing with multi line strings. For regular strings, you have to use a combination of the plus <code>+</code> sign and <code>\n</code> to denote a new line. But template literals don't require any of that.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> regularString = 
<span class="hljs-string">'Hello there! \n'</span> +
<span class="hljs-string">'Welcome to our website. \n'</span> +
<span class="hljs-string">'How can we help you today?'</span>

<span class="hljs-keyword">const</span> templateLiteral = 
<span class="hljs-string">`Hello there!
Welcome to our website.
How can we help you today?`</span>

<span class="hljs-built_in">console</span>.log(regularString)
<span class="hljs-built_in">console</span>.log(templateLiteral)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-03-at-7.44.20-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Multi line string examples for regular string and template literal.</em></p>
<p>Both the <code>regularString</code> and <code>templateLiteral</code> variables give the same output. The template string recognises whitespaces and linebreaks automatically.</p>
<h3 id="heading-readability-and-maintainability">Readability and Maintainability</h3>
<p>Template literals also make your code more readable and easier to maintain. As you've seen already, they doesn't require any concatenation with the plus <code>+</code> sign. And you also don't need to worry about escaping quotations marks.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> city = <span class="hljs-string">"Paris"</span>
<span class="hljs-keyword">const</span> str1 = <span class="hljs-string">'She said, "I love '</span> + city + <span class="hljs-string">', it\'s a beautiful place."'</span>
<span class="hljs-keyword">const</span> str2 = <span class="hljs-string">`She said, "I love <span class="hljs-subst">${city}</span>, it's a beautiful place`</span>

<span class="hljs-built_in">console</span>.log(regularString)
<span class="hljs-built_in">console</span>.log(templateLiteral)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-04-at-7.00.42-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Results of regular string and template literal examples</em></p>
<p>Unlike the template literal, the regular string requires the following;</p>
<ul>
<li><p>The use of the plus <code>+</code> for concatenation.</p>
</li>
<li><p>Careful use of single and double quotes.</p>
</li>
<li><p>The need to escape the single quote in string with <code>\</code>.</p>
</li>
</ul>
<h2 id="heading-some-practical-use-cases-of-template-literals">Some Practical Use Cases of Template Literals</h2>
<p>So far, you've learned what template literals are and how they compare with regular strings. Now, let's look at some practical examples.</p>
<h3 id="heading-generating-html-markup">Generating HTML Markup</h3>
<p>You will often see template literals used for generating HTML markup. They allow you to embed JavaScript expressions directly into HTML strings. This makes it easy to create content that's dynamic and data driven.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Marie"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>,
};

<span class="hljs-keyword">const</span> userProfile = <span class="hljs-string">`
&lt;div&gt;
  &lt;h2&gt;Name: <span class="hljs-subst">${user.name}</span>&lt;/h2&gt;
  &lt;p&gt;Age: <span class="hljs-subst">${user.age}</span>&lt;/p&gt;
&lt;/div&gt;
`</span>
</code></pre>
<p>Note how the <code>${}</code> syntax allows you to run JavaScript expressions directly within the string. In this case, it's used to read the values of the <code>user</code> object's properties.</p>
<h3 id="heading-creating-dynamic-sql-queries">Creating Dynamic SQL Queries</h3>
<p>You can also use template literals to create dynamic SQL queries by embedding variables or expressions directly into the query strings. This means you can easily create queries based on runtime values.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> tableName = <span class="hljs-string">"users"</span>;
<span class="hljs-keyword">const</span> columnName = <span class="hljs-string">"name"</span>;
<span class="hljs-keyword">const</span> searchValue = <span class="hljs-string">"John"</span>;

<span class="hljs-keyword">const</span> sqlQuery = 
  <span class="hljs-string">`SELECT * FROM <span class="hljs-subst">${tableName}</span> WHERE <span class="hljs-subst">${columnName}</span> = '<span class="hljs-subst">${searchValue}</span>'`</span>
</code></pre>
<h3 id="heading-localization-and-internalization">Localization and Internalization</h3>
<p>Another practical use of template literals is for handling localization and internationalization in your apps. It's easier to manage translations because with template literals, you can embed variables for localized content or language keys directly into strings.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Marie"</span>,
};

<span class="hljs-keyword">const</span> locale = <span class="hljs-string">"fr"</span>;
<span class="hljs-keyword">const</span> greetings = {
  <span class="hljs-attr">en</span>: <span class="hljs-string">"Hello"</span>,
  <span class="hljs-attr">es</span>: <span class="hljs-string">"Hola"</span>,
  <span class="hljs-attr">fr</span>: <span class="hljs-string">"Bonjour"</span>
};

<span class="hljs-keyword">const</span> localizedGreeting = <span class="hljs-string">`<span class="hljs-subst">${greetings[locale]}</span> <span class="hljs-subst">${user.name}</span>!`</span>;
<span class="hljs-built_in">console</span>.log(localizedGreeting)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-04-at-7.51.34-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of using template literals for localized content.</em></p>
<p>This example creates a <code>localizedGreeting</code> string without relying on any cumbersome concatenation.</p>
<h2 id="heading-tagged-template-literals">Tagged Template Literals</h2>
<p>This is a feature of the JavaScript template literal that you can use to perform advanced string manipulation.</p>
<p>To use this feature, you need a tag function and then a tagged template.</p>
<p>The tagFunction takes in a mix of strings and variables as arguments. It then formats them based on some condition or rules you set.</p>
<p>Then, you call (or run) the tag function by placing it before the opening backtick of the template literal.</p>
<h3 id="heading-syntax-for-tagged-template-literal">Syntax for Tagged Template Literal</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">taggedFunc</span>(<span class="hljs-params">strings, ...values</span>) </span>{
  <span class="hljs-built_in">console</span>.log(strings)
  <span class="hljs-built_in">console</span>.log(values)
}

<span class="hljs-keyword">const</span> name = <span class="hljs-string">'Sarah'</span>
<span class="hljs-keyword">const</span> city = <span class="hljs-string">'Rome'</span>

taggedFunc<span class="hljs-string">`Hello <span class="hljs-subst">${name}</span>. Welcome to <span class="hljs-subst">${city}</span>.`</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-04-at-10.03.12-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Log results for the string and value arguments of a tagged template literal</em></p>
<p>There are three things to take note of here.</p>
<p>First, the first parameter (<code>strings</code> in this example) is always an array of all the blocks of strings in the template literal. In this case, it is the array below.</p>
<pre><code class="lang-javascript">[<span class="hljs-string">'Hello '</span>, <span class="hljs-string">'. Welcome to '</span>, <span class="hljs-string">'.'</span>]
</code></pre>
<p>Next, the rest of the parameters will be all the variables and evaluated expressions within the template literals. The <a target="_blank" href="https://www.freecodecamp.org/news/javascript-rest-vs-spread-operators/">JavaScript rest parameter</a> syntax <code>...values</code> makes it simple to get all of them.</p>
<pre><code class="lang-javascript">[<span class="hljs-string">'Sarah'</span>, <span class="hljs-string">'Rome'</span>]
</code></pre>
<p>Finally, take note of how the <code>taggedFunc</code> is used. Unlike a regular function, you won't call it with a parenthesis. But by attaching it before the first backtick of the template literal.</p>
<pre><code class="lang-javascript">taggedFunc<span class="hljs-string">`Hello <span class="hljs-subst">${name}</span>. Welcome to <span class="hljs-subst">${city}</span>.`</span> ✅

taggedFunc(Hello ${name}. Welcome to ${city}.) ❌
</code></pre>
<h2 id="heading-practical-example-of-tagged-template-literal">Practical Example of Tagged Template Literal</h2>
<p>Now let's see some practical examples of using a tagged template literal to handle string manipulation.</p>
<h3 id="heading-example-1">Example 1</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">receiptTag</span>(<span class="hljs-params">strings, ...values</span>) </span>{  

  <span class="hljs-keyword">let</span> finalString = <span class="hljs-string">''</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; values.length; i++) {
    finalString += strings[i] + values[i]
  }

  <span class="hljs-comment">// Add the last string literal</span>
  finalString += strings[strings.length - <span class="hljs-number">1</span>] 

  <span class="hljs-keyword">return</span> finalString
}

<span class="hljs-keyword">const</span> item = <span class="hljs-string">'apple'</span>
<span class="hljs-keyword">const</span> price = <span class="hljs-number">2.5</span>
<span class="hljs-keyword">const</span> quantity = <span class="hljs-number">3</span>

<span class="hljs-keyword">const</span> message = receiptTag<span class="hljs-string">`
  You have <span class="hljs-subst">${quantity}</span> <span class="hljs-subst">${item}</span>s.
  Unit cost: $<span class="hljs-subst">${price}</span>. 
  Total cost: $<span class="hljs-subst">${quantity * price}</span>.
`</span>

<span class="hljs-built_in">console</span>.log(message)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-04-at-10.37.18-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of a string formatted with a tagged template literal.</em></p>
<p>In this example, the <code>recieptTag</code> function receives a template literal with four expressions:</p>
<ul>
<li><p><code>${quantity}</code></p>
</li>
<li><p><code>${item}</code></p>
</li>
<li><p><code>${price}</code></p>
</li>
<li><p><code>${quantity * price}</code></p>
</li>
</ul>
<p>The <code>values</code> array will contain the evaluated values of these expressions.</p>
<pre><code class="lang-javascript">[<span class="hljs-number">3</span>, <span class="hljs-string">'apple'</span>, <span class="hljs-number">2.5</span>, <span class="hljs-number">7.5</span>]
</code></pre>
<p>And you can process them accordingly in the tagged function.</p>
<p>The result, logged to the console is a <code>message</code> that includes information about the quantity, item, unit cost and total cost.</p>
<h3 id="heading-example-2">Example 2</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetUser</span>(<span class="hljs-params">strings, name</span>) </span>{
  <span class="hljs-keyword">const</span> now = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>()
  <span class="hljs-keyword">const</span> currentHour = now.getHours()

  <span class="hljs-keyword">const</span> timeOfDay = currentHour &lt; <span class="hljs-number">12</span> ? <span class="hljs-string">'morning'</span> : currentHour &lt; <span class="hljs-number">17</span> ? <span class="hljs-string">'afternoon'</span> : <span class="hljs-string">'evening'</span>

  <span class="hljs-keyword">return</span> <span class="hljs-string">`Good <span class="hljs-subst">${timeOfDay}</span> <span class="hljs-subst">${name}</span><span class="hljs-subst">${strings[<span class="hljs-number">1</span>]}</span>`</span>
}

<span class="hljs-keyword">const</span> userName = <span class="hljs-string">'Ama'</span>

<span class="hljs-built_in">console</span>.log(greetUser<span class="hljs-string">`Hello <span class="hljs-subst">${userName}</span>, nice to meet you!`</span>)
</code></pre>
<p>This example uses tagged template literal to determine how to greet the user based on what time of day it is.</p>
<p>The function first gets the current hour using the date object. Then uses a tenary operator to determin time of day. And returns a string with a <code>timeOfDay</code> variable indicating what time of day it is.</p>
<p>Also, pay attention to the first word of the log statement and compare it to the first word of the string passed to the tag to see how the function has changed the string.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Template literals provide a convenient way to work with strings in JavaScript. In this article, you've learned about the syntax, and how to use them in your projects.</p>
<p>You also learned about an advanced feature of template literals: tagged template literals. These are functions that take in an array of string blocks and expressions. They return a string based on the logic you write for the function.</p>
<p>Thanks for reading. And happy coding! For more in-depth tutorials, feel free to <a target="_blank" href="https://www.youtube.com/@DevAfterHours">subscribe to my YouTube channel</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ HTMLCollection vs NodeList – What's the Difference? ]]>
                </title>
                <description>
                    <![CDATA[ If you're a web developer or have worked with the DOM (Document Object Model), you may have come across the terms HTMLCollection and NodeList before. But what do they mean and when do you need to use them? By the end of this article, you will learn a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/dom-manipulation-htmlcollection-vs-nodelist/</link>
                <guid isPermaLink="false">66d45dd8182810487e0ce0fd</guid>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Thu, 07 Dec 2023 22:11:45 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/Benjamin-Semah---DevAfterHours.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you're a web developer or have worked with the DOM (Document Object Model), you may have come across the terms <code>HTMLCollection</code> and <code>NodeList</code> before. But what do they mean and when do you need to use them?</p>
<p>By the end of this article, you will learn all about <code>HTMLCollection</code> and <code>NodeList</code>.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-an-htmlcollection">What is an <code>HTMLCollection</code>?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-nodelist">What is a <code>NodeList</code></a>?</p>
</li>
<li><p><a class="post-section-overview" href="#heading-similarities-between-htmlcollection-and-nodelist">Similarities between <code>HTMLCollection</code> and <code>NodeList</code></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-differences-between-htmlcollection-and-nodelist">Differences between <code>HTMLCollection</code> and <code>NodeList</code></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-which-one-should-you-use">Which one should you use</a>?</p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<p>Let's get started!</p>
<h2 id="heading-what-is-an-htmlcollection">What is an <code>HTMLCollection</code>?</h2>
<p>An <code>HTMLCollection</code> is a list of DOM elements that match certain criteria. For example, they may have the same tag name or class. Or they may be related in a specific context, like children of a particular element.</p>
<p>Here's an example:</p>
<pre><code class="lang-html">  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>First button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>Second button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>Third button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>In this example, we have three button elements. Each has a class of <code>btn</code>. Now, let's select the buttons using the <code>getElementsByClassName</code> method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> buttonElements = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">'btn'</span>)
<span class="hljs-built_in">console</span>.log(buttonElements)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-04-at-8.10.41-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The <code>getElementsByClassName</code> methods returns an <code>HTMLCollection</code> of the three buttons with the <code>btn</code> class. It looks like an array but it's not. More on that later.</p>
<h2 id="heading-what-is-a-nodelist">What is a <code>NodeList</code>?</h2>
<p>Like the name suggests, a <code>NodeList</code> is a list of nodes. But what is a node? A node is any individual element in the DOM tree. This could be elements, attributes, texts, comments, and so on.</p>
<p>An example of a DOM method that will return a <code>nodeList</code> is <code>querySelectorAll</code>.</p>
<p>Example:</p>
<pre><code class="lang-html">  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>First button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>Second button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>Third button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>Using the same example, let's select the buttons with <code>querySelectorAll</code> instead.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> buttonElements = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'.btn'</span>)
<span class="hljs-built_in">console</span>.log(buttonElements)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-04-at-8.33.08-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This time, the <code>console.log</code> statement prints a <code>NodeList</code>. Again, this is also similar to an array but it isn't quite an array.</p>
<h2 id="heading-similarities-between-htmlcollection-and-nodelist">Similarities between <code>HTMLCollection</code> and <code>NodeList</code></h2>
<p>Now that you know what <code>HTMLCollection</code> and <code>NodeList</code> are, let's look at how they are alike. They both aren't arrays even though they look like one. But they have features that make them have some behaviours of arrays.</p>
<p>You can access the contents of both using zero-based indexing like you would with an array. And you can also use the length property to find the length of both an <code>HTMLCollection</code> and a <code>NodeList</code>.</p>
<p>Example:</p>
<pre><code class="lang-html">  <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">class</span>=<span class="hljs-string">"paragraph"</span>&gt;</span>First 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">class</span>=<span class="hljs-string">"paragraph"</span>&gt;</span>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">class</span>=<span class="hljs-string">"paragraph"</span>&gt;</span>Third paragraph<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>
</code></pre>
<p>This is a <code>div</code> with three paragraphs. Let's see examples of accessing the elements with zero-based indexing and also checking the length for both <code>HTMLCollection</code> and <code>NodeList</code>.</p>
<h3 id="heading-example-with-htmlcollection">Example with <code>HTMLCollection</code>:</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// getElementsByClassName will return an HTMLCollection</span>
<span class="hljs-keyword">const</span> paragraphs = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">"paragraph"</span>)
<span class="hljs-built_in">console</span>.log(paragraphs)

<span class="hljs-comment">// Use the index to get the first paragraph</span>
<span class="hljs-keyword">let</span> firstParagraph = paragraphs[<span class="hljs-number">0</span>] 
<span class="hljs-built_in">console</span>.log(firstParagraph)

<span class="hljs-comment">// Use the length property</span>
<span class="hljs-built_in">console</span>.log(paragraphs.length)
</code></pre>
<p>The screenshot below shows the results for the three <code>console.log</code> statements.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-04-at-9.38.09-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Even though the <code>HTMLCollection</code> is not an array, you can still use the index to access the items in the collection. And you can also get the length using the <code>length</code> property.</p>
<p>You will get the same result for a <code>NodeList</code>. To get a <code>NodeList</code>, let's use the <code>querySelectorAll</code> method instead.</p>
<h3 id="heading-example-with-nodelist">Example with <code>NodeList</code>:</h3>
<pre><code class="lang-javascript"><span class="hljs-comment">// querySelectorAll will return a Nodelist</span>
<span class="hljs-keyword">const</span> paragraphs = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">".paragraph"</span>)
<span class="hljs-built_in">console</span>.log(paragraphs)

<span class="hljs-comment">// Use the index to get the first paragraph</span>
<span class="hljs-keyword">let</span> firstParagraph = paragraphs[<span class="hljs-number">0</span>] 
<span class="hljs-built_in">console</span>.log(firstParagraph)

<span class="hljs-comment">// Use the length property</span>
<span class="hljs-built_in">console</span>.log(paragraphs.length)
</code></pre>
<p>Just like the <code>HTMLCollection</code>, the <code>NodeList</code> also uses zero-based indexing. And you can also use the length property on it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-04-at-9.55.22-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-differences-between-htmlcollection-and-nodelist">Differences between <code>HTMLCollection</code> and <code>NodeList</code></h2>
<p>You've seen how an <code>HTMLCollection</code> and a <code>NodeList</code> are alike. But there are also some differences you need to be aware of when working with these two types of collections in the DOM.</p>
<h3 id="heading-elements-nodes-only-vs-all-nodes">Elements nodes only vs all nodes</h3>
<p>Elements nodes are HTML elements like <code>&lt;p&gt;</code>, <code>&lt;div&gt;</code>, <code>&lt;img&gt;</code>, and others. But there are other types of nodes too. For example, text nodes and attribute nodes.</p>
<p>An <code>HTMLCollection</code> will include only element nodes whiles a <code>NodeList</code> includes other node types.</p>
<p>Example:</p>
<pre><code class="lang-javascript">&lt;div&gt;
  This is a text
  &lt;p <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"paragraph"</span>&gt;First paragraph&lt;/p&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"paragraph"</span>&gt;</span>First paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
&lt;/div&gt;
</code></pre>
<p>Here is a <code>div</code> with a text node and two element nodes (paragraphs). Each paragraph also has a text node.</p>
<p>Assuming you wanted to get only the element nodes in the <code>div</code>, you can use the <code>children</code> property on the <code>div</code>. And it will return an <code>HTMLCollection</code> containing only the element nodes.</p>
<p>But if you wanted all the nodes and not just the element nodes, then you can use the <code>childNodes</code> property to get all the nodes.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> divElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'div'</span>)

<span class="hljs-built_in">console</span>.log(divElement.children) <span class="hljs-comment">// returns an HTMLCollection</span>
<span class="hljs-built_in">console</span>.log(divElement.childNodes) <span class="hljs-comment">// returns a NodeList</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-04-at-10.59.18-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The <code>HTMLCollection</code> has two items: the paragraph element nodes. Whilst the <code>NodeList</code> includes the first text and the two paragraphs and their text contents too.</p>
<h3 id="heading-live-collections-vs-static-collections">Live Collections vs Static Collections</h3>
<p>The concepts of "live" and "static" refer to how an <code>HTMLCollection</code> and <code>NodeList</code> behave in response to changes in the document structure.</p>
<h4 id="heading-an-htmlcollection-is-always-live">An <code>HTMLCollection</code> is always live</h4>
<p>What does it mean to say an <code>HTMLCollection</code> is always live? It means when there is a change in the document, it will be automatically updated to reflect the change.</p>
<p>Example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Paragraph One<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Paragraph Two<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Paragraph Three<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// returns an HTMLCollection</span>
<span class="hljs-keyword">const</span> paragraphs = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'p'</span>)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"BEFORE UPDATE: "</span>, paragraphs)

<span class="hljs-keyword">const</span> newParagraph = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'p'</span>)
<span class="hljs-built_in">document</span>.body.appendChild(newParagraph)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"AFTER UPDATE: "</span>, paragraphs)
</code></pre>
<p>The code above creates an <code>HTMLCollection</code> called <code>paragraphs</code> using the <code>getElementsByTagName</code> method. And there are two <code>console.log</code> statements. One before a new paragraph is created and appended to the body, and another one after that.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-06-at-9.04.10-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Before the update, the <code>HTMLCollection</code> had three elements. But after the update, the collection now has four elements, reflecting the change in the document.</p>
<h4 id="heading-a-nodelist-is-sometimes-static">A <code>NodeList</code> is sometimes static</h4>
<p>A <code>NodeList</code> is not always live. It can be static or live depending on how it is generated. For example, a <code>NodeList</code> generated with the <code>querySelectorAll</code> method is static. A change in the document isn't reflected in the <code>NodeList</code>.</p>
<p>Example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Paragraph One<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Paragraph Two<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Paragraph Three<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// returns an HTMLCollection</span>
<span class="hljs-keyword">const</span> paragraphs = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'p'</span>)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"BEFORE UPDATE: "</span>, paragraphs)

<span class="hljs-keyword">const</span> newParagraph = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'p'</span>)
<span class="hljs-built_in">document</span>.body.appendChild(newParagraph)

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"AFTER UPDATE: "</span>, paragraphs)
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-06-at-9.09.42-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Because of the static nature of the <code>NodeList</code>, it remains the same even after an update in the document.</p>
<p>Note: in exceptional cases, like when a <code>NodeList</code> is generated with the <code>getElementsByName</code>, that <code>NodeList</code> will be live.</p>
<h3 id="heading-how-to-access-items-in-the-collection">How to Access Items in the Collection</h3>
<p>When accessing elements in an <code>HTMLCollection</code>, you can use any of the following.</p>
<ul>
<li><p>The index of element.</p>
</li>
<li><p>Their <code>id</code> attribute with the <code>namedItem</code> property.</p>
</li>
<li><p>Their <code>name</code> attribute with the <code>namedItem</code> property.</p>
</li>
</ul>
<p>But with a <code>NodeList</code>, you can only access the nodes in the list only by their index.</p>
<pre><code class="lang-javascript">&lt;div id=<span class="hljs-string">"container"</span>&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn1"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"first-name"</span>&gt;</span>First Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn2"</span>&gt;</span>Second Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn3"</span>&gt;</span>Third Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
&lt;/div&gt;
</code></pre>
<p>Here is a <code>div</code> container with three buttons. Note the first button has an id attribute and a name attribute.</p>
<h4 id="heading-example-with-htmlcollection-1">Example with <code>HTMLCollection</code>:</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> container = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#container'</span>)
<span class="hljs-keyword">const</span> buttons = container.children <span class="hljs-comment">// returns HTMLCollection</span>

<span class="hljs-built_in">console</span>.log(buttons[<span class="hljs-number">0</span>])<span class="hljs-comment">// using the index</span>
<span class="hljs-built_in">console</span>.log(buttons.namedItem(<span class="hljs-string">"btn1"</span>)) <span class="hljs-comment">// using the id attribute</span>
<span class="hljs-built_in">console</span>.log(buttons.namedItem(<span class="hljs-string">"first-name"</span>)) <span class="hljs-comment">// using the name attribute</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-04-at-11.57.33-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>All three <code>console.log</code>s successfully return the first button.</p>
<h4 id="heading-example-with-nodelist-1">Example with <code>NodeList</code>:</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> container = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#container'</span>)
<span class="hljs-keyword">const</span> buttons = container.childNodes <span class="hljs-comment">// returns a NodeList</span>

<span class="hljs-built_in">console</span>.log(buttons[<span class="hljs-number">1</span>])<span class="hljs-comment">// using the index</span>
<span class="hljs-built_in">console</span>.log(buttons.namedItem(<span class="hljs-string">"btn1"</span>)) <span class="hljs-comment">// throws an error</span>
<span class="hljs-built_in">console</span>.log(buttons.namedItem(<span class="hljs-string">"first-name"</span>)) <span class="hljs-comment">// throws an error</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-06-at-7.19.56-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Using the same example for a <code>NodeList</code>, the first <code>console.log</code> statement prints the button. But the other two raise a <code>TypeError</code>.</p>
<h3 id="heading-how-to-loop-through-the-collection">How to loop through the collection</h3>
<p>You cannot loop through an <code>HTMLCollection</code> with any of the array methods. Unless you first create an array from the collection.</p>
<p>But with a <code>NodeList</code>, you can use the <code>forEach</code> method to loop through it. But you cannot use other array methods like <code>map</code>, <code>filter</code>, and others without first creating an array from it.</p>
<p>Example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>First button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>Second button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>Third button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>The code below attempts to loop through an <code>HTMLCollection</code> with the <code>forEach</code> method and results in an <code>TypError</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// returns an HTMLCollection</span>
<span class="hljs-keyword">const</span> allButtons = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">'btn'</span>) 

allButtons.forEach(<span class="hljs-function"><span class="hljs-params">button</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(button))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-06-at-8.04.26-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Let's see another example but with a <code>NodeList</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// returns a NodeList</span>
<span class="hljs-keyword">const</span> allButtons = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'.btn'</span>) 

allButtons.forEach(<span class="hljs-function"><span class="hljs-params">button</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(button))
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-06-at-8.07.27-AM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the example above, the <code>forEach</code> method works successfully on the <code>NodeList</code>.</p>
<p>If for some reason, you still want to loop through an <code>HTMLCollection</code> without first creating an array from it, you can use the <code>for...of</code> statement. Let's use the same buttons example to show how you can do that.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// returns an HTMLCollection</span>
<span class="hljs-keyword">const</span> allButtons = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">'btn'</span>)

<span class="hljs-keyword">for</span> (button <span class="hljs-keyword">of</span> allButtons) {
  <span class="hljs-built_in">console</span>.log(button)
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/12/Screenshot-2023-12-06-at-8.07.27-AM-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-which-one-should-you-use">Which One Should You Use?</h2>
<p>The question of whether you should use an <code>HTMLCollection</code> or a <code>NodeList</code> depends on the use case or specific context.</p>
<p>If you want a live collection that automatically updates when there's a change in the document, then you should use an <code>HTMLCollection</code>. But if you prefer a static collection that doesn't update with a change in the document, then you should use a <code>NodeList</code>.</p>
<p>Most modern JavaScript frameworks and libraries provide higher-level abstractions, simplifying many DOM manipulation tasks. And you don't need to worry about them.</p>
<p>But having a solid understanding of native DOM collections like <code>HTMLCollection</code> and <code>NodeList</code> remains valuable, especially in scenarios where fine-grained control or compatibility with legacy code is essential.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article you learned about <code>HTMLCollection</code> and <code>NodeList</code>. You learned about what they are, their similarities and differences. The article also touched on when you should consider using either an <code>HTMLCollection</code> or a <code>NodeList</code>.</p>
<p>Thanks for reading. And happy coding. For more in-depth tutorials, feel free to <a target="_blank" href="https://www.youtube.com/@DevAfterHours">subscribe to my YouTube channel</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The CSS Flexbox Handbook – Complete Guide with Practical Examples ]]>
                </title>
                <description>
                    <![CDATA[ Flexbox is a useful tool for creating beautiful and responsive layouts for web pages. In this guide, you will learn everything you need to know to start using CSS Flexbox like a pro. We'll also go through loads of practice examples. This is a perfect... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-css-flexbox-handbook/</link>
                <guid isPermaLink="false">66d45de94a7504b7409c3359</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ flexbox ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ responsive design ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Wed, 18 Oct 2023 17:25:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/10/The-CSS-Flexbox-Handbook-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Flexbox is a useful tool for creating beautiful and responsive layouts for web pages. In this guide, you will learn everything you need to know to start using CSS Flexbox like a pro. We'll also go through loads of practice examples.</p>
<p>This is a perfect resource for you if you are a beginner web developer. It'll also be useful if you're an experienced developer who wants to brush up on your responsive web design skills.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-flexbox">What is Flexbox?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-the-benefits-of-using-flexbox">What are the benefits of using Flexbox?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-main-axis-and-the-cross-axis">The main axis and the cross axis</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-flex-containers-and-flex-items">Flex Containers and Flex Items</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-flex-and-inline-flex">Understanding <code>Flex</code> and <code>Inline-flex</code></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-display-flex">display: flex</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-display-inline-flex">display: inline-flex</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-flex-container-properties">The Flex Container Properties</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-flex-direction-property">The <code>flex-direction</code> Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-flex-wrap-property">The <code>flex-wrap</code> Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-flex-flow-shorthand-property">The <code>flex-flow</code> Shorthand Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-justify-content-property">The <code>justify-content</code> Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-align-items-property">The <code>align-items</code> Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-align-content-property">The <code>align-content</code> Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-place-content-property">The <code>place-content</code> Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#the-flex-items-properties">The Flex Items Properties</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-order-property">The <code>order</code> Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-align-self-property">The <code>align-self</code> Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-flex-grow-property">The <code>flex-grow</code> Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-flex-shrink-property">The <code>flex-shrink</code> Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-flex-basis-property">The <code>flex-basis</code> Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-flex-shorthand-property">The <code>flex</code> Shorthand Property</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-flexbox-gaps">Flexbox Gaps</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-center-an-element-with-flexbox">How to Center an Element With Flexbox</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-practice-with-flexbox-games">Practice with Flexbox Games</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-are-there-bugs-in-css-flexbox">Are There Bugs in CSS Fexbox?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-flexbox">What is Flexbox?</h2>
<p>Flexbox is short for "Flexible Box Layout". It's a CSS layout model that simplifies creating complex layouts. It provides a flexible way to align elements and distribute space within a container element.</p>
<p>The Flexbox layout model is bidirectional. This means you can either arrange your elements in rows, columns, or both. More on that later.</p>
<h3 id="heading-what-are-the-benefits-of-using-flexbox">What are the benefits of using Flexbox?</h3>
<p>Before Flexbox, it was hard to create complex layouts and responsive web pages. You needed a combination of CSS floats and position properties. This required many workarounds and hacks.</p>
<p>But with Flexbox, you can now do the following with less difficulty and fewer lines of code:</p>
<ul>
<li><p>Align and center elements using properties like <code>justify-content</code> and <code>align-items</code>.</p>
</li>
<li><p>Develop responsive layouts without writing lots of media queries.</p>
</li>
<li><p>Reorder elements without changing the HTML structure</p>
</li>
<li><p>Create same-height columns without any extra HTML elements or background images.</p>
</li>
</ul>
<p>Now you know what Flexbox is, along with some of the things you can do with it. Let's see how you can use it.</p>
<h3 id="heading-the-main-axis-and-the-cross-axis">The main axis and the cross-axis</h3>
<p>The first thing you need to understand about Flexbox is the concept of axes. Every flex container (an element with a <code>display</code> property set to <code>flex</code> or <code>inline-flex</code>) has a main axis and a cross axis.</p>
<p>The main axis is either horizontal or vertical depending on the value of the <code>flex-direction</code>. No worries if you are not familiar with <code>flex-direction</code>. You are about to learn it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/44.-main---cross-axis.png" alt="The main axis and the cross axis when the " width="600" height="400" loading="lazy"></p>
<p><em>The cross axis and main axis when the</em> <code>flex-direction</code> is <code>row</code></p>
<p>In this example, the main axis is horizontal and the cross axis is vertical.</p>
<p>The following is an example where the the main axis is vertical and the cross axis, is horizontal.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/45.-cross---main-axis.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The main axis and cross axis when the</em> <code>flex-direction</code> is <code>column</code></p>
<h2 id="heading-flex-containers-and-flex-items">Flex Containers and Flex Items</h2>
<p>To use all of Flexbox's properties, you need to set the <code>display</code> property for an element to <code>flex</code> or <code>inline-flex</code>.</p>
<p>This turns the element into a flex container, and the children of that element become flex items.</p>
<p>Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">section</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>  
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Flex Item 1<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>  
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Flex Item 2<span class="hljs-tag">&lt;/<span class="hljs-name">div</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>&gt;</span>This paragraph is not a flex item<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">section</span>&gt;</span>
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {  
  <span class="hljs-attribute">display</span>: flex;
}
</code></pre>
<p>The <code>.container</code> element is now a flex container. The three div elements are direct children of the <code>.container</code> element, which makes them flex items.</p>
<p>But the paragraph element inside the third div is not a flex item. This is because it's not a direct child of the <code>.container</code> element.</p>
<h2 id="heading-understanding-flex-and-inline-flex">Understanding <code>flex</code> and <code>inline-flex</code></h2>
<p>You can use both <code>flex</code> and <code>inline-flex</code> to make an element a flex container. The difference is in how they interact with surrounding elements.</p>
<h3 id="heading-display-flex"><code>display: flex</code></h3>
<p>This makes the flex container behave like a block-level element. The flex-container takes up the entire available width of its parent element. It starts on a new line, and the element that comes after it also starts on a new line.</p>
<p>Example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Button One<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

/* Flex Container */
<span class="hljs-tag">&lt;<span class="hljs-name">section</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>  
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"red"</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">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"gold"</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">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"green"</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">section</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Button Two<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">display</span>: flex;
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/46.-display-flex.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Flex containers behave like block elements when you use</em> <code>display: flex</code></p>
<p>The <code>.container</code> element takes up the entire available width of the body (its parent element).</p>
<h3 id="heading-display-inline-flex"><code>display: inline-flex</code></h3>
<p>This makes the flex-container behave like an inline-level element. This allows other inline elements (like buttons) to flow alongside it. Using the previous example, this is how the elements will be arranged when you change <code>display</code> from <code>flex</code> to <code>inline-flex</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/47.-display-inline-flex.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Flex containers behave like</em> <code>inline-elements</code> when you use <code>display: inline-flex</code></p>
<p>The flex container does not take up the entire width of its parent. It uses only as much horizontal space as necessary for its content.</p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ug2zkz?file=style.css"><strong>Practice using flex and inline-flex</strong></a> <strong>on StackBlitz</strong></p>
<h2 id="heading-the-flex-container-properties">The Flex Container Properties</h2>
<p>The flex container properties allow you to control the layout and alignment of the flex items within a flex container.</p>
<p><strong>NOTE:</strong> You apply these properties on the flex container, and not on its items.</p>
<p>The following are the flex container properties:</p>
<ul>
<li><p><code>flex-direction</code></p>
</li>
<li><p><code>flex-wrap</code></p>
</li>
<li><p><code>flex-flow</code></p>
</li>
<li><p><code>justify-content</code></p>
</li>
<li><p><code>align-items</code></p>
</li>
<li><p><code>align-content</code></p>
</li>
<li><p><code>place-content</code></p>
</li>
</ul>
<h3 id="heading-the-flex-direction-property">The <code>flex-direction</code> Property</h3>
<p>The <code>flex-direction</code> property defines the direction for displaying the flex items. It is what sets the flex container's main axis. This property can take any of these four values:</p>
<ul>
<li><p><code>row</code> (default value)</p>
</li>
<li><p><code>column</code></p>
</li>
<li><p><code>row-reverse</code></p>
</li>
<li><p><code>column-reverse</code></p>
</li>
</ul>
<p>Now, let's look at some examples to see how it all works.</p>
<p>In the following code snippet, we have a <code>names-container</code> with four names:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"names-container"</span>&gt;</span>  
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"jill"</span>&gt;</span>1. JILL<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">"john"</span>&gt;</span>2. JOHN<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">"jane"</span>&gt;</span>3. JANE<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">"jack"</span>&gt;</span>4. JACK<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>
</code></pre>
<p>Let's see the different ways you can arrange the names using the <code>flex-direction</code> property.</p>
<h4 id="heading-flex-direction-row"><code>flex-direction: row</code></h4>
<p>This displays the flex-items horizontally from left to right.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">flex-direction</span>: row;  
    <span class="hljs-comment">/* Other styles here... */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/1.-flex-direction-row.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>flex-direction: row</code></p>
<h4 id="heading-flex-direction-column"><code>flex-direction: column</code></h4>
<p>This displays the flex-items vertically from top to bottom.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/2.-flex-direction-column.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>flex-direction: column</code></p>
<h4 id="heading-flex-direction-row-reverse"><code>flex-direction: row-reverse</code></h4>
<p>This is the opposite of the row value. It displays the flex items from right to left.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/3.-flex-direction-row-reverse.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>flex-direction: row-reverse</code></p>
<h4 id="heading-flex-direction-column-reverse"><code>flex-direction: column-reverse</code></h4>
<p>This is the opposite of the column value. It displays the flex items from the bottom to the top.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/4.-flex-direction-column-reverse.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>flex-direction: column-reverse</code></p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-aaerav?file=style.css"><strong>Practice using flex-direction</strong></a> <strong>on StackBlitz</strong></p>
<h4 id="heading-a-note-on-the-reverse-values-and-accessibility">A note on the reverse values and accessibility:</h4>
<p>There's something you need to keep in mind when you use <code>row-reverse</code> and <code>column-reverse</code>. As you've already seen, both affect the visual order of elements on the screen.</p>
<p>But the order in your HTML remains unchanged. And that is the order that screen readers and keyboard navigation controls use.</p>
<p>In the example, when you use <code>row-reverse</code>, you see Jack's name first on the screen, followed by Jane, John, and Jill.</p>
<p>But for someone using a screen reader, they will hear the names as they appear in the HTML and not as they appear on screen. In this case, they will first hear Jill's name, followed by John, Jane, and Jack.</p>
<h3 id="heading-the-flex-wrap-property">The <code>flex-wrap</code> Property</h3>
<p>Sometimes, the space within the flex container will not be enough for the flex items.</p>
<p>In such cases, you use the <code>flex-wrap</code> property to choose whether to let the flex-items overflow or begin on a new line.</p>
<p>The <code>flex-wrap</code> property accepts any of the following values:</p>
<ul>
<li><p><code>nowrap</code> (default value)</p>
</li>
<li><p><code>wrap</code></p>
</li>
<li><p><code>wrap-reverse</code></p>
</li>
</ul>
<p>To see <code>flex-wrap</code> in action, let's add four more names to our <code>names-container</code>:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"names-container"</span>&gt;</span>  
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"jill"</span>&gt;</span>1. JILL<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">"john"</span>&gt;</span>2. JOHN<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">"jane"</span>&gt;</span>3. JANE<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">"jack"</span>&gt;</span>4. JACK<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">"sara"</span>&gt;</span>5. SARA<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">"seth"</span>&gt;</span>6. SETH<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">"seal"</span>&gt;</span>7. SEAL<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>
</code></pre>
<h4 id="heading-flex-wrap-nowrap"><code>flex-wrap: nowrap</code></h4>
<p>This keeps all the flex items on a single line either in a row or column. It allows the flex items to overflow if there's not enough room in the flex container. See the example below:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">flex-direction</span>: row;  
    <span class="hljs-attribute">flex-wrap</span>: nowrap;  
    <span class="hljs-comment">/* Other styles here... */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/5.-flex-wrap-nowrap.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Flex items overflows because</em> <code>flex-wrap</code> is set to <code>nowrap</code></p>
<p>In this example, three names overflow out of the container because there is not enough space for them.</p>
<h4 id="heading-flex-wrap-wrap"><code>flex-wrap: wrap</code></h4>
<p>This will wrap or push the flex items to the next line if there's not enough room for them.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/6.-flex-wrap-wrap.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Flex items wrap or moves to the next line when</em> <code>flex-wrap</code> is set to <code>wrap</code></p>
<h4 id="heading-flex-wrap-wrap-reverse"><code>flex-wrap: wrap-reverse</code></h4>
<p>This is the opposite of <code>wrap</code>. It moves the overflow items to the next line but in a reverse direction.</p>
<p>For example, using <code>wrap-reverse</code> on the names container moves overflow items to the next top line instead of the next line below.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/7.-flex-wrap-wrap-reverse.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>flex-wrap: wrap-reverse</code></p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-cbmfgr?file=style.css"><strong>Practice using flex-wrap</strong></a> <strong>on StackBlitz.</strong></p>
<h3 id="heading-the-flex-flow-shorthand-property">The <code>flex-flow</code> Shorthand Property</h3>
<p>The <code>flex-flow</code> property is a shorthand for the <code>flex-direction</code> and <code>flex-wrap</code> properties. This means that when you use <code>flex-flow</code>, you can apply both properties with only a single line of code.</p>
<p>See the example below using the names container. You can give the container <code>flex-direction</code> and <code>flex-wrap</code> properties.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">flex-direction</span>: column;  
    <span class="hljs-attribute">flex-wrap</span>: wrap;
}
</code></pre>
<p>Or you can use the <code>flex-flow</code> shorthand to get the same result.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">flex-flow</span>: column wrap;
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/8.-flex-flow.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>flex-flow: column wrap</code></p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-xuv4bx?file=style.css"><strong>Practice using flex-flow</strong></a> <strong>on StackBlitz.</strong></p>
<h3 id="heading-the-justify-content-property">The <code>justify-content</code> Property</h3>
<p>This <code>justify-content</code> property handles the alignment of flex items on the main axis of the flex container.</p>
<p>You can use it to take care of how space is distributed on the main axis. This property takes any of the following values:</p>
<ul>
<li><p><code>flex-start</code> (default value)</p>
</li>
<li><p><code>flex-end</code></p>
</li>
<li><p><code>center</code></p>
</li>
<li><p><code>space-between</code></p>
</li>
<li><p><code>space-around</code></p>
</li>
<li><p><code>space-evenly</code></p>
</li>
</ul>
<h4 id="heading-justify-content-flex-start"><code>justify-content: flex-start</code></h4>
<p>This places the items at the start of the flex-direction. If the main axis is horizontal with a <code>flex-direction</code> of <code>row</code> (like the example below), it aligns the items to the left. And if it's vertical (with a <code>flex-direction</code> of <code>column</code>), it aligns the items to the top.</p>
<p>Using the names container example, this is how <code>justify-content: flex-start</code> would look like:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">justify-content</span>: flex-start;  
    <span class="hljs-comment">/* Other styles here... */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/9.-justify-content-flex-start.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>justify-content: flex-start</code></p>
<h4 id="heading-justify-content-flex-end"><code>justify-content: flex-end</code></h4>
<p>This will place the flex items at the end of the flex-direction of the main axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/10.-justify-content-flex-end.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>justify-content: flex-end</code></p>
<h4 id="heading-justify-content-center"><code>justify-content: center</code></h4>
<p>This places the flex items at the center of the flex container's main axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/11.-justify-content-center-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>justify-content: center</code></p>
<h4 id="heading-justify-content-space-between"><code>justify-content: space-between</code></h4>
<p>This will place the first flex item at the start of the main axis. And also place the last item at the end of the main axis. Then space on the main axis is distributed equally among the the elements.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/12.-justify-content-space-between.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>justify-content: space-between</code></p>
<h4 id="heading-justify-content-space-evenly"><code>justify-content: space-evenly</code></h4>
<p>This distributes space equally among the flex items. This means the space before and after each item is the same.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/13.-justify-content-space-evenly.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>justify-content: space-evenly</code></p>
<h4 id="heading-justify-content-space-around"><code>justify-content: space-around</code></h4>
<p>This also distributes space equally between the flex items. The key difference here is that the space before the first item and after the last item is half the space between the flex items.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/14.-justify-content-space-around.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>justify-content: space-around</code></p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-zpcbxv?file=style.css"><strong>Practice using justify-content</strong></a> <strong>on StackBlitz.</strong></p>
<h3 id="heading-the-align-items-property">The <code>align-items</code> Property</h3>
<p>The <code>align-items</code> property handles the alignment of flex items on the cross-axis of the flex container. It can take any of the following values:</p>
<ul>
<li><p><code>stretch</code> (default value)</p>
</li>
<li><p><code>flex-start</code></p>
</li>
<li><p><code>flex-end</code></p>
</li>
<li><p><code>center</code></p>
</li>
<li><p><code>baseline</code></p>
</li>
</ul>
<h4 id="heading-align-items-stretch"><code>align-items: stretch</code></h4>
<p>This stretches the flex items to fill up the space within the flex-container.</p>
<p>See the example below using a new names container with name cards of different sizes:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">align-items</span>: stretch;  
    <span class="hljs-comment">/* Other styles here... */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/15.-align-items-stretch.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>align-items: stretch</code></p>
<h4 id="heading-align-items-flex-start"><code>align-items: flex-start</code></h4>
<p>This will place the flex items at the start of the cross-axis of the flex container. If the cross-axis is vertical like in the example below, <code>align-items: flex-start</code> will place the items at the top.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">align-items</span>: flex-start;  
    <span class="hljs-comment">/* Other styles here... */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/16.-align-items-flex-start.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>align-items: flex-start</code></p>
<h4 id="heading-align-items-flex-end"><code>align-items: flex-end</code></h4>
<p>This will place the flex items at the end of the cross-axis of the flex container. If the cross-axis is vertical like in the example below, <code>align-items: flex-end</code> will place the items at the bottom.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">align-items</span>: flex-end;  
    <span class="hljs-comment">/* Other styles here... */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/17.-align-items-flex-end.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>align-items: flex-end</code></p>
<h4 id="heading-align-items-center"><code>align-items: center</code></h4>
<p>This aligns flex items at the center of the cross-axis of the flex container.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">align-items</span>: center;  
    <span class="hljs-comment">/* Other styles here... */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/18.-align-items-center.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>align-items: center</code></p>
<h4 id="heading-align-items-baseline"><code>align-items: baseline</code></h4>
<p>When you use the <code>baseline</code> value, flex items are arranged such that their baselines are aligned. See the example below:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">align-items</span>: baseline;  
    <span class="hljs-comment">/* Other styles here... */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/Untitled-design-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The baseline is indicated with the dotted white line</em></p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-jydywf?file=style.css"><strong>Practice using align-items</strong></a> <strong>on StackBlitz.</strong></p>
<h3 id="heading-the-align-content-property">The <code>align-content</code> Property</h3>
<p>When you have a flex container with wrap (or more than one flex line), you may need to align the lines to distribute the space as you want. That is when you use <code>align-content</code>. This property can take any of the following values:</p>
<ul>
<li><p><code>stretch</code> (default value)</p>
</li>
<li><p><code>flex-start</code></p>
</li>
<li><p><code>flex-end</code></p>
</li>
<li><p><code>center</code></p>
</li>
<li><p><code>space-between</code></p>
</li>
<li><p><code>space-evenly</code></p>
</li>
<li><p><code>space-around</code></p>
</li>
</ul>
<p>In the example below, there are 11 names in the names container. And the names container element has a <code>flex-wrap</code> value of <code>wrap</code>. This means you can apply the <code>align-content</code> property to change the alignment of the flex lines.</p>
<h4 id="heading-align-content-stretch"><code>align-content: stretch</code></h4>
<p>This stretches the flex lines to fill up the space within the flex container's cross-axis.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">flex-wrap</span>: wrap;  
    <span class="hljs-attribute">align-items</span>: stretch;  
    <span class="hljs-comment">/* Other styles here... */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/20.-align-content-stretch.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>align-content: stretch</code></p>
<h4 id="heading-align-content-flex-start"><code>align-content: flex-start</code></h4>
<p>This places the flex lines at the start of the container's cross-axis. For example, if the cross axis is vertical like that of the names container, it will place the flex lines at the top.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/21.-align-content-flex-start.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>align-content: flex-start</code></p>
<h4 id="heading-align-content-flex-end"><code>align-content: flex-end</code></h4>
<p>This places the flex lines at the end of the container's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/22.-align-content-flex-end.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>align-content: flex-end</code></p>
<h4 id="heading-align-content-center"><code>align-content: center</code></h4>
<p>This places the flex lines at the center of the container's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/23.-align-content-center.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>align-content: center</code></p>
<h4 id="heading-align-content-space-between"><code>align-content: space-between</code></h4>
<p>This will place the first flex line at the start of the cross-axis. It also places the last flex line at the end of the cross axis. Then space on the cross-axis is distributed equally between the the lines.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/24.-align-content-space-between.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>align-content: space-between</code></p>
<h4 id="heading-align-content-space-evenly"><code>align-content: space-evenly</code></h4>
<p>This distributes space equally between the flex lines. This means the space before and after each line is the same.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/25.-align-content-space-evenly.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>align-content: space-evenly</code></p>
<h4 id="heading-align-content-space-around"><code>align-content: space-around</code></h4>
<p>This also distributes space equally between the flex lines. The key difference here is the space before the first line and after the last line is half the space between the flex lines.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/26.-align-content-space-around.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>align-content: space-around</code></p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-fukvgd?file=style.css"><strong>Practice using align-content</strong></a> <strong>on StackBlitz.</strong></p>
<h3 id="heading-the-place-content-property">The <code>place-content</code> Property</h3>
<p>If you need to use both the <code>justify-content</code> and <code>align-content</code> properties, you use the <code>place-content</code> shorthand property.</p>
<p>It can take one or two values. When you give it a single value, the browser will apply the same value for both <code>justify-content</code> and <code>align-content</code>.</p>
<p>And when you give 2 values for <code>place-content</code>, the first value will be for <code>align-content</code> and the second for <code>justify-content</code>.</p>
<p>Let's look at an example:</p>
<p>Instead of writing this:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">flex-wrap</span>: wrap;  
    <span class="hljs-attribute">align-content</span>: flex-end;  
    <span class="hljs-attribute">justify-content</span>: flex-start;  
    <span class="hljs-comment">/* Other content */</span>
}
</code></pre>
<p>You can instead write the following and it will have the same effect:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">flex-wrap</span>: wrap;  
    <span class="hljs-attribute">place-content</span>: flex-end flex-start;  
    <span class="hljs-comment">/* Other content */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/43.-place-content.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of using the</em> <code>place-content</code> shorthand</p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ytdywl?file=style.css"><strong>Practice using place-content</strong></a> <strong>on StackBlitz.</strong></p>
<h2 id="heading-the-flex-item-properties">The Flex Item Properties</h2>
<p>Every direct child of a flex container is a flex item. So far, you've learned the properties of the flex containers.</p>
<p>Flexbox also has properties that you can apply to individual flex items. They include the following:</p>
<ul>
<li><p><code>order</code></p>
</li>
<li><p><code>align-self</code></p>
</li>
<li><p><code>flex-grow</code></p>
</li>
<li><p><code>flex-shrink</code></p>
</li>
<li><p><code>flex-basis</code></p>
</li>
<li><p><code>flex</code></p>
</li>
</ul>
<h3 id="heading-the-order-property">The <code>order</code> property</h3>
<p>The <code>order</code> property determines the order of appearance for the flex items.</p>
<p>The value you give to this property must be a number. A flex item with a lower number will appear before one with a higher number.</p>
<p>In the HTML code, the order for the four names is as follows:</p>
<ol>
<li><p>Jill</p>
</li>
<li><p>John</p>
</li>
<li><p>Jane</p>
</li>
<li><p>Jack</p>
</li>
</ol>
<pre><code class="lang-css">&lt;<span class="hljs-selector-tag">div</span> <span class="hljs-selector-tag">class</span>="<span class="hljs-selector-tag">names-container</span>"&gt;
    &lt;<span class="hljs-selector-tag">p</span> <span class="hljs-selector-tag">id</span>="<span class="hljs-selector-tag">jill</span>"&gt;1. <span class="hljs-selector-tag">JILL</span>&lt;/<span class="hljs-selector-tag">p</span>&gt;
    &lt;<span class="hljs-selector-tag">p</span> <span class="hljs-selector-tag">id</span>="<span class="hljs-selector-tag">john</span>"&gt;2. <span class="hljs-selector-tag">JOHN</span>&lt;/<span class="hljs-selector-tag">p</span>&gt;
    &lt;<span class="hljs-selector-tag">p</span> <span class="hljs-selector-tag">id</span>="<span class="hljs-selector-tag">jane</span>"&gt;3. <span class="hljs-selector-tag">JANE</span>&lt;/<span class="hljs-selector-tag">p</span>&gt;
    &lt;<span class="hljs-selector-tag">p</span> <span class="hljs-selector-tag">id</span>="<span class="hljs-selector-tag">jack</span>"&gt;4. <span class="hljs-selector-tag">JACK</span>&lt;/<span class="hljs-selector-tag">p</span>&gt;
&lt;/<span class="hljs-selector-tag">div</span>&gt;
</code></pre>
<p>You can change the order of appearance on the screen using the <code>order</code> property. See the example below.</p>
<p>Here's how they appear with no <code>order</code> properties:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/27.-no-order-property.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Name cards before add the</em> <code>order</code> property</p>
<p>Now, see how they appear when you add the following order properties:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;
}

<span class="hljs-selector-id">#jill</span> {  
    <span class="hljs-attribute">order</span>: <span class="hljs-number">2</span>;  
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fe4f46</span>;
}

<span class="hljs-selector-id">#john</span> {  
    <span class="hljs-attribute">order</span>: <span class="hljs-number">4</span>;  
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fcd65c</span>;
}

<span class="hljs-selector-id">#jane</span> {  
    <span class="hljs-attribute">order</span>: <span class="hljs-number">1</span>;  
    <span class="hljs-attribute">background-color</span>: 
    <span class="hljs-number">#00bab4</span>;
}

<span class="hljs-selector-id">#jack</span> {  
    <span class="hljs-attribute">order</span>: <span class="hljs-number">3</span>;  
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#003f54</span>;
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/28.-with-order-property.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The</em> <code>order</code> property changes the order of appearance</p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-c5mf8q?file=style.css"><strong>Practice using the order property</strong></a> <strong>on StackBlitz.</strong></p>
<p><strong>Word of caution:</strong> Even though the order of appearance changes on screen, the order in the HTML remains unchanged. And it's the order in the HTML that screen readers use. Where possible, it's best practice to change the order in the HTML rather than doing it with Flexbox.</p>
<h3 id="heading-the-align-self-property">The <code>align-self</code> property</h3>
<p>You can use the <code>align-self</code> property to give a flex item a different alignment from the other items.</p>
<p>It works the same way as the <code>align-items</code> property. The difference is that whereas <code>align-items</code> applies to all flex items, the <code>align-self</code> property is applied to only specific items.</p>
<p>Example:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">align-items</span>: center;  
    <span class="hljs-comment">/* Other styles */</span>    
}

<span class="hljs-selector-id">#jill</span> {
    <span class="hljs-attribute">align-self</span>: flex-start;
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/37.-align-self.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>align-self</code> with a <code>flex-start</code> value</p>
<p>In the example, the <code>align-items</code> property for the names container has a value of <code>center</code>. This aligns all the names at the center.</p>
<p>But using the <code>align-self</code> property, you are able to align Jill's name card to the top with a value of <code>flex-start</code>.</p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-e9ctpu?file=style.css"><strong>Practice using the align-self property</strong></a> <strong>on StackBlitz.</strong></p>
<h3 id="heading-the-flex-grow-property">The <code>flex-grow</code> property</h3>
<p>When you set a container's display to <code>flex</code>, often there will be some extra space after the items are arranged. See the example below:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">justify-content</span>: 
    flex-start;  
     <span class="hljs-comment">/* Other styles */</span>
 }
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/29.-flex-grow-extra-space.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The flex container has more than enough space for the flex items</em></p>
<p>The browser treats the extra as a value of <code>1</code>. This means when you give a <code>flex-grow</code> value of <code>0.5</code> to only one of the flex items, the browser will add half of the remaining space to the item's size.</p>
<pre><code class="lang-css"><span class="hljs-selector-id">#jill</span> {
    <span class="hljs-attribute">flex-grow</span>: <span class="hljs-number">0.5</span>;
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/30.-flex-grow-0.5.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The</em> <code>flex-grow</code> property makes the Jill's larger than its initial size</p>
<p>And if you add a <code>flex-grow</code> value of <code>1</code> to <strong>only one of the flex items</strong>, the browser will add all the extra space to that item.</p>
<p><strong>NOTE:</strong> If only one item in the container has a <code>flex-grow</code> value, then any value of 1 or more will make it take up all the extra space.</p>
<p>For example, the two code snippets below will have the same effect on Jill's card:</p>
<pre><code class="lang-css"><span class="hljs-selector-id">#jill</span> {  
    <span class="hljs-attribute">flex-grow</span>: <span class="hljs-number">1</span>;
}
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-id">#jill</span> {  
    <span class="hljs-attribute">flex-grow</span>: <span class="hljs-number">99</span>;
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/31.-flex-grow-1-or-more.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>When only one card has a</em> <code>flex-grow</code> of <code>1</code> or more</p>
<p>What happens when you add <code>flex-grow</code> values to more than one element?</p>
<p>The browser will share the extra space proportionately for them.</p>
<p>For example, when you give Jane a <code>flex-grow</code> of <code>3</code> and Jack a <code>flex-grow</code> of <code>1</code>, the browser will share the extra space with a <code>3:1</code> ratio.</p>
<p>This means the total value of the extra space becomes <code>4</code> (3+1). <code>Jane</code> will then get <code>3/4</code> of the extra space. And <code>Jack</code> will get <code>1/4</code> of it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/32.-flex-grow-jane-jack.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The extra space is shared proportionately betwee</em> <code>Jane</code> and <code>Jack</code></p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-m6h8af?file=style.css"><strong>Practice using the flex-grow property</strong></a> <strong>on StackBlitz.</strong></p>
<h3 id="heading-the-flex-shrink-property">The <code>flex-shrink</code> property</h3>
<p>The <code>flex-shrink</code> property is the opposite of <code>flex-grow</code>.</p>
<p>You use <code>flex-grow</code> when you want to increase the flex item's size if there's extra space. But, you use <code>flex-shrink</code> when you want to decrease the flex-item's size if there's not enough space in the flex container.</p>
<p>See the example below:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"numbers-container"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"one"</span>&gt;</span>1<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">"two"</span>&gt;</span>2<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">"three"</span>&gt;</span>3<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">"four"</span>&gt;</span>4<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>
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-class">.numbers-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">justify-content</span>: flex-start;  
    <span class="hljs-comment">/* Other styles */</span>
}

<span class="hljs-selector-id">#one</span> {  
    <span class="hljs-attribute">flex-shrink</span>: <span class="hljs-number">2</span>;  
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fe4f46</span>;
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/33.-flex-shrink-value-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The first card shrinks to make room for the others</em></p>
<p>In the example, each of the four numbers has a width of 150px (that's a total of 600px). But the <code>numbers-container</code> has a width of 400px which is not enough.</p>
<p>The cards have to shrink to fit in the available space. But Number <code>1</code> which with a <code>flex-shrink</code> value of 2 shrinks to become twice as small as the other numbers.</p>
<h4 id="heading-what-if-you-dont-want-a-flex-item-to-shrink">What if you don't want a flex item to shrink?</h4>
<p>To prevent a flex item from shrinking, give it a <code>flex-shrink</code> value of <code>0</code>.</p>
<p>For example, when you give Number <code>1</code> a <code>flex-shrink</code> of <code>0</code>, it will maintain the width of 150px. And the other flex items will shrink to fit in the remaining space.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/34.-flex-shrink-vallue-0.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The first card does not shrink because it has a</em> <code>flex-shrink</code> value of <code>0</code></p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-q9zndc?file=style.css"><strong>Practice using the flex-shrink property</strong></a> <strong>on StackBlitz.</strong></p>
<h3 id="heading-the-flex-basis-property">The <code>flex-basis</code> property</h3>
<p>You can use the <code>flex-basis</code> property to set the default length of a specific flex item. This is either the width or height of the item depending on the <code>flex-direction</code>.</p>
<p>If the <code>flex-direction</code> is <code>row</code> or <code>row-reverse</code>, the value for <code>flex-basis</code> becomes the initial width of the item.</p>
<p>And if <code>flex-direction</code> is <code>column</code> or <code>column-reverse</code>, then the value for <code>flex-basis</code> becomes the initial height of the item.</p>
<p>Example:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">flex-direction</span>: column;  
    <span class="hljs-comment">/* Other styles */</span>
}

<span class="hljs-selector-tag">div</span> {  
    <span class="hljs-attribute">height</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-id">#jane</span> {  
    <span class="hljs-attribute">flex-basis</span>: <span class="hljs-number">60px</span>;
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/35.-flex-basis-height.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>flex-basis</code> setting the height of an item</p>
<p>In the example, the height for the divs is set at 20px. But Jane gets a <code>flex-basis</code> value of 60px. And that overrides the 20px given to all the divs.</p>
<p><strong>Note:</strong> The flex-basis of 60px becomes the height for Jane because the <code>flex direction</code> is <code>column</code>. This means the main axis is vertical.</p>
<p>Here is another example. This time, the <code>flex-direction</code> is <code>row</code>. This means the <code>flex-basis</code> will set the width of the item.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">flex-direction</span>: row;  
    <span class="hljs-comment">/* Other styles */</span>
}

<span class="hljs-selector-tag">div</span> {  
    <span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>;
}

<span class="hljs-selector-id">#jane</span> {  
    <span class="hljs-attribute">flex-basis</span>: <span class="hljs-number">140px</span>;
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/36.-flex-basis-width.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of</em> <code>flex-basis</code> setting the width of an item</p>
<p>While all the other divs have a width of 70px, Jane has a width of 140px set by the <code>flex-basis</code>.</p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-maihzd?file=style.css"><strong>Practice using the flex-basis property</strong></a> <strong>on StackBlitz.</strong></p>
<h3 id="heading-the-flex-shorthand-property">The <code>flex</code> Shorthand Property</h3>
<p>You can use <code>flex</code> as a shorthand for the <code>flex-grow</code>, <code>flex-shrink</code>, and <code>flex-basis</code> properties.</p>
<p>For example, instead of writing the following:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item</span> {  
    <span class="hljs-attribute">flex-grow</span>: <span class="hljs-number">2</span>;  
    <span class="hljs-attribute">flex-shrink</span>: <span class="hljs-number">0</span>;  
    <span class="hljs-attribute">flex-basis</span>: <span class="hljs-number">50px</span>;
}
</code></pre>
<p>You can use the shorthand like so and it will have the same effect:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item</span> {  
    <span class="hljs-attribute">flex</span>: <span class="hljs-number">2</span> <span class="hljs-number">0</span> <span class="hljs-number">50px</span>;
}
</code></pre>
<p>The <code>flex</code> property can take up to three values. The order of the values is important. The browser assigns the first value for <code>flex-grow</code>, the second for <code>flex-shrink</code>, and the third for <code>flex-basis</code>.</p>
<p>The default values for <code>flex</code> are <code>1 0 auto</code>.</p>
<p>This means if you give <code>flex</code> a single value of 2, the browser uses 2 for <code>flex-grow</code>. And then it sets <code>flex-shrink</code> to 0 and <code>flex-basis</code> to auto.</p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-m19hov?file=style.css"><strong>Practice using the</strong> <code>flex</code> property</a> <strong>on StackBlitz.</strong></p>
<h2 id="heading-how-to-center-an-element-with-flexbox">How to Center an Element With Flexbox</h2>
<p>One of the headaches for many front-end developers is centering elements. Flexbox has a perfect solution for that.</p>
<p>There are two steps involved.</p>
<ol>
<li><p>Make the parent element a flex container by setting <code>display</code> to <code>flex</code>.</p>
</li>
<li><p>Give a value of <code>center</code> to both <code>justify-content</code> and <code>align-items</code>.</p>
</li>
</ol>
<p>That's it! Your element will be perfectly centered.</p>
<p>Example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"name-container"</span>&gt;</span>  
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>JOHN<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>
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-class">.name-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">justify-content</span>: center;  
    <span class="hljs-attribute">align-items</span>: center;  
    <span class="hljs-comment">/* Other Styles */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/38.-center-element-w--flexbox.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of centering an element with Flexbox</em></p>
<p>Whether you're trying to center text, images, or even an entire navigation bar, this will work just fine.</p>
<h2 id="heading-flexbox-gaps">Flexbox Gaps</h2>
<p>You can use the <code>gap</code> property to adjust the space between flex items.</p>
<p><strong>NOTE:</strong> You apply the gap property on the flex container and not the flex items.</p>
<p><code>gap</code> can take two values: the first value for gaps between the rows and the second value for gaps between the columns.</p>
<p>Example:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">flex-wrap</span>: wrap;  
    <span class="hljs-attribute">gap</span>: <span class="hljs-number">50px</span> <span class="hljs-number">10px</span>; 
    <span class="hljs-comment">/* row-gap column-gap */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/39.-gap-two-values.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of giving two values for the gap property</em></p>
<p>If the gap you want between the rows and the columns is the same, you can use a single value. The browser will apply the same value to both rows and columns.</p>
<p>Example:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">flex-wrap</span>: wrap;  
    <span class="hljs-attribute">gap</span>: <span class="hljs-number">10px</span>; 
    <span class="hljs-comment">/* Other Styles */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/40.-gap-single-value.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of using only one value for both rows and columns gap</em></p>
<p>You can also use the properties <code>row-gap</code> if you need to apply a specific gap value between only the rows. and <code>column-gap</code> if you need to add gaps between only the columns.</p>
<p>Example: Adding gaps between only the rows:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">flex-wrap</span>: wrap;  
    <span class="hljs-attribute">row-gap</span>: <span class="hljs-number">20px</span>; 
    <span class="hljs-comment">/* Other Styles */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/41.-row-gap.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of using</em> <code>row-gap</code></p>
<p>Example: Adding gaps between only the columns:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.names-container</span> {  
    <span class="hljs-attribute">display</span>: flex;  
    <span class="hljs-attribute">flex-wrap</span>: wrap;  
    <span class="hljs-attribute">column-gap</span>: <span class="hljs-number">20px</span>; 
    <span class="hljs-comment">/* Other Styles */</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/08/42.-column-gap.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of using</em> <code>column-gap</code></p>
<p><a target="_blank" href="https://stackblitz.com/edit/js-v77toh?file=style.css"><strong>Practice using the gap property</strong></a> <strong>on StackBlitz.</strong></p>
<h2 id="heading-practice-with-flexbox-games">Practice with Flexbox Games</h2>
<p>Want to practice Flexbox in an interactive way? Check out the following games. They provide a hands-on experience for practicing Flexbox in a fun and engaging way.</p>
<ul>
<li><p><a target="_blank" href="https://flexboxfroggy.com/">Flexbox Froggy</a></p>
</li>
<li><p><a target="_blank" href="http://www.flexboxdefense.com/">Flexbox Defense</a></p>
</li>
<li><p><a target="_blank" href="https://mastery.games/flexboxzombies/">Flexbox Zombies</a></p>
</li>
</ul>
<h2 id="heading-are-there-bugs-in-css-flexbox">Are There Bugs in CSS Flexbox?</h2>
<p>While CSS Flexbox is a powerful layout tool, it's got a few bugs that may surprise you.</p>
<p>A common example is that <strong>some HTML elements cannot act as flex containers</strong>. These include the <code>&lt;button&gt;</code>, <code>&lt;fieldset&gt;</code>, and <code>&lt;summary&gt;</code> elements.</p>
<p>The workaround is to use an element like a <code>div</code> to wrap around the element's children. Then use Flexbox on the wrapper <code>div</code>.</p>
<p>If you are curious about other Flexbox bugs and workarounds, you can have a look at <a target="_blank" href="https://github.com/philipwalton/flexbugs">the Flexbugs repository</a> on GitHub.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this guide, you learned all the Flexbox properties, their values, and how to use them to create responsive layouts. You also learned about some games like Flexbox Froggy you can use for practice.</p>
<p>Thank you for reading, and happy coding! For more in-depth tutorials, feel free to <a target="_blank" href="https://www.youtube.com/@DevAfterHours">subscribe to my YouTube channel</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create and Publish an NPM Package – a Step-by-Step Guide ]]>
                </title>
                <description>
                    <![CDATA[ NPM is the largest software registry on the internet. There are over a million packages in the NPM Library. Developers publish packages on NPM to share their code with others. And organisations also use NPM to share code internally. In this article, ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-create-and-publish-your-first-npm-package/</link>
                <guid isPermaLink="false">66d45ddaa3a4f04fb2dd2e33</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ npm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Wed, 01 Feb 2023 21:36:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/npm-package-article-image.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>NPM is the largest software registry on the internet. There are over a million packages in the NPM Library.</p>
<p>Developers publish packages on NPM to share their code with others. And organisations also use NPM to share code internally.</p>
<p>In this article, you will learn how to create a package. And you will also learn how to publish your package on NPM so others can download and use it.</p>
<p>Let's get started!</p>
<h2 id="heading-how-to-choose-a-name-for-your-npm-package">How to Choose a Name For Your NPM Package</h2>
<p>The first thing you need to do before creating your package is to choose a name. This is important because your package needs to have a unique name. You should choose a name that has not been used already.</p>
<p>When you decide on a name, go to the <a target="_blank" href="https://www.npmjs.com/">NPM registry</a> and run a search. Be sure there's no exact match to the name you chose (or a match that is too similar).</p>
<p>For example, if there's a package called <code>hellonpmpackage</code> and you decide to call yours <code>hello-npm-package</code>, NPM will throw an error when you attempt to publish it.</p>
<p>If there's already a package in the NPM registry with the same you want to use, then you have two options.</p>
<ol>
<li><p>You can choose a different name.</p>
</li>
<li><p>You can publish your package as a scoped package (see the section "Publishing scoped packages" below).</p>
</li>
</ol>
<h2 id="heading-how-to-create-a-npm-package">How to Create a NPM Package</h2>
<p>Follow the steps below to create your package.</p>
<h3 id="heading-1-install-node">1. Install Node</h3>
<p>If you do not already have Node installed, you should go ahead and install it. You can visit the official website to <a target="_blank" href="https://nodejs.org/en/download/">download and install Node.js</a>. NPM comes pre-installed with Node.</p>
<h3 id="heading-2-initialize-a-git-repository">2. Initialize a Git Repository</h3>
<p>Create a new project folder for your package and navigate into the folder. Then, run the following command in your terminal:</p>
<pre><code class="lang-json">git init
</code></pre>
<p>This will help you track the changes you make to your package. Also, make sure you have a remote version of your repository on GitHub (or your preferred hosting service).</p>
<h3 id="heading-3-initialize-npm-in-your-project">3. Initialize NPM in Your Project</h3>
<p>To do this, navigate to the root directory of your project and run the following command:</p>
<pre><code class="lang-json">npm init
</code></pre>
<p>This command will create a <code>package.json</code> file. You will get prompts to provide the following information:</p>
<ul>
<li><p><code>package-name</code>: As you learned earlier in this tutorial, the name of your package must be unique. Also it must be lowercase. It may include hyphens.</p>
</li>
<li><p><code>version</code>: The initial value is 1.0.0. You update the number when you update your package using <a target="_blank" href="https://www.freecodecamp.org/news/semantic-versioning-1fd6f57749f7/">semantic versioning</a>.</p>
</li>
<li><p><code>description</code>: You can provide a description of your package here. Indicate what your package does and how to use it.</p>
</li>
<li><p><code>entry point</code>: The entry file for your code. The default value is <code>index.js</code>.</p>
</li>
<li><p><code>test command</code>: Here, you can add the command you want to run when a user runs <code>npm run test</code>.</p>
</li>
<li><p><code>git repository</code>: The link to your remote repository on GitHub.</p>
</li>
<li><p><code>keywords</code>: Add relevant keywords that will help others find your package on the NPM registry.</p>
</li>
<li><p><code>author</code>: Add your name.</p>
</li>
<li><p><code>license</code>: You can add a license or use the default license (Internet Systems Consortium (ISC) License).</p>
</li>
</ul>
<p>See the screenshot below for an example of how to answer the prompt questions:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/npm-image1.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Creating a package.json file</em></p>
<p><em>Note: I left the</em> <code>test command</code> blank because there is no test command for the package in this tutorial.</p>
<h3 id="heading-4-add-your-code">4. Add Your Code</h3>
<p>Now, you can go ahead and add the code for your package.</p>
<p>First, you need to create the file that will be loaded when your module is required by another application. For this tutorial, that will be the <code>index.js</code> file.</p>
<p>Inside the <code>index.js</code> file, add the code for your package.</p>
<p>For this tutorial, I will be creating a simple package called <code>first-hello-npm</code>. This package returns the string <code>"Hello NPM!"</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//index.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">helloNpm</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">"hello NPM"</span>
}

<span class="hljs-built_in">module</span>.exports = helloNpm
</code></pre>
<p>After creating your function, you should export it like in the example above. That way, anyone who downloads your package can load and use it in their code.</p>
<p>If you have been following along, you should now have your package created. But before you publish, you need to test your package. Testing your package reduces the chances of publishing bugs to the NPM registry.</p>
<h2 id="heading-how-to-test-your-npm-package">How to Test Your NPM Package</h2>
<p>Testing ensures that your NPM package works as expected. There are many ways to test your package. In this tutorial, you will learn one of the simplest ways of testing.</p>
<p>First, navigate to the root of your <code>package</code> project. Then, run the following command:</p>
<pre><code class="lang-json">npm link
</code></pre>
<p>This will make your package available globally. And you can require the package in a different project to test it out.</p>
<p>Create a <code>test</code> folder. And inside that test folder, add a <code>script.js</code> file.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/npm-image2.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of a test folder with a script.js file</em></p>
<p>In the example above, the test folder contains only the <code>script.js</code> file. It does not yet contain the package. To add the package you created to your test folder, run the command below:</p>
<pre><code class="lang-json">npm link &lt;name-of-package&gt;
</code></pre>
<p>In the case of the test folder for this tutorial, I will run the following command:</p>
<pre><code class="lang-json">npm link first-hello-npm
</code></pre>
<p>This will create a <code>node-modules</code> folder. And it'll add all the files and folders from your package – see the screenshot below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/npm-image3.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the <code>script.js</code> file, you can now require your package and use it for the test.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// test/script.js</span>

<span class="hljs-keyword">const</span> helloNpm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'first-hello-npm'</span>)

<span class="hljs-built_in">console</span>.log(helloNpm())
</code></pre>
<p>The <code>first-hello-npm</code> package is expected to return the string <code>"hello NPM!"</code>. As you can see from the screenshot below, the package works as expected when I run the script.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/npm-image4.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Test result for first-hello-npm package</em></p>
<p>After testing your package and ensuring it works as expected, you can now publish it on the NPM registry.</p>
<h2 id="heading-how-to-publish-your-npm-package">How to Publish Your NPM Package</h2>
<p>To publish your package on the NPM registry, you need to have an account. If you don't have an account, visit the <a target="_blank" href="https://www.npmjs.com/signup">NPM sign up page</a> to create one.</p>
<p>After creating the account, open your terminal and run the following command in the root of your package:</p>
<pre><code class="lang-json">npm login
</code></pre>
<p>You will get a prompt to enter your <code>username</code> and <code>password</code>. If login is successful, you should see a message like this:</p>
<p><code>Logged in as &lt;your-username&gt; on https://registry.npmjs.org/.</code></p>
<p>You can now run the following command to publish your package on the NPM registry:</p>
<pre><code class="lang-json">npm publish
</code></pre>
<p>If all goes well, you should get results similar to the screenshot below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/npm-image7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Notice indicating that the package is published successfully.</em></p>
<p>If you have been following along, then congratulations! You just published your first NPM package.</p>
<p>You can visit the <a target="_blank" href="https://www.npmjs.com/">NPM website</a> and run a search for your package. You should see your package show up in the search results.</p>
<p>For example, from the screenshot below, you can see the <code>first-hello-npm</code> package is now available on NPM.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/package-available.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The first-hello-npm package is now available on NPM</em></p>
<h2 id="heading-how-to-publish-scoped-npm-packages">How to Publish Scoped NPM Packages</h2>
<p>If an existing package has the same name you would like to use, the workaround is to publish a scoped package.</p>
<p>When you publish a scoped package, you have the option to make it public or private. If it's private, you can choose who you want to share the package with.</p>
<h3 id="heading-how-to-create-a-scoped-npm-package">How to Create a Scoped NPM Package</h3>
<p>To create a scoped package, first navigate to the root of your package directory.</p>
<p>Then, run the <code>npm init</code> command and pass your <code>username</code> as the value to the <code>scope</code> flag:</p>
<pre><code class="lang-json">npm init --scope=@your-username
</code></pre>
<p>Respond to the prompts to create a <code>package.json</code> file. For your package name, the format should be <code>@your-username/package-name</code>.</p>
<p>For example <code>@benjaminsemah/first-hello-npm</code>.</p>
<p>You can now add the code for your package and test it. The process is the same as already explained above.</p>
<p>Then, to publish your scoped package, run the following command in your terminal.</p>
<pre><code class="lang-json">npm publish --access public
</code></pre>
<p>You can change from <code>public</code> to <code>private</code> if you don't want to make the package available for public use.</p>
<p>You should see a response similar to this.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/scoped-package-published.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Scoped package published successfully.</em></p>
<p>Congratulations if you followed along. You've published your scoped package. You should see your scoped package on NPM if you search for it. For example in the screenshot below, you can see the scoped package I created in this tutorial.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/scoped-package-available.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Scoped package is now available on NPM</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Packages helps developers work faster. And they also improve collaboration. When you figure out a smarter way of doing things, one way you can share with the community is to create and publish your solution as a package.</p>
<p>In this article, you learned what packages are and why they are useful. You also learned how to create and publish packages on the NPM registry. The developer community awaits all the beautiful packages you will create and share.</p>
<p>Thanks for reading. And happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Are Node Modules and How Do You Use Them? ]]>
                </title>
                <description>
                    <![CDATA[ Every Node.js application has modules. These modules form part of the building blocks of the application. They help developers work faster and write more structured code. In this tutorial, you will learn what node modules are. You will also learn abo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-node-modules/</link>
                <guid isPermaLink="false">66d45df0182810487e0ce11d</guid>
                
                    <category>
                        <![CDATA[ Express ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ npm ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Tue, 06 Dec 2022 17:54:33 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/stock.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Every Node.js application has modules. These modules form part of the building blocks of the application. They help developers work faster and write more structured code.</p>
<p>In this tutorial, you will learn what node modules are. You will also learn about the three types of node modules. And we'll go over the right way to use them in your applications.</p>
<h2 id="heading-what-is-a-module-in-javascript">What is a Module in JavaScript?</h2>
<p>In simple terms, a module is a piece of reusable JavaScript code. It could be a <code>.js</code> file or a directory containing <code>.js</code> files. You can export the content of these files and use them in other files.</p>
<p>Modules help developers adhere to the DRY (Don't Repeat Yourself) principle in programming. They also help to break down complex logic into small, simple, and manageable chunks.</p>
<h2 id="heading-types-of-node-modules">Types of Node Modules</h2>
<p>There are three main types of Node modules that you will work with as a Node.js developer. They include the following.</p>
<ul>
<li><p>Built-in modules</p>
</li>
<li><p>Local modules</p>
</li>
<li><p>Third-party modules</p>
</li>
</ul>
<h3 id="heading-built-in-modules">Built-in Modules</h3>
<p>Node.js comes with some modules out of the box. These modules are available for use when you install Node.js. Some common examples of built-in Node modules are the following:</p>
<ul>
<li><p>http</p>
</li>
<li><p>url</p>
</li>
<li><p>path</p>
</li>
<li><p>fs</p>
</li>
<li><p>os</p>
</li>
</ul>
<p>You can use the built-in modules with the syntax below.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> someVariable = <span class="hljs-built_in">require</span>(<span class="hljs-string">'nameOfModule'</span>)
</code></pre>
<p>You load the module with the <code>require</code> function. You need to pass the name of the module you're loading as an argument to the <code>require</code> function.</p>
<p><strong>Note:</strong> The name of the module must be in quotation marks. Also, using <code>const</code> to declare the variable ensures that you do not overwrite the value when calling it.</p>
<p>You also need to save the returned value from the <code>require</code> function in <code>someVariable</code>. You can name that variable anything you want. But often, you will see programmers give the same to the variable as the name of the module (see example below).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>) 

server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> { 
    res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span>}) 
    res.end(<span class="hljs-string">'Hello World!'</span>)
})

server.listen(<span class="hljs-number">3000</span>)
</code></pre>
<p>You use the <code>require</code> function to load the built-in <code>http</code> module. Then, you save the returned value in a variable named <code>http</code>.</p>
<p>The returned value from the <code>http</code> module is an object. Since you've loaded it using the <code>require</code> function, you can now use it in your code. For example, call the <code>.createServer</code> property to create a server.</p>
<h3 id="heading-local-modules">Local Modules</h3>
<p>When you work with Node.js, you create local modules that you load and use in your program. Let's see how to do that.</p>
<p>Create a simple <code>sayHello</code> module. It takes a <code>userName</code> as a parameter and prints "hello" and the user's name.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params">userName</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello <span class="hljs-subst">${userName}</span>!`</span>)
}

<span class="hljs-built_in">module</span>.exports = sayHello
</code></pre>
<p>First, you need to create the function. Then you export it using the syntax <code>module.exports</code>. It doesn't have to be a function, though. Your module can export an object, array, or any data type.</p>
<h4 id="heading-how-to-load-your-local-modules">How to load your local modules</h4>
<p>You can load your local modules and use them in other files. To do so, you use the <code>require</code> function as you did for the built-in modules.</p>
<p>But with your custom functions, you need to provide the path of the file as an argument. In this case, the path is <code>'./sayHello</code>' (which is referencing the <code>sayHello.js</code> file).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sayHello = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./sayHello'</span>)
sayHello(<span class="hljs-string">"Maria"</span>) <span class="hljs-comment">// Hello Maria!</span>
</code></pre>
<p>Once you've loaded your module, you can make a reference to it in your code.</p>
<h3 id="heading-third-party-modules">Third-Party Modules</h3>
<p>A cool thing about using modules in Node.js is that you can share them with others. The Node Package Manager (NPM) makes that possible. When you install Node.js, NPM comes along with it.</p>
<p>With NPM, you can share your modules as packages via <a target="_blank" href="https://www.npmjs.com/">the NPM registry.</a> And you can also use packages others have shared.</p>
<h4 id="heading-how-to-use-third-party-packages">How to use third-party packages</h4>
<p>To use a third-party package in your application, you first need to install it. You can run the command below to install a package.</p>
<pre><code class="lang-javascript">npm install &lt;name-<span class="hljs-keyword">of</span>-package&gt;
</code></pre>
<p>For example, there's a package called <code>capitalize</code>. It performs functions like capitalizing the first letter of a word.</p>
<p>Running the command below will install the capitalize package:</p>
<pre><code class="lang-javascript">npm install capitalize
</code></pre>
<p>To use the installed package, you need to load it with the <code>require</code> function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> capitalize = <span class="hljs-built_in">require</span>(<span class="hljs-string">'capitalize)</span>
</code></pre>
<p>And then you can use it in your code, like this for example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> capitalize = <span class="hljs-built_in">require</span>(<span class="hljs-string">'capitalize'</span>)
<span class="hljs-built_in">console</span>.log(capitalize(<span class="hljs-string">"hello"</span>)) <span class="hljs-comment">// Hello</span>
</code></pre>
<p>This is a simple example. But there are packages that perform more complex tasks and can save you loads of time.</p>
<p>For example, you can use the Express.js package which is a Node.js framework. It makes building apps faster and simple. To learn more about NPM, read this <a target="_blank" href="https://www.freecodecamp.org/news/what-is-npm-a-node-package-manager-tutorial-for-beginners/">freeCodeCamp article on the Node Package Manager</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned about what Node modules are and the three types of node modules. You also learned about how to use the different types in your application.</p>
<p>Thanks for reading. And happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Exactly is Node.js? Explained for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ Node.js allows developers to create both front-end and back-end applications using JavaScript. It was released in 2009 by Ryan Dahl. In this article, you will learn about Node.js. You will learn the following: What is Node.js? How the Node.js envir... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-node-js/</link>
                <guid isPermaLink="false">66d45df255db48792eed3f4f</guid>
                
                    <category>
                        <![CDATA[ Express ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ npm ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Mon, 05 Dec 2022 15:18:12 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/What-is.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Node.js allows developers to create both front-end and back-end applications using JavaScript. It was released in 2009 by Ryan Dahl.</p>
<p>In this article, you will learn about Node.js. You will learn the following:</p>
<ul>
<li><p>What is Node.js?</p>
</li>
<li><p>How the Node.js environment differs from the browser.</p>
</li>
<li><p>Why you should learn Node.js.</p>
</li>
<li><p>How to get started with Node.js.</p>
</li>
<li><p>Resources to help you learn Node.js.</p>
</li>
</ul>
<h2 id="heading-what-is-nodejs">What is Node.js?</h2>
<blockquote>
<p>"Node.js is an open-source and cross-platform JavaScript runtime environment." - <a target="_blank" href="https://nodejs.dev/en/learn/introduction-to-nodejs/">Nodejs.dev Docs</a></p>
</blockquote>
<p>This sounds like a cool, straightforward answer. But for a beginner, this definition might raise further questions. So let's break it down and understand what it means.</p>
<p><strong>Node.js is open-source:</strong> This means that the source code for Node.js is publicly available. And it's maintained by contributors from all over the world. The <a target="_blank" href="https://nodejs.org/en/get-involved/contribute/">Node.js contribution guide</a> shows you how to contribute.</p>
<p><strong>Node.js is cross-platform:</strong> Node.js is not dependent on any operating system software. It can work on Linux, macOS, or Windows.</p>
<p><strong>Node.js is a JavaScript runtime environment:</strong> When you write JavaScript code in your text editor, that code cannot perform any task unless you execute (or run) it. And to run your code, you need a runtime environment.</p>
<p>Browsers like Chrome and Firefox have runtime environments. That is why they can run JavaScript code. Before Node.js was created, JavaScript could only run in a browser. And it was used to build only front-end applications.</p>
<p>Node.js provides a runtime environment outside of the browser. It's also built on the <a target="_blank" href="https://www.freecodecamp.org/news/javascript-under-the-hood-v8/">Chrome V8 JavaScript engine</a>. This makes it possible to build back-end applications using the same JavaScript programming language you may be familiar with.</p>
<h2 id="heading-differences-between-the-browser-and-nodejs-runtime-environments">Differences Between the Browser and Node.js Runtime Environments</h2>
<p>Both the browser and Node.js are capable of executing JavaScript programs. But there are some key differences that you need to know. They include the following.</p>
<h3 id="heading-access-to-the-dom-apis">Access to the DOM APIs</h3>
<p>With the browser runtime, you can access the Document Object Model (DOM). And you can perform all the DOM operations. But Node.js does not have access to the DOM.</p>
<p>Node.js exposes almost all the system resources to your programs. This means you can interact with the operating system, access the file systems, and read and write to the files. But, you do not have access to operating systems and file systems from the browser.</p>
<h3 id="heading-window-vs-global-object">Window vs Global object</h3>
<p>JavaScript has a built-in global object. The JavaScript global object for the browser is called the <code>window</code> object. In Node.js, the global object goes by the name <code>global</code>.</p>
<p>The <code>window</code> object contains methods and properties available only in the browser environment.</p>
<h3 id="heading-control-over-runtime-versions">Control over runtime versions</h3>
<p>With Node.js, you can choose which version to run your server-side application on. As a result, you can use modern JavaScript features without worrying about any version-specific inconsistencies.</p>
<p>Contrast this to the browser runtime environment. As a developer, you have no control over the version of browsers your clients use to access your app.</p>
<h3 id="heading-loading-modules-import-vs-require-keywords">Loading modules (<code>import</code> vs <code>require</code> keywords)</h3>
<p>Node.js offers out-of-the-box support for CommonJS and ES modules. You can load modules using the <code>require</code> keyword (CommonJS syntax) and the <code>import</code> keyword (ES syntax).</p>
<p>Some modern browsers support ES modules. This means you can use <code>import</code> ES modules. But you will still need to create bundles to cater to older browsers that do not support ES modules.</p>
<h2 id="heading-how-much-javascript-do-you-need-to-get-started-with-node">How Much JavaScript Do You Need to Get Started with Node?</h2>
<p>If you are an absolute beginner to JavaScript, I recommend that you start with the basics.</p>
<p>Become familiar with basic JavaScript concepts first. Then, you can move on to learning to build server-side applications with Node.js.</p>
<p>There's no way you'll ever exhaust all there is to learn about JavaScript. So, how to determine when you know enough JavaScript to get started with Node.js?</p>
<p>The Node.js documentation provides a <a target="_blank" href="https://nodejs.org/en/learn/getting-started/how-much-javascript-do-you-need-to-know-to-use-nodejs">list of JavaScript topics to learn</a> before diving deep with Node.js.</p>
<p>Once you have a grasp of JavaScript basics, then you can get started with Node.js</p>
<h2 id="heading-how-to-get-started-with-nodejs">How to Get Started with Node.js</h2>
<p>Let's see how you can create your first Node.js application. This section will show you how to run Node.js scripts from the command line.</p>
<h3 id="heading-how-to-download-and-install-nodejs">How to download and install Node.js</h3>
<p>First, you need to download and install Node.js. There are different ways you can do that. If you are a beginner, I would suggest that you <a target="_blank" href="https://nodejs.org/en/download/">download Node.js from the official website</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/node1.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Screenshot of the official Node.js website</em></p>
<p>Official packages are available on the website for all major platforms (Windows, macOS, and Linux). Download and install the appropriate package for your system.</p>
<h3 id="heading-how-to-check-the-nodejs-version">How to check the Node.js version</h3>
<p>To check the Node.js version, run the command <code>node --version</code> in your terminal.<br>If the installation was successful, you will see the version of Node.js you installed. You should get a response like the screenshot below.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/node2.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-run-nodejs-from-the-command-line">How to run Node.js from the command line</h3>
<p>Let's build a simple <code>Hello World</code> app.</p>
<p>Create a new project folder. You can call it <code>my-project.</code> Open the project in your code editor. Inside the folder, create an <code>app.js</code> file.</p>
<p>Add the following code to <code>app.js</code></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/node3.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>As you can see, this is JavaScript code.</p>
<p>You can run the script in the command line by running the command <code>node &lt;fileName&gt;</code>. In this case, the file name is <code>app.js</code>.</p>
<p>Run the following command in your terminal to execute the <code>Hello world.</code> program:</p>
<pre><code class="lang-bash">node app.js
</code></pre>
<p>You should see the string "Hello world." logged in your terminal like so.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/node4.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Congratulations! You just ran your first Node.js application.</p>
<h2 id="heading-should-you-learn-nodejs">Should You Learn Node.js?</h2>
<p>Here are some reasons why you should consider learning Node.js</p>
<h3 id="heading-nodejs-allows-you-to-write-javascript-on-both-client-and-server">Node.js allows you to write JavaScript on both client and server.</h3>
<p>One of the advantages of Node.js is that it allows you to work on both the front-end and back-end of your application. And you use one programming language – JavaScript – to do so.</p>
<p>This is good news for front-end developers who work with JavaScript. If you want to start working on the server side, it's easier compared to learning a new back-end language from scratch.</p>
<h3 id="heading-node-has-a-vibrant-community">Node has a vibrant community.</h3>
<p>As I mentioned earlier in the article, Node.js is open-sourced. It is actively maintained by developers from all over the world.</p>
<p>There is a vibrant community surrounding Node.js. You can find excellent tutorials and solutions to problems when you get stuck.</p>
<h3 id="heading-node-is-built-on-top-of-google-chromes-v8-engine">Node is built on top of Google Chrome's V8 engine.</h3>
<p>Node.js is built on top of the Chrome V8 JavaScript engine. This is significant because the V8 engine powers some of Google's in-browser applications like Gmail. As such, Google invests heavily to ensure it offers high performance.</p>
<h3 id="heading-demand-in-the-market">Demand in the market</h3>
<p>Many big names like Netflix, Uber, Paypal, and LinkedIn, and others use Node.js. Apart from the big names, many startups also use Node.js in developing their applications.</p>
<p>Learning to work with Node.js will make you a desirable candidate in the job market.</p>
<h3 id="heading-the-npm-library">The NPM library</h3>
<p>The NPM library is one of the excellent resources that comes with Node.js.<br>The library contains a registry of over a million packages. A package is a reusable piece of code.</p>
<p>You can create a package for a recurring task or problem and share the code with others via the registry.</p>
<p>You can also download packages that others have shared. For many tasks that developers perform regularly, there are packages available for that.</p>
<h2 id="heading-resources-to-learn-node">Resources to Learn Node</h2>
<p>If you are curious about learning how to build Node.js applications, I recommend the following resources.</p>
<ul>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=Oe421EPjeBE">8-Hour Node.js and Express.js Course on freeCodeCamp YouTube Channel</a>.</p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/learn/back-end-development-and-apis/">The freeCodeCamp Backend Development and APIs curriculum</a></p>
</li>
<li><p><a target="_blank" href="https://nodejs.dev/en/learn">Nodejs.dev Documentation</a></p>
</li>
</ul>
<p>Also, below is a link to a video of Ryan Dahl when he first presented Node.js.</p>
<p><a target="_blank" href="https://www.youtube.com/watch?v=ztspvPYybIY">Ryan Dahl: Original Node.js presentation at JSConf 2009</a></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>A single blog post like this is not enough to learn all there is to know about Node.js. The purpose of this article was to give you an overview of what Node.js is.</p>
<p>If you were not sure what Node.js is, I hope this article addressed your concerns and cleared your confusion.</p>
<p>Thanks for reading. And happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Schedule an Email in Gmail – a Step-by-Step Guide ]]>
                </title>
                <description>
                    <![CDATA[ Sometimes you might want to compose an email but send it later. Well, did you know that Gmail allows you to schedule up to 100 emails? In this article, you will learn how to schedule your emails using Gmail. There's no need to install any software or... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/schedule-email-in-gmail/</link>
                <guid isPermaLink="false">66d45de5182810487e0ce10e</guid>
                
                    <category>
                        <![CDATA[ email ]]>
                    </category>
                
                    <category>
                        <![CDATA[ gmail ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Wed, 30 Nov 2022 22:23:40 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/email-gd2563c0fc_1280.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Sometimes you might want to compose an email but send it later. Well, did you know that Gmail allows you to schedule up to 100 emails?</p>
<p>In this article, you will learn how to schedule your emails using Gmail. There's no need to install any software or plugins.</p>
<h2 id="heading-what-you-will-learn">What you will learn</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-schedule-an-email-in-gmail">How to schedule an email in Gmail</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-view-or-edit-a-scheduled-email-in-gmail">How to view or edit a scheduled email in Gmail</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-cancel-a-scheduled-email-in-gmail">How to cancel a scheduled email in Gmail</a></p>
</li>
</ul>
<h2 id="heading-how-to-schedule-an-email-in-gmail">How to Schedule an Email in Gmail</h2>
<p><strong>Step 1:</strong> Log in to your Gmail account.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/1.-login.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Step 2:</strong> Click compose to create your email.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/2.-click-compose.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Step 3:</strong> Create the email you want to schedule.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/3.-create-email.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Step 4:</strong> Click the Down arrow on the <code>Send</code> button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/4.-click-arrow.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Step 5:</strong> Click <code>Schedule send</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/5.-schedule-send.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Step 6:</strong> The popup modal give you a few options. You can choose one. Or you can create a custom date/time by clicking <code>Select date and time</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/6.-select-date-time.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Step 7:</strong> Click the <code>Schedule send</code> button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/7.-schedule-send2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>That's it! Your email is now scheduled. You will see a notification from Gmail (like the one below) confirming a successful schedule.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/8.-success-schedule.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Next, let's see how you can edit a scheduled mail in Gmail. This can be either editing the content of the mail or changing the scheduled time.</p>
<h2 id="heading-how-to-edit-a-scheduled-email-in-gmail">How to Edit a Scheduled Email in Gmail</h2>
<p>Assuming you are already logged in to your Gmail, continue with the steps below. If not, first login and then continue with the steps below.</p>
<p><strong>Step 1:</strong> To edit a scheduled email, click <code>Scheduled</code> on the left panel.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/scheduled.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Step 2:</strong> You will be presented with a list of your scheduled emails. Select the email you want to edit.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/schedule-list.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Step 3:</strong> Click <code>Cancel send</code> at the top right of your email.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/cancel-send.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Step 4:</strong> Make the changes if you want to edit the content of your email. If you only want to change the scheduled time, move to Step 5.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/edit-schedule.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Step 5:</strong> Next, you use the same process you used for the initial schedule.</p>
<ul>
<li><p>Click the down arrow next to the <code>Send</code> button.</p>
</li>
<li><p>And then click <code>Schedule send</code>.</p>
</li>
<li><p>Choose a new date and time.</p>
</li>
</ul>
<p>That's it! You've successfully edited the scheduled email.</p>
<h2 id="heading-how-to-cancel-a-scheduled-email-in-gmail">How to Cancel a Scheduled Email in Gmail</h2>
<p>Assuming you are already logged in to your Gmail, continue with the steps below. If not, first login and then continue with the steps below.</p>
<p><strong>Step 1:</strong> To cancel a scheduled email, click <code>Scheduled</code> on the left panel.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/scheduled-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Step 2:</strong> You will be presented with a list of your scheduled emails. Select the email you want to cancel.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/schedule-list-1.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Step 3:</strong> Click <code>Cancel send</code> at the top right of your email.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/cancel-send-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Note that cancelling a scheduled email in Gmail does not delete it. Gmail treats it as a draft and adds it to the drafts folder. See the Gmail notification below.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/msg-revert.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You now know how to do the following.</p>
<ul>
<li><p>Schedule an email in Gmail.</p>
</li>
<li><p>Edit or change the date/time for a scheduled email.</p>
</li>
<li><p>Cancel a scheduled email.</p>
</li>
</ul>
<p>You can also check out this <a target="_blank" href="https://www.freecodecamp.org/news/how-to-batch-delete-emails-in-gmail-delete-multiple-email-messages/">freeCodeCamp article on how to batch delete Emails</a>.</p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Validate URLs in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ A Uniform Resource Locator (URL) is what leads you to a page or file on the internet. URLs serve as the addresses of things on the internet. All valid URLs follow certain patterns. So if you know those patterns, you can determine whether a URL is val... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-validate-urls-in-javascript/</link>
                <guid isPermaLink="false">66d45dde51f567b42d9f8447</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ npm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Regex ]]>
                    </category>
                
                    <category>
                        <![CDATA[ url ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Tue, 22 Nov 2022 04:12:10 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/08/jase-bloor-oCZHIa1D4EU-unsplash--1-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A Uniform Resource Locator (URL) is what leads you to a page or file on the internet. URLs serve as the addresses of things on the internet.</p>
<p>All valid URLs follow certain patterns. So if you know those patterns, you can determine whether a URL is valid or not in your program and give feedback, throw an error, and so on.</p>
<p>In this tutorial, you will learn three methods to check if a string in JavaScript is a valid URL:</p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-use-the-url-constructor-to-validate-urls">How to Use the <code>URL</code> Constructor to Validate URLs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-npm-packages-to-validate-urls">How to Use npm Packages to Validate URLs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-regex-to-validate-urls">How to Use Regex to Validate URLs</a></p>
</li>
</ul>
<h2 id="heading-how-to-use-the-url-constructor-to-validate-urls">How to Use the <code>URL</code> Constructor to Validate URLs</h2>
<p>When you pass a string to the <code>URL</code> constructor, it returns a new <code>URL</code> object if a string is a valid URL. Otherwise, it returns an error:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fccUrl = <span class="hljs-keyword">new</span> URL(<span class="hljs-string">"https://www.freecodecamp.org/"</span>);
<span class="hljs-built_in">console</span>.log(fccUrl);
</code></pre>
<p>The following is what you get when you log <code>fccUrl</code> to the console:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/validURL.PNG" alt="A URL object in JavaScript" width="600" height="400" loading="lazy"></p>
<p><em>A</em> <code>URL</code> object in JavaScript</p>
<p>This object means that the string you passed to the <code>URL</code> constructor was a valid URL.</p>
<p>Now let's see what you get when you pass an invalid URL string:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fccUrl = <span class="hljs-keyword">new</span> URL(<span class="hljs-string">'freecodecamp'</span>);
<span class="hljs-built_in">console</span>.log(fccUrl);
</code></pre>
<p>The string <code>'freecodecamp'</code> is not a valid URL. Thus, you get the following <code>TypeError</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/invalidURL.PNG" alt="A TypeError after passing an invalid URL to the URL constructor" width="600" height="400" loading="lazy"></p>
<p><em>Invalid URL</em></p>
<p>To recap:</p>
<ol>
<li><p>When you pass a valid URL string to the <code>URL</code> constructor, it returns a new <code>URL</code> object.</p>
</li>
<li><p>When you pass an invalid URL string to the <code>URL</code> constructor, it returns a <code>TypeError</code>.</p>
</li>
</ol>
<p>With this knowledge, you can create a custom function to check the validity of a given URL string.</p>
<h3 id="heading-how-to-create-a-url-validator-function-with-the-url-constructor">How to Create a URL Validator Function with the <code>URL</code> Constructor</h3>
<p>By using the <code>URL</code> constructor and a <code>try...catch</code> statement, you can create a custom <code>isValidUrl</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isValidUrl</span>(<span class="hljs-params">string</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">new</span> URL(string);
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}
</code></pre>
<p>The <code>isValidUrl</code> function returns <code>true</code> when the string you pass as an argument is a valid URL. Otherwise, it returns <code>false</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(isValidUrl(<span class="hljs-string">'https://www.freecodecamp.org/'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(isValidUrl(<span class="hljs-string">'mailto://mail@freecodecamp.org'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(isValidUrl(<span class="hljs-string">'freecodecamp'</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<h3 id="heading-how-to-validate-only-http-urls-with-the-url-constructor">How to Validate Only HTTP URLs with the <code>URL</code> Constructor</h3>
<p>Sometimes, you may want to check if the string is a valid HTTP URL, and reject other valid URLs like <code>'mailto://mail@freecodecamp.org'</code>.</p>
<p>If you look closely at the <code>URL</code> object, one of its properties is <code>protocol</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/protocol.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The</em> <code>URL</code> object has a protocol property.</p>
<p>In the example above, the value of the protocol property is <code>'https:'</code>.</p>
<p>To check if a string is a valid HTTP URL, you can use the protocol property of the URL object:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isValidHttpUrl</span>(<span class="hljs-params">string</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> newUrl = <span class="hljs-keyword">new</span> URL(string);
    <span class="hljs-keyword">return</span> newUrl.protocol === <span class="hljs-string">'http:'</span> || newUrl.protocol === <span class="hljs-string">'https:'</span>;
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}

<span class="hljs-built_in">console</span>.log(isValidHttpUrl(<span class="hljs-string">'https://www.freecodecamp.org/'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(isValidHttpUrl(<span class="hljs-string">'mailto://mail@freecodecamp.org'</span>)); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(isValidHttpUrl(<span class="hljs-string">'freecodecamp'</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<p>The difference here is that you're not returning <code>true</code> after the new <code>URL</code> object is created. Instead, you're checking if the <code>protocol</code> property has a value equal to <code>'http:'</code> or <code>'https:'</code> and returning <code>true</code> if it is and <code>false</code> if not.</p>
<h2 id="heading-how-to-use-npm-packages-to-validate-urls">How to Use npm Packages to Validate URLs</h2>
<p>There are two NPM packages you can use: <code>is-url</code> and <code>is-url-http</code>.</p>
<p>These packages are the simplest way to check if a string is a valid URL. All you need to do is pass in a string as a parameter, and they will return <code>true</code> or <code>false</code>.</p>
<p>Let's see how both of these packages work.</p>
<h3 id="heading-how-to-validate-urls-with-the-is-url-package">How to Validate URLs with the <code>is-url</code> Package</h3>
<p>You can use the <code>is-url</code> package to check if a string is a valid URL. This package does not check the protocol of the URL passed to it.</p>
<p>To use <code>is-url</code>, first install it using the command below:</p>
<pre><code class="lang-javascript">npm install is-url
</code></pre>
<p>Then import it and pass your URL string to it as an argument:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> isUrl <span class="hljs-keyword">from</span> <span class="hljs-string">'is-url'</span>;

<span class="hljs-keyword">const</span> firstCheck = isUrl(<span class="hljs-string">'https://www.freecodecamp.org/'</span>);
<span class="hljs-keyword">const</span> secondCheck = isUrl(<span class="hljs-string">'mailto://mail@freecodecamp.org'</span>);
<span class="hljs-keyword">const</span> thirdCheck = isUrl(<span class="hljs-string">'freeCodeCamp'</span>);

<span class="hljs-built_in">console</span>.log(firstCheck); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(secondCheck); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(thirdCheck); <span class="hljs-comment">// false</span>
</code></pre>
<p>The <code>is-url</code> package returns <code>true</code> for strings that have valid URL formats and <code>false</code> for strings that have invalid URL formats.</p>
<p>In the example, both <code>firstCheck</code> (with the <code>https:</code> protocol) and <code>secondCheck</code> (with the <code>mailto:</code> protocol) return <code>true</code>.</p>
<h3 id="heading-how-to-validate-http-urls-with-the-is-http-url-package">How to Validate HTTP URLs with the <code>is-http-url</code> Package</h3>
<p>You can use the <code>is-url-http</code> package to check if a string is a valid HTTP URL.</p>
<p>Install the package with the following command:</p>
<pre><code class="lang-javascript">npm install is-url-http
</code></pre>
<p>Then import it and pass the URL string to it like so:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> isUrlHttp <span class="hljs-keyword">from</span> <span class="hljs-string">'is-url-http'</span>;

<span class="hljs-keyword">const</span> firstCheck = isUrlHttp(<span class="hljs-string">'https://www.freecodecamp.org/'</span>);
<span class="hljs-keyword">const</span> secondCheck = isUrlHttp(<span class="hljs-string">'mailto://freecodecamp@mail.org'</span>);
<span class="hljs-keyword">const</span> thirdCheck = isUrlHttp(<span class="hljs-string">'freeCodeCamp'</span>);

<span class="hljs-built_in">console</span>.log(firstCheck); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(secondCheck); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(thirdCheck); <span class="hljs-comment">// false</span>
</code></pre>
<p>In this example, only <code>firstCheck</code> returns <code>true</code>. The <code>is-url-http</code> package is not only checks that the string is a valid URL, it also checks if it's a valid HTTP URL. That is why it returns <code>false</code> for <code>secondCheck</code>, which is not a valid HTTP URL.</p>
<h2 id="heading-how-to-use-regex-to-validate-urls">How to Use Regex to Validate URLs</h2>
<p>You can also use regex, or a regular expression, to check if a string is a valid URL or not.</p>
<p>All valid URLs follow a particular pattern. They have three main parts, which are:</p>
<ul>
<li><p>Protocol</p>
</li>
<li><p>Domain name (or IP address)</p>
</li>
<li><p>Port and path</p>
</li>
</ul>
<p>Sometimes a query string or fragment locator follows the path.</p>
<p>You can learn more about URL patterns from this <a target="_blank" href="https://www.freecodecamp.org/news/what-happens-when-you-hit-url-in-your-browser/">freeCodeCamp article on the structure of URLs</a>.</p>
<p>Knowing the pattern URLs are made of, you can use regex to check for the existence of such patterns in a string. If the patterns exist, then the string passes the regex test. Otherwise, it fails.</p>
<p>Also, using regex, you can check for all valid URLs, or only check for valid HTTP URLs.</p>
<h3 id="heading-how-to-validate-urls-with-regex">How to Validate URLs with Regex</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isValidUrl</span>(<span class="hljs-params">str</span>) </span>{
  <span class="hljs-keyword">const</span> pattern = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(
    <span class="hljs-string">'^([a-zA-Z]+:\\/\\/)?'</span> + <span class="hljs-comment">// protocol</span>
      <span class="hljs-string">'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'</span> + <span class="hljs-comment">// domain name</span>
      <span class="hljs-string">'((\\d{1,3}\\.){3}\\d{1,3}))'</span> + <span class="hljs-comment">// OR IP (v4) address</span>
      <span class="hljs-string">'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'</span> + <span class="hljs-comment">// port and path</span>
      <span class="hljs-string">'(\\?[;&amp;a-z\\d%_.~+=-]*)?'</span> + <span class="hljs-comment">// query string</span>
      <span class="hljs-string">'(\\#[-a-z\\d_]*)?$'</span>, <span class="hljs-comment">// fragment locator</span>
    <span class="hljs-string">'i'</span>
  );
  <span class="hljs-keyword">return</span> pattern.test(str);
}

<span class="hljs-built_in">console</span>.log(isValidUrl(<span class="hljs-string">'https://www.freecodecamp.org/'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(isValidUrl(<span class="hljs-string">'mailto://freecodecamp.org'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(isValidUrl(<span class="hljs-string">'freeCodeCamp'</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<p>The regex in the <code>isValidUrl</code> function above checks if a string is a valid URL. The protocol check <code>^([a-zA-Z]+:\\/\\/)?</code> is not limited to just <code>https:</code>.</p>
<p>This is why the second example with the <code>mailto:</code> protocol returns <code>true</code>.</p>
<h3 id="heading-how-to-validate-http-urls-with-regex">How to Validate HTTP URLs with Regex</h3>
<p>To use regex to check if a string is a valid HTTP URL, you need to edit the protocol check.</p>
<p>Instead of <code>^([a-zA-Z]+:\\/\\/)?</code>, you should use <code>'^(https?:\\/\\/)?'</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isValidHttpUrl</span>(<span class="hljs-params">str</span>) </span>{
  <span class="hljs-keyword">const</span> pattern = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(
    <span class="hljs-string">'^(https?:\\/\\/)?'</span> + <span class="hljs-comment">// protocol</span>
      <span class="hljs-string">'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'</span> + <span class="hljs-comment">// domain name</span>
      <span class="hljs-string">'((\\d{1,3}\\.){3}\\d{1,3}))'</span> + <span class="hljs-comment">// OR ip (v4) address</span>
      <span class="hljs-string">'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'</span> + <span class="hljs-comment">// port and path</span>
      <span class="hljs-string">'(\\?[;&amp;a-z\\d%_.~+=-]*)?'</span> + <span class="hljs-comment">// query string</span>
      <span class="hljs-string">'(\\#[-a-z\\d_]*)?$'</span>, <span class="hljs-comment">// fragment locator</span>
    <span class="hljs-string">'i'</span>
  );
  <span class="hljs-keyword">return</span> pattern.test(str);
}

<span class="hljs-built_in">console</span>.log(isValidHttpUrl(<span class="hljs-string">'https://www.freecodecamp.org/'</span>)); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(isValidHttpUrl(<span class="hljs-string">'mailto://freecodecamp.org'</span>)); <span class="hljs-comment">// false</span>
<span class="hljs-built_in">console</span>.log(isValidHttpUrl(<span class="hljs-string">'freeCodeCamp'</span>)); <span class="hljs-comment">// false</span>
</code></pre>
<p>Now only the first example which has a valid <code>https:</code> protocol returns <code>true</code>. Note that URL strings with <code>http:</code> work, too.</p>
<h2 id="heading-wrapping-up">Wrapping up!</h2>
<p>In this article, you learned how to check the validity of URLs in JavaScript. You now know the following three methods for doing so.</p>
<ul>
<li><p>How to Use the <code>URL</code> Constructor to Validate URLs</p>
</li>
<li><p>How to Use npm Packages to Validate URLs (<code>is-url</code> and <code>is-http-url</code>)</p>
</li>
<li><p>How to Use Regex to Validate URLs</p>
</li>
</ul>
<p>It's up to you to choose which method you're comfortable working with.</p>
<p>Thanks for reading. And happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Recursion in JavaScript? ]]>
                </title>
                <description>
                    <![CDATA[ Recursion is a problem-solving technique in programming. In this article, you will learn how to use recursive functions in JavaScript. What is a Recursive Function? A recursive function is a function that calls itself somewhere within the body of the... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/recursion-in-javascript/</link>
                <guid isPermaLink="false">66d45de155db48792eed3f47</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Recursion ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Mon, 14 Nov 2022 18:44:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/benjamin-semah-freecodecamp-recursion.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Recursion is a problem-solving technique in programming. In this article, you will learn how to use recursive functions in JavaScript.</p>
<h2 id="heading-what-is-a-recursive-function">What is a Recursive Function?</h2>
<p>A recursive function is a function that calls itself somewhere within the body of the function. Below is a basic example of a recursive function.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">recursiveFunc</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// some code here... </span>
  recursiveFunc()
}
</code></pre>
<p>As you can see, the <code>recursiveFunc</code> function calls itself within the body of the function. It will repeat calling itself until the desired output is achieved.</p>
<p>So how do you tell the function when to stop calling itself? You do that using a <strong>base condition</strong>.</p>
<h2 id="heading-the-three-parts-of-a-recursive-function">The Three Parts of a Recursive Function</h2>
<p>Every time you write a recursive function, three elements must be present. They are:</p>
<ul>
<li><p>The function definition.</p>
</li>
<li><p>The base condition.</p>
</li>
<li><p>The recursive call.</p>
</li>
</ul>
<p>When these three elements are missing, your recursive function won't work as you expect. Let's take a closer look at each one.</p>
<h3 id="heading-how-to-define-a-recursive-function">How to define a recursive function</h3>
<p>You define a recursive function the same way you define regular JavaScript functions.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">recursiveFunc</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// some code here...</span>
}
</code></pre>
<p>What differentiates recursive functions from regular JavaScript functions are the base condition and the recursive call.</p>
<h3 id="heading-what-is-a-base-condition">What is a base condition?</h3>
<p>When using a recursive function, the base condition is what lets the function know when to stop calling itself. Once the base condition is met, the recursion ends.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">recursiveFunc</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span>(base condition) {
    <span class="hljs-comment">// stops recursion if condition is met</span>
  }
  <span class="hljs-comment">// else recursion continues</span>
  recurse();
}
</code></pre>
<h3 id="heading-why-do-you-need-a-base-condition">Why do you need a base condition?</h3>
<p>Without the base condition, you will run into infinite recursion. A situation where your function continues calling itself without stopping, like this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomething</span>(<span class="hljs-params">action</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I am <span class="hljs-subst">${action}</span>.`</span>)
  doSomething(action)
}

doSomething(<span class="hljs-string">"running"</span>)
</code></pre>
<p>Also, without a base condition, your function exceeds the maximum call stack. You will run into the error shown below.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/benjamin-semah-max-callstack.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Maximum call stack exceeded when there's no base condition</em></p>
<p>The Call Stack keeps track of what functions are currently running and the functions that are within them.</p>
<p>The call stack has a limit. And since a recursive function without a base condition will run infinitely, it exceeds the call stack's limit.</p>
<p>The base condition provides a way to break out when the function gets the desired output.</p>
<h3 id="heading-example-of-recursive-function">Example of recursive function</h3>
<p>Let's see a simple example of a recursive function.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomething</span>(<span class="hljs-params">n</span>) </span>{
  <span class="hljs-keyword">if</span>(n === <span class="hljs-number">0</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"TASK COMPLETED!"</span>)
    <span class="hljs-keyword">return</span>
  }
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'm doing something."</span>)
  doSomething(n - <span class="hljs-number">1</span>)
}
doSomething(<span class="hljs-number">3</span>)
</code></pre>
<p>Here is the result when you pass the number <code>3</code> to the <code>doSomething</code> function.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/11/benjamin-semah-task-completed.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The base condition for the <code>doSomething</code> function is <code>n === 0</code>. Anytime the function is called, it first checks if the base condition is met.</p>
<p>If yes, it prints <code>TASK COMPLETED!</code>. If not, it continues with the rest of the code in the function. In this case, it will print <code>I'm doing something.</code> and then call the function again.</p>
<h3 id="heading-the-recursive-call">The recursive call</h3>
<p>The recursive call is what handles the function calling itself again. In the <code>doSomething</code> function, the recursive call is the line below.</p>
<pre><code class="lang-javascript">doSomething(n<span class="hljs-number">-1</span>)
</code></pre>
<p>Note what happens when the function calls itself. A new parameter <code>n - 1</code> is passed to the function. On every iteration of a recursive call, the parameter will differ from that of the previous call.</p>
<p>The function will keep calling itself until the new parameter satisfies the base condition.</p>
<h2 id="heading-recursion-vs-loops">Recursion vs Loops</h2>
<p>Recursion and loops work in similar ways. Every recursive function you write has an alternative solution with a loop.</p>
<p>For example, you can create a function to find the factorial of a given number using both recursion and loops.</p>
<h3 id="heading-how-to-find-the-factorial-with-a-loop">How to find the factorial with a loop:</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findFactorial</span>(<span class="hljs-params">num</span>) </span>{
  <span class="hljs-keyword">let</span> factorial = <span class="hljs-number">1</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = num; i &gt; <span class="hljs-number">0</span>; i--) {
    factorial *= i
  }
  <span class="hljs-keyword">return</span> factorial
}

findFactorial(<span class="hljs-number">5</span>) <span class="hljs-comment">// 120</span>
</code></pre>
<p>To find the factorial using a loop, you first initialize a variable <code>factorial</code> with a value of <code>1</code>.</p>
<p>Then you initiate the loop with the given number <code>num</code>. The loop will continue running until <code>i &gt; 0</code>.</p>
<p>For each iteration, you multiply the current value of <code>factorial</code> by <code>i</code>. And you decrease the value of <code>i</code> by 1 until <code>i</code> is not greater than zero.</p>
<p>Finally, you return the value of the factorial when the loop finishes running.</p>
<h3 id="heading-how-to-find-the-factorial-with-recursion">How to find the factorial with recursion:</h3>
<p>You can create the same solution with a recursive function.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findFactorial</span>(<span class="hljs-params">num</span>) </span>{
  <span class="hljs-keyword">if</span> (num === <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
  <span class="hljs-keyword">let</span> factorial = num * findFactorial(num - <span class="hljs-number">1</span>)
  <span class="hljs-keyword">return</span> factorial;
}

findFactorial(<span class="hljs-number">5</span>) <span class="hljs-comment">// 120</span>
</code></pre>
<p>First, you need a base condition <code>num === 0</code>.</p>
<p>You also need the recursive call <code>findFactorial(num - 1)</code> to ensure the number keeps reducing at each call when you pass a new parameter of <code>n-1</code>.</p>
<p>Then you multiply the result with the previous number <code>num * findFactorial(num - 1)</code> until the base condition is met.</p>
<h3 id="heading-so-which-is-better-recursion-or-loops">So which is better – recursion or loops?</h3>
<p>So which one is better? There's no right or wrong answer to that. It's up to you to decide. Depending on the problem you're solving, you may choose one over the other.</p>
<p>Optimize for the readability of your code. Sometimes, like in the factorial example, recursion leads to shorter and more readable code.</p>
<p>But recursive functions are not always intuitive. If that's the case, you should stick to loops.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you've learned what recursion is and how to create recursive functions in JavaScript.</p>
<p>Reading and writing recursive functions might be confusing at first. But remember, what makes recursive functions different from regular functions are the <strong>base condition</strong> and the <strong>recursive call</strong>.</p>
<p>Thanks for reading. And happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
