<?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[ Front-end Development - 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[ Front-end Development - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 12 May 2026 20:31:45 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/front-end-development/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ From broke musician to working dev. How college drop-out Ryan Furrer taught himself to code [Podcast #166] ]]>
                </title>
                <description>
                    <![CDATA[ On this week's episode of the podcast, I interview Ryan Furrer. He's a Front End Engineer working on tools that help companies monitor their buildings for energy usage, water leaks, and other environmental factors. Ryan dropped out of college and wor... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/from-broke-musician-to-working-dev-ryan-furrer-podcast-166/</link>
                <guid isPermaLink="false">67e6f817cd414b8fc3de97c7</guid>
                
                    <category>
                        <![CDATA[ learn to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ podcast ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Quincy Larson ]]>
                </dc:creator>
                <pubDate>Fri, 28 Mar 2025 19:27:19 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1743210493481/822f4059-5ddc-4df6-b11b-814e747544c6.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>On this week's episode of the podcast, I interview Ryan Furrer. He's a Front End Engineer working on tools that help companies monitor their buildings for energy usage, water leaks, and other environmental factors.</p>
<p>Ryan dropped out of college and worked as a musician and violin instructor. He spent 5 years teaching himself how to program before getting freelance gigs, and ultimately landing developer jobs.</p>
<p>We talk about:</p>
<ul>
<li><p>Life as a broke musician</p>
</li>
<li><p>Teaching yourself to code while working full-time</p>
</li>
<li><p>How Ryan had to move back in with his parents after a divorce</p>
</li>
<li><p>His 5-year journey to his first developer job</p>
</li>
</ul>
<p>Also, I want to thank the 11,384 kind people who support our charity each month, and who make this podcast possible. You can join them and support our mission at: <a target="_blank" href="https://www.freecodecamp.org/donate">https://www.freecodecamp.org/donate</a></p>
<p>You can watch the interview on YouTube:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/PiWejwwj7Nk" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p> </p>
<p>Or you can listen to the podcast in Apple Podcasts, Spotify, or your favorite podcast app. Be sure to follow the freeCodeCamp Podcast there so you'll get new episodes each Friday.</p>
<p>Links we talk about during our conversation:</p>
<p>Ryan's podcast, Web Dev Dialogues: <a target="_blank" href="https://www.webdevdialogues.com/episodes">https://www.webdevdialogues.com/episodes</a></p>
<p>Ryan's website: <a target="_blank" href="https://www.ryanfurrer.com">https://www.ryanfurrer.com</a></p>
<p>A freeCodeCamp course on the Astro front end development framework taught by freeCodeCamp podcast guest James Q Quick: <a target="_blank" href="https://www.freecodecamp.org/news/learn-the-astro-web-framework/">https://www.freecodecamp.org/news/learn-the-astro-web-framework/</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Tutorial – How to Set Up a Front End Development Project ]]>
                </title>
                <description>
                    <![CDATA[ Let’s say you plan to build a website. Before you start, you want to set up a few tools to make your life easier. But which tools should you have? The JavaScript ecosystem is changing so fast that it can be overwhelming to pick the best tools to use.... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-set-up-a-front-end-development-project/</link>
                <guid isPermaLink="false">66c4c80d6e4b60b5b844529e</guid>
                
                    <category>
                        <![CDATA[ eslint ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Prettier ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Hunor Márton Borbély ]]>
                </dc:creator>
                <pubDate>Wed, 12 Feb 2025 21:44:03 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1739318785959/23632d35-1d5a-4797-8c7d-fbad6c80a879.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Let’s say you plan to build a website. Before you start, you want to set up a few tools to make your life easier. But which tools should you have?</p>
<p>The JavaScript ecosystem is changing so fast that it can be overwhelming to pick the best tools to use. To solve this problem, in this article, I’m going to walk you through how to set up a front-end project from scratch.</p>
<p>We'll cover things like must-have editor extensions, adding JavaScript libraries to your project, why you'll use Node.js even if you want to do front-end development, and setting up an application bundler that will generate a live preview as you code in your browser.</p>
<p>You can also <a target="_blank" href="https://www.youtube.com/watch?v=BiBjuphZQxA">watch this article as a video</a> on YouTube. Let's dive in.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-how-to-choose-a-code-editor">How to Choose a Code Editor</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-auto-format-your-code-in-vs-code">How to Auto-format Your Code in VS Code</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-do-you-need-node-for-a-front-end-project">Why Do You Need Node for a Front-End Project?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-run-your-project">How to Run Your Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-add-libraries-to-your-javascript-project">How to Add Libraries to Your JavaScript Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-get-coding-tips-while-you-code">How to Get Coding Tips While You Code</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-initialize-a-project-with-vite">Initialize a Project with Vite</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ol>
<h2 id="heading-how-to-choose-a-code-editor"><strong>How to Choose a Code Editor</strong></h2>
<p>Let’s start with the foundations. As a web developer, you mostly edit text, so you need a good editor. So which one should you use?</p>
<p>Picking an editor is highly based on personal preference, as most editors have very similar features.</p>
<p>If you don’t have a personal preference, I highly recommend <a target="_blank" href="https://vscode.dev/">VS Code</a>. Lately, it has become the de facto standard editor for web development.</p>
<p><a target="_blank" href="https://survey.stackoverflow.co/2024/technology#1-integrated-development-environment"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738945424232/9f41d802-e672-4cd7-ada3-5e8d54000446.png" alt="VS Code is by far the most used editor" class="image--center mx-auto" width="3840" height="2160" loading="lazy"></a></p>
<p>One of the greatest features of all the mainstream editors is that you can add extensions to them. Let’s walk through two extensions that are must-haves.</p>
<h2 id="heading-how-to-auto-format-your-code-in-vs-code"><strong>How to Auto-format Your Code in VS Code</strong></h2>
<p>Prettier is an extension that makes your code more readable and more consistent.</p>
<p>Let’s say you copy-pasted some code, and it’s hard to read. The tabulation is off, a line is too long, and so on. Then you just save the file, and magically, everything looks as it should be.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738948709710/c64a427d-b868-4704-87db-338ebf079c67.png" alt="Prettier formats the code based on best practices" class="image--center mx-auto" width="2280" height="1280" loading="lazy"></p>
<p>This is what Prettier does. It formats the code based on best practices. It doesn't just fix tabulation and wrap the lines. It also adds parentheses to improve code readability, makes sure you are consistent with quotation marks, and many more.</p>
<p>To make it work in VS Code, we must first install the Prettier extension. To do so, go to the extensions panel in VS Code, search for Prettier, and then install it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738955063143/7e8378e5-cf70-4527-9951-b822a745f4bf.png" alt="To install Prettier, go to the Extensions panel, search for Prettier, and install it" class="image--center mx-auto" width="2260" height="1280" loading="lazy"></p>
<p>Installing this extension doesn't format your files automatically on save by default. The default behavior is that once you install this extension, you can right-click within a file and select <strong>Format Document</strong>. You can also select part of a file and choose <strong>Format Selection</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738955102891/2e55eaa7-ec2a-4aca-ad79-b1df82d31e5c.png" alt="Right-click within a file and select Format Document to format it" class="image--center mx-auto" width="2260" height="1280" loading="lazy"></p>
<p>The first time you do this, you need to select the default formatter. VS Code already has a formatter, but it isn’t as powerful as Prettier. Now that you have two formatters, you have to let VS Code know that you want to use Prettier for formatting in the future.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738955119781/d0ef8bc3-54d0-4428-9731-c8857171f3e7.png" alt="The first time, you need to select the default formatter" class="image--center mx-auto" width="2260" height="1280" loading="lazy"></p>
<p>If you wish to auto-format your files when you save them, you need to change the settings. Go to Settings in your VS Code preferences and search for the <strong>Format on Save</strong> option. By default, this is false, so make sure that you tick this checkbox. With this, Prettier formats your files every time you save them. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738955201893/fd3fbec6-5265-4c9b-adab-c1a9d524a635.png" alt="Set the Format On Save option in Settings" class="image--center mx-auto" width="2260" height="1280" loading="lazy"></p>
<p>Formatting can be controversial, though. I highly recommend the default settings, especially for beginners. But if you prefer a different style, you can customize things.</p>
<p>You can indicate with comments to <a target="_blank" href="https://prettier.io/docs/en/ignore.html">ignore specific lines</a> and create a config file to list your preferences.</p>
<p>In the root folder of your project, you can create a file called <strong>.prettierrc</strong> and add a few options. A typical option could be if you prefer single quotes instead of double quotes in your files. Or if you don't want to have semi-colons at the end of your lines.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738955259640/d430386f-de2a-49f3-b252-aee4a9bc1089.png" alt="Adding a custom Prettier configuration" class="image--center mx-auto" width="2260" height="1280" loading="lazy"></p>
<p>With this configuration, you will have a different format once you save your files.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"singleQuote"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">"semi"</span>: <span class="hljs-literal">false</span>
}
</code></pre>
<p>There are many more options, of course. If you want to dig deeper, check out <a target="_blank" href="https://prettier.io/docs/en/configuration.html">Prettier's documentation</a><a target="_blank" href="https://prettier.io/docs/en/configuration.html">.</a></p>
<h2 id="heading-why-do-you-need-node-for-a-front-end-project"><strong>Why Do You Need Node for a Front-End Project?</strong></h2>
<p>Before we get to the second must-have extension, we need to set up a few other things. First, we need to talk about Node.js. What is Node, and why do you need it even if you work as a front-end developer?</p>
<p>Node is often associated with backend development, but that's not its only job. Node is a JavaScript runtime – this means it runs JavaScript files outside of the browser.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738949060189/11f39633-76a1-4c38-92ef-88846ffdeb8f.png" alt="You can run JavaScript as part of a website in your browser" class="image--center mx-auto" width="2200" height="1220" loading="lazy"></p>
<p>There are two ways of running JavaScript code. You can either have it as part of a website and run the entire website in a browser, or run only the Javascript file with a runtime like Node.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738949071655/68552f47-63ba-4cfc-9ba0-abb9218a4857.png" alt="You can run JavaScript on its own with Node" class="image--center mx-auto" width="2200" height="1220" loading="lazy"></p>
<p>In the example below, we have a very simple Javascript file that prints "Hello World" to the console. If we have Node installed, we can go to the terminal, navigate to the folder where this file is, and then run it with Node like this. You can see that the file was executed, and the result is in the console.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738947073105/9b56af05-e925-4cd1-9475-b3e49898dd39.png" alt="Node can run JavaScript files on their own" class="image--center mx-auto" width="1280" height="720" loading="lazy"></p>
<p>That's what Node really is: a tool that runs JavaScript files on their own.</p>
<p>JavaScript mostly behaves the same way in both environments. But there are also differences in what JavaScript can do in a browser vs when it runs with Node.</p>
<p>For instance, when running in the browser, JavaScript can access and modify HTML elements. That's the main point of having JavaScript in the first place.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738949133299/b1c6d0a6-ba11-4659-a51e-b72e4bbfde68.png" alt="In the browser, JavaScript can access and modify your HTML elements" class="image--center mx-auto" width="2200" height="1220" loading="lazy"></p>
<p>In Node, there's no HTML file. JavaScript runs on its own. On the other hand, in Node, JavaScript has access to your file system and can read and write your files.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738949113586/e8702a9c-91bf-4096-8768-cf06e4e41082.png" alt="With Node, JavaScript can access and modify your File system" class="image--center mx-auto" width="2200" height="1220" loading="lazy"></p>
<p>For instance, you can run scripts on your machine to initialize a project. We are going to do that. You can run checks on your files and automatically correct the mistakes. Or you can run your test files.</p>
<p>In short, Node lets you run some tools that make your life much easier as a developer.</p>
<p>To install Node, go to <a target="_blank" href="http://nodejs.org">nodejs.org</a> and install it. If you are unsure if you already have Node, you can also go to your terminal and run <strong>node -v</strong> to check. If you get a version number, you have Node.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738949153110/c9e63db3-d52b-4122-a31c-6b871ed2e4b5.png" alt="The website of Node.js" class="image--center mx-auto" width="2200" height="1220" loading="lazy"></p>
<p>So, why do people associate Node primarily with backend development? If the backend code is in JavaScript, the servers must run it somehow without a browser. So yes, if you are a backend developer using JavaScript, then you're most probably going to use Node. But Node is much more than that.</p>
<h2 id="heading-how-to-run-your-project"><strong>How to Run Your Project</strong></h2>
<p>Now that we have Node, we can use a live server to see our site live in the browser as we develop it. Without this, you need to manually refresh the browser window every time you make a change.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738949223269/97bc1d15-4ab6-4204-88d6-257fa471f95d.png" alt="A bundler creates a package that you can run in the browser" class="image--center mx-auto" width="2248" height="1220" loading="lazy"></p>
<p>These tools are called bundlers because they take all your files and turn them into a neat package you can run in the browser. So why do you need them?</p>
<ul>
<li><p>They update your site live in the browser with hot reloading. When you save a file, you immediately see the result in your browser.</p>
</li>
<li><p>As web development tools have evolved, the browser won't understand your files when you use anything more advanced. For instance, are you using React? Then, you're using the JSX syntax – the one that looks like HTML. The JSX syntax is not part of JavaScript. You need a tool to convert it into plain JavaScript. Otherwise, it won't run in your browser. Or are you using TypeScript? You also need to turn that into JavaScript. Or, if you're using SCSS or any other CSS dialect, you need to convert it to plain CSS.</p>
</li>
<li><p>If you import libraries using the JavaScript module system, you need a live server to avoid CORS issues in your browser.</p>
</li>
</ul>
<p>This is what bundlers do. They make sure that you can use modern-day tooling while you're developing your application, and they can also create a final production build that you can publish on the internet.</p>
<p>How do you pick a bundler? There are several options, and essentially, they all do the same thing. The difference between them is in their performance, configuration options, and ease of use.</p>
<p>The most used bundler is still <a target="_blank" href="https://webpack.js.org/">webpack</a>, one of the earliest bundlers in the field. But the one that seems to have taken over the throne and gained more and more popularity is <a target="_blank" href="https://vite.dev/">Vite</a>. Here's a chart from the latest edition of the State of JavaScript survey.</p>
<p><a target="_blank" href="https://2024.stateofjs.com/en-US/libraries/#all_tools_experience"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738947476843/195adbd5-5aba-427e-9b00-c507542235d2.png" alt="The sentiment towards WebPack and Vite" class="image--center mx-auto" width="1540" height="900" loading="lazy"></a></p>
<p>This chart shows that while most developers have used Webpack, they don’t necessarily love it. At the same time, Vite's popularity is rising while still maintaining a positive sentiment.</p>
<p>If you haven't checked out the <a target="_blank" href="https://stateofjs.com/en-US">State of JavaScript</a> survey before, I highly recommend going through it. It gives you an excellent overview of the latest trends with JavaScript. You can learn which tools and libraries people love to use and which they will abandon soon. If you feel overwhelmed by all the changes in the JavaScript ecosystem, the results of this survey can be a great guide.</p>
<p>Once we have a folder for our project, let's navigate to it using our terminal. The easiest way to do this is to open the folder in VS Code and then use the built-in terminal. VS Code will open the terminal with the correct folder.</p>
<p>Then, you can run the project in the terminal with the following command. npx is a command line tool that comes with Node. This is one of the reasons we installed Node: to be able to run commands like this.</p>
<pre><code class="lang-bash">npx vite
</code></pre>
<p>The first time you run this script, it will ask you to install Vite. Say yes. Then, it will show you the URL of a local server, which you can open in a browser to view your project.</p>
<pre><code class="lang-bash">  VITE v6.1.0  ready <span class="hljs-keyword">in</span> 162 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h + enter to show <span class="hljs-built_in">help</span>
</code></pre>
<p>Now, if you update a file and save the changes, the new version appears in the browser immediately. It generates a live preview of your site until you stop the script or close the terminal. You can keep it running while you're developing your site.</p>
<p>Once you have finished, you can press <strong>Ctrl+C</strong> to stop the script. If it gets desynchronized or you break it with an error, restart it by pressing <strong>Ctrl+C</strong> to stop it and rerunning the same script. So that's how you run a project with Vite.</p>
<h2 id="heading-how-to-add-libraries-to-your-javascript-project"><strong>How to Add Libraries to Your JavaScript Project</strong></h2>
<p>Now that we have Node, we can also use npm or Note Package Manager to add libraries to our project. npm is another tool included with Node. So how does it work?</p>
<p>First, I will walk you through setting things up step by step the manual way so it's clear how the different parts come together. Then, I will show you how to automate most of these steps.</p>
<p>Navigate to your current folder in the terminal and run the following command to initialize the project. This command initializes a package.json file with some metadata.</p>
<pre><code class="lang-bash">npm init --yes
</code></pre>
<p>At this point, this file is not very interesting. It contains the project name, description, version number, and so on. You can change these values.</p>
<p>Now, we can add libraries to our package with the npm install command. In a <a target="_blank" href="https://www.freecodecamp.org/news/render-3d-objects-in-browser-drawing-a-box-with-threejs/">previous article</a>, we used Three.js to render 3D boxes in the browser.</p>
<p>So, as an example, let's install <a target="_blank" href="https://threejs.org/">Three.js</a>. Go to your terminal again, make sure you are in the correct folder, and run the following command:</p>
<pre><code class="lang-bash">npm install three
</code></pre>
<p>This command will install Three.js. But how do you know that the keyword is three here, not Three.js?</p>
<p>When you don’t know the package name, you can just google npm and the name of the library you need. Or, if you don't even know the library name, you can also just search for an npm 3D library and see what Google comes up with.</p>
<p>We can go through each package one by one and pick one based on their capabilities and other info. These packages mostly come with descriptions and quick examples to give you an idea of what the library can do for you.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738949563130/ce677d97-20c4-48ed-a168-b99eb01c84d4.png" alt="How to pick a library to use" class="image--center mx-auto" width="2260" height="1260" loading="lazy"></p>
<p>Another indicator you might want to look for is the weekly downloads and the date of the last update to ensure you select an actively maintained library that people still use.</p>
<p>Once you find the package you are looking for, you can see the command to install it at the top right corner: <code>npm i three</code>. The <code>i</code> here is just shorthand for install. Another way to learn how to install Three.js is to go to its official documentation and check the <a target="_blank" href="https://threejs.org/docs/index.html#manual/en/introduction/Installation">installation guide</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738952468171/7a54e0bb-d88d-428b-911c-cf7a71676562.png" alt="The package.json file after initializing the project and installing Three.js" class="image--center mx-auto" width="2260" height="1260" loading="lazy"></p>
<p>When we install a package, three things happen:</p>
<ul>
<li><p>It adds the latest version of Three.js in our package.json file as a project dependency.</p>
</li>
<li><p>It also creates a package-lock file, which NPM uses to keep track of the dependencies. You should never edit the dependency section of your package.json file or the package-lock file manually. Instead, you should always use commands like npm install and uninstall to add, remove, or update packages.</p>
</li>
<li><p>Finally, the node_modules folder gets created. This folder contains the source code of Three.js. When we import Three.js in our project, it looks for it in this folder. The content of this folder is also something that you should never change. You can look into it if you're interested in the source code of the library that you're using, but you shouldn't change it.</p>
</li>
</ul>
<p>If something goes wrong and you have an error with your dependencies that you can't figure out, then you can always safely delete the node_modules folder and the package-lock file and reinstall your dependencies based on the package.json file. This is not something that you should do, but you can always go back to having a clean slate.</p>
<p>Now that we have installed Three.js, we can create a simple website that displays a 3D box. It's a simple HTML file and a JavaScript file with the code for the 3D box. The key here is that we import Three.js with the import statement in the JavaScript file. This import will use the package that we just installed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738952825715/9828ea05-e75a-4fdf-b1a3-39bd3aa8e380.png" alt="Using Three.js in a sample project" class="image--center mx-auto" width="2546" height="1444" loading="lazy"></p>
<p>Then, we can run the project with Vite. Using imports means that we use the module system now. Running a project with the module syntax can be a bit tricky, as the browser gives you CORS errors by default. However, as we are using Vite to run our project, it works seamlessly without any questions. That’s one of the reasons we use Vite.</p>
<p>If you want to learn more about building 3D games with Three.js, check out my <a target="_blank" href="https://www.freecodecamp.org/news/three-js-tutorial/">earlier article</a> on building a minimalistic car in the browser.</p>
<h2 id="heading-how-to-get-coding-tips-while-you-code"><strong>How to Get Coding Tips While You Code</strong></h2>
<p>The second must-have editor extension is ESLint. While Prettier formatted the code, ESLint gives you coding tips.</p>
<p>It helps you catch basic mistakes and avoid patterns that can cause bugs or be misleading when you try to understand the code.</p>
<p>Here’s a simple example where you declare a variable, but then you have a typo, and you try to use another variable that doesn't exist. ESLint will highlight this for you. It will give you an error both at the variable declaration, saying that you created a variable you don't use, and add the usage, saying that you're trying to use a variable that is not declared. With ESLint, it's easy to spot that you made a typo.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738953388793/c081f406-f964-4c4c-95ef-83cdc8e403df.png" alt="c081f406-f964-4c4c-95ef-83cdc8e403df" class="image--center mx-auto" width="1928" height="1244" loading="lazy"></p>
<p>ESLint, of course, is much more complex than just being able to catch simple errors. There are also less obvious use cases where you might not understand why ESLint is complaining. Then, you can always click the link in the error popup for more details explaining why this pattern is harmful and what you can do to avoid it.</p>
<p>So how can we use ESLint in our projects? This time, we need to have an extension and a configuration. First, as we did with Prettier, we must install the ESLint extension. Go to your extensions, search for ESLint, and install it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738953594259/a6f02e96-069d-4463-8322-86a23c523df3.png" alt="To install ESLint go to the Extensions panel, search for ESLint, and install it" class="image--center mx-auto" width="2260" height="1280" loading="lazy"></p>
<p>We also need to set up ESLint for our project. Before we do that, we need to make sure that the project already has a package.json file. If you don't already have a package.json file, we first have to run <code>npm init --yes</code> to initialize the project. Then, we can generate an ESLint config with the following command:</p>
<pre><code class="lang-bash">npm init @eslint/config@latest
</code></pre>
<p>This script will ask you a few questions. Based on your answers, it will customize the configuration and the rules to check. For most cases, you can use the default option.</p>
<ul>
<li><p>The first time, it will ask for permission to install ESLint. Say yes.</p>
</li>
<li><p>Then, it will ask you whether to use ESLint only for syntax checks or to find problems as well. Choose the second option to get the most help from ESLint.</p>
</li>
<li><p>Then select that you’ll use it with JavaScript modules. Modern web development projects use the JavaScript module system. We use JavaScript modules if we have imports and exports in our code.</p>
</li>
<li><p>Then, it will ask what framework we are using. If we select a framework, it will add framework-specific rules to our project. For instance, using it with React will force us to define the prop types. If we don't use a front-end framework, just vanilla JavaScript, then select "None of these".</p>
</li>
<li><p>Then, it will ask if the project is using TypeScript. Choose based on your preference.</p>
</li>
<li><p>It asks where you run the code. As we have a front-end project, select "Browser".</p>
</li>
<li><p>Then, it will ask if you want to install the additional dependencies that are required for the rules based on your selections. Select yes.</p>
</li>
<li><p>It will also ask what package manager we’re using. We haven't talked a lot about this, but there are multiple package managers that we can use. Select the default: npm.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738953735596/a69f62ac-b5b4-459e-8e78-6956442adfe4.png" alt="Installing ESLint" class="image--center mx-auto" width="2640" height="1624" loading="lazy"></p>
<p>These were a lot of questions. Let's see what happened after we ran this command.</p>
<p>After this step, we have ESLint and some other dependencies based on the answers in the package.json file as development dependencies. Development dependency means that ESLint won't be part of your website's final code, but we need it during development.</p>
<p>ESLint also became part of our node_modules folder, and there are many more packages here now. This is because a dependency can have other dependencies, and the dependencies of the dependencies will also be part of the node_modules folder.</p>
<p>ESLint also created a config file that sets up the rules based on your answers. We will see how to customize the rules.</p>
<p>Now that ESLint is working, you should also see errors in the code once something is off. If you go to your JavaScript file and try to use an undeclared variable, ESLint will highlight the issue.</p>
<p>ESLint is also highly customizable. For instance, we might not want to mark an unused variable as an error. First, we go to the error popup and select the identifier of this type of error. Then, we go to the ESLint config and override this error as follows. Here, we can reduce the severity to a warning or completely turn off this rule.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738953834462/387e36f3-81ee-461c-ae02-3ca614c7b765.png" alt="Turning off ESLint rules in the config" class="image--center mx-auto" width="2640" height="1624" loading="lazy"></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> globals <span class="hljs-keyword">from</span> <span class="hljs-string">"globals"</span>;
<span class="hljs-keyword">import</span> pluginJs <span class="hljs-keyword">from</span> <span class="hljs-string">"@eslint/js"</span>;


<span class="hljs-comment">/** @type {import('eslint').Linter.Config[]} */</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> [
  {<span class="hljs-attr">languageOptions</span>: { <span class="hljs-attr">globals</span>: globals.browser }},
  pluginJs.configs.recommended,
  {
    <span class="hljs-attr">rules</span>: {
      <span class="hljs-string">"no-unused-vars"</span>: <span class="hljs-string">"off"</span>, <span class="hljs-comment">// Turn off the No Unused Variables rule</span>
    }
  }
];
</code></pre>
<p>But if you're a beginner, I recommend following the rules that ESLint has by default. Sometimes, it might be annoying to fix all the seemingly harmless issues, but all these rules are based on industry best practices, so it's good to follow them. For more details, check out <a target="_blank" href="https://eslint.org/docs/latest/use/configure/rules">ESLint's documentation</a>.</p>
<h2 id="heading-initialize-a-project-with-vite">Initialize a Project with Vite</h2>
<p>We walked through the step-by-step process of setting up a project. We used <strong>npm init</strong> to initialize the project, manually set up ESLint, and ran our project with Vite. Vite can also initialize the project with a sample application and all the necessary files, which is especially handy when we set up a React project. </p>
<p>Let's see how to set up a vanilla JavaScript and a React project. Let's navigate to a folder in the terminal that will contain our project. We don't need to create a project folder this time because the script will make it for us. Then, run the following command to initialize a project:</p>
<pre><code class="lang-bash">npm create vite@latest
</code></pre>
<p>This command asks you a few questions.</p>
<ul>
<li><p>First, it will ask you for the project name, which will also be the name of the folder created as the project root.</p>
</li>
<li><p>Then, it will ask what framework you use. If you don't use any framework and want plain old JavaScript, choose "Vanilla." If you use React, choose React.</p>
</li>
<li><p>Then, it will ask you if you want to use TypeScript or JavaScript. Here, the default is TypeScript. If you're a beginner in web development, choose JavaScript. If you are more confident with your skills, then go with TypeScript. TypeScript is more complicated, but it has become the industry standard in web development, and most jobs require you to know it. As a beginner, you can go with JavaScript.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738953943915/884e22b0-f096-4338-a392-588b032834f4.png" alt="Creating a project with Vite" class="image--center mx-auto" width="1364" height="966" loading="lazy"></p>
<p>Now, we can navigate to the new folder created and check out what we have here. If you choose a vanilla JavaScript project, you can see it generated a simple application with HTML, CSS, and some JavaScript files. You can change or even delete these. You'll need an HTML file as an entry point, but you can replace the rest.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738954107608/0234f409-6f78-4039-b5d1-133c8cd09530.png" alt="Vite can create a sample application with an HTML, CSS, and JavaScript file" class="image--center mx-auto" width="2624" height="1822" loading="lazy"></p>
<p>We can run this project with <strong>npx vite</strong> as we did before, but there’s a better way. For a real project, we want to add Vite as a development dependency to ensure consistency with the version we are using.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"my-project"</span>,
  <span class="hljs-attr">"private"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"0.0.0"</span>,
  <span class="hljs-attr">"type"</span>: <span class="hljs-string">"module"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"vite"</span>,
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"vite build"</span>,
    <span class="hljs-attr">"preview"</span>: <span class="hljs-string">"vite preview"</span>
  },
  <span class="hljs-attr">"devDependencies"</span>: {
    <span class="hljs-attr">"vite"</span>: <span class="hljs-string">"^6.1.0"</span>
  }
}
</code></pre>
<p>The package.json file shows that Vite has been added as a development dependency. To use this hardcoded version, we first have to install it via <code>npm install</code>. This command installs all the dependencies listed in the package.json file.</p>
<pre><code class="lang-bash">npm install
</code></pre>
<p>This package.json file now also has a scripts section. This section can define scripts to run your app locally, create a production build, or test your application. You can run them with <strong>npm run</strong>. So, for instance, to run the application, you can open the terminal with the correct folder and run the following command.</p>
<pre><code class="lang-bash">npm run dev
</code></pre>
<p>This runs the script labeled as “dev” in the scripts section, which will run the Vite version we just installed with <strong>npm install</strong>.</p>
<p>Vite does not install ESLint when you create a vanilla project, but you can always install it manually, as we did before with <strong>npm init @eslint/config@latest</strong>.</p>
<p>If you choose React as a framework when we initialize the project, we will have a couple more files. For instance, we have an ESLint config with the recommended React settings. We also have a Vite config that enables us to use React and a sample application that we can run.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738954174340/26c5a9a5-b983-4ed7-8e43-fbab4400e08b.png" alt="Vite can also create a React project for you" class="image--center mx-auto" width="2624" height="1822" loading="lazy"></p>
<p>To run this app, we need to install the dependencies. So, let's go to the terminal and run <code>npm install</code>. This will install all the dependencies, including React. Then, we can run this app with <code>npm run dev</code>, and we will have a working React application.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we set up and run a front-end project with Vite. We also covered how to find and add dependencies, how to have consistent and automatic formatting with Prettier, and how to avoid bugs with ESLint.</p>
<p>What happens once you finish developing your app? How do you upload it to the web and share it with the world? That's the topic of a future article.</p>
<h3 id="heading-subscribe-for-more-tutorials-on-web-development"><strong>Subscribe for more tutorials on Web Development:</strong></h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/BiBjuphZQxA" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Essential JavaScript Concepts to Know Before Learning React – With Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ You may have seen the shiny technologies like React, Vue, and Angular that promise to revolutionize your front-end development. It's tempting to dive headfirst into these frameworks, eager to build stunning user interfaces. But hold on! Before you em... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/essential-javascript-concepts-before-react/</link>
                <guid isPermaLink="false">66dfae7a77d188f61ea4b29e</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Akande Olalekan Toheeb ]]>
                </dc:creator>
                <pubDate>Tue, 10 Sep 2024 02:27:06 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723690396380/c9b8a333-4cbe-42c4-bfab-da39f34d3fd4.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>You may have seen the shiny technologies like React, Vue, and Angular that promise to revolutionize your front-end development. It's tempting to dive headfirst into these frameworks, eager to build stunning user interfaces. But hold on! Before you embark on this exciting journey, consider this:</p>
<p>A strong foundation in JavaScript is the cornerstone of any successful front-end project.</p>
<p>In this article, I aim to provide you with the fundamental JavaScript knowledge required to succeed in React and other front-end frameworks. By the end of this piece, you will better understand key JavaScript concepts—such as destructuring, short-circuiting, and fetching data, among others—and how to use them effectively.</p>
<p>Are you ready to improve your JavaScript skills? Let's dive right in 😉</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-use-template-literals">How to Use Template Literals</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-destructure-objects-and-arrays">How to Destructure Objects and Arrays</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-ternaries-instead-of-ifelse-statements">Ternaries Instead of if/else Statements</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-arrow-functions">How to Use Arrow Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-short-circuiting-with-and-or-nullish">Short-Circuiting with &amp;&amp; , ||, and ??</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-array-methods">How to Use Array Methods</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-fetch-data">How to Fetch Data</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-you-can-start-react-now">You Can Start React Now</a></p>
</li>
</ul>
<h2 id="heading-how-to-use-template-literals">How to Use Template Literals</h2>
<p>Ever felt like string construction in JavaScript was a bit of a chore? Imagine putting together a birthday message and constantly adding quotes and plus(+) signs to include the name.</p>
<p>Before ES6, that was the reality with string concatenation. Let's say you wanted to greet a user:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name = prompt(<span class="hljs-string">"What is your name?"</span>);
<span class="hljs-keyword">let</span> greeting = alert(<span class="hljs-string">"Hello, "</span> + name + “!<span class="hljs-string">");</span>
</code></pre>
<p>This code works, but it can get messy when dealing with multiple variables or dynamic content.</p>
<p>Then came template literals! Introduced in ES6, they offer a more elegant way to create strings using backticks (``) instead of quotes. Here's how to rewrite the greeting with template literals:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name = prompt(<span class="hljs-string">"What is your name?"</span>);
<span class="hljs-keyword">let</span> greetings = alert(<span class="hljs-string">`Hello <span class="hljs-subst">${name}</span>`</span>);
</code></pre>
<p>See the difference? The <code>${name}</code> part tells JavaScript to insert the value of the <code>name</code> variable directly into the string.</p>
<p>Template literals give you the power to perform string interpolation easily in the JavaScript ecosystem, no more clunky concatenation 😉!</p>
<p><strong>The Benefits of Template Literals include:</strong></p>
<ul>
<li><p><strong>Readability:</strong> Your code becomes clearer and easier to understand.</p>
</li>
<li><p><strong>Maintainability:</strong> Updates are simpler since changes are localized within the template literal.</p>
</li>
<li><p><strong>Expressiveness:</strong> You can create multi-line strings and even use functions within them!</p>
</li>
</ul>
<p>Not only do template literals make your life easier, but they're also instrumental in building dynamic components with React. You can, for instance, create dynamic list items, conditionally render components, or format output based on data.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> name = <span class="hljs-string">'Alice'</span>;
<span class="hljs-keyword">const</span> greeting = <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>! How are you today?`</span>;
<span class="hljs-built_in">console</span>.log(greeting); <span class="hljs-comment">// Output: Hello, Alice! How are you today?</span>

<span class="hljs-keyword">const</span> items = [<span class="hljs-string">'apple'</span>, <span class="hljs-string">'banana'</span>, <span class="hljs-string">'orange'</span>];
<span class="hljs-keyword">const</span> listItems = items.map(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> <span class="hljs-string">`&lt;li&gt;<span class="hljs-subst">${item}</span>&lt;/li&gt;`</span>).join(<span class="hljs-string">''</span>);
<span class="hljs-keyword">const</span> list = <span class="hljs-string">`&lt;ul&gt;<span class="hljs-subst">${listItems}</span>&lt;/ul&gt;`</span>;
</code></pre>
<p>As you can see, template literals make building dynamic and readable string-based components in React easier.</p>
<h2 id="heading-how-to-destructure-objects-and-arrays">How to Destructure Objects and Arrays</h2>
<p>Destructuring in JavaScript allows you to extract values from arrays or properties from objects into separate variables, providing a concise and efficient way to handle data structures.</p>
<h3 id="heading-how-to-destructure-objects-in-javascript">How to Destructure Objects in JavaScript</h3>
<p>To destructure an object, use curly braces <code>{ }</code> and specify the property names you want to extract. Let's consider an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {
    <span class="hljs-attr">firstName</span>: <span class="hljs-string">'Olalekan'</span>,
    <span class="hljs-attr">lastName</span>: ‘Akande<span class="hljs-string">',
    middleName: ‘Toheeb’,
    age: 30 
};

const {  lastName , firstName} = person;
console.log(firstName, lastName); // Output: Akande Olalekan</span>
</code></pre>
<p>In this code, we destructured the <code>person</code> object and extracted the <code>firstName</code> and <code>lastName</code> properties into separate variables.</p>
<h4 id="heading-nested-destructuring">Nested Destructuring:</h4>
<p>You can also destructure nested objects:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> address = {
    <span class="hljs-attr">street</span>: <span class="hljs-string">'123 Main St’,
    city: '</span>Ilorin<span class="hljs-string">'
    state: {
        name: '</span>Kwara<span class="hljs-string">',
        abbreviation: '</span>KW<span class="hljs-string">'
    }
};



const { street, city, state: { name } } = address;
console.log(street, city, name); // Output: 123 Main St Ilorin Kwara</span>
</code></pre>
<p><strong>Default Values:</strong></p>
<p>You can provide default values for properties if they are undefined:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> config = {
    <span class="hljs-attr">theme</span>: <span class="hljs-string">'light'</span>
};

<span class="hljs-keyword">const</span> { theme = <span class="hljs-string">'dark'</span> } = config;
<span class="hljs-built_in">console</span>.log(theme); <span class="hljs-comment">// Output: light</span>
</code></pre>
<h4 id="heading-renaming-property">Renaming Property</h4>
<p>Occasionally, you might need to change an existing property name to a different one for better readability or consistency within your project. Destructuring offers a convenient way to achieve this.</p>
<p>Using a different property name within the destructuring assignment can effectively rename the property as you extract it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {
    <span class="hljs-attr">firstName</span>: <span class="hljs-string">'Olalekan'</span>,
    <span class="hljs-attr">lastName</span>: ‘Akande<span class="hljs-string">',
    middleName: ‘Toheeb’,
    age: 30 
};

const { firstName: givenName, lastName: familyName } = person;
console.log(familyName, givenName); // Output: Akande Olalekan</span>
</code></pre>
<p>In this example, <code>firstName</code> is renamed to <code>givenName</code>, and <code>lastName</code> is renamed <code>familyName</code> during the destructuring process.</p>
<p>This renaming technique can improve code clarity and maintainability, especially when dealing with complex objects.</p>
<h3 id="heading-destructuring-arrays">Destructuring Arrays</h3>
<p>To destructure an array, you use square brackets <code>[]</code> and specify the indices of the elements you want to extract:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> [first, second] = numbers;
<span class="hljs-built_in">console</span>.log(first, second, rest); <span class="hljs-comment">// Output: 1 2</span>
</code></pre>
<h3 id="heading-destructuring-in-react">Destructuring in React</h3>
<p>Destructuring is widely used in React components to extract props, state, and context values. It simplifies code and improves readability:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">(<span class="hljs-params">{ name, age }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello, {name}!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>You are {age} years old.<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>
  );
};
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1723980495782/290be34c-171f-4010-b42f-224af48a6cd2.png" alt="destructuring in objects, arrays, rest and spread operators" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h3 id="heading-rest-and-spread-operator">Rest and Spread Operator</h3>
<p>The rest and spread operators are closely related to destructuring.</p>
<h4 id="heading-rest-operator">Rest Operator</h4>
<p>The rest operator (<code>...</code>) collects the remaining elements of an array or object into a new array or object:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> [first, ...rest] = numbers;
<span class="hljs-built_in">console</span>.log(rest); <span class="hljs-comment">// Output: [2, 3, 4, 5]</span>
</code></pre>
<h4 id="heading-spread-operator">Spread Operator</h4>
<p>The spread operator also uses <code>...</code> but is used to expand an iterable into individual elements:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> newArray = [...numbers, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-built_in">console</span>.log(newArray); <span class="hljs-comment">// Output: [1, 2, 3, 4, 5]</span>
</code></pre>
<p>In React, the spread operator is often used to clone arrays or objects, or to pass props to components:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = { <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> };
<span class="hljs-keyword">const</span> newPerson = { ...person, <span class="hljs-attr">city</span>: <span class="hljs-string">'New York'</span> };
<span class="hljs-built_in">console</span>.log(newPerson); <span class="hljs-comment">// Output: { name: 'John', age: 30, city: 'New York' }</span>
</code></pre>
<p>Understanding destructuring and the rest/spread operators can help you write more concise and expressive JavaScript code, especially when working with React.</p>
<h2 id="heading-ternaries-instead-of-ifelse-statements">Ternaries Instead of if/else Statements</h2>
<p>Ternary operators offer a concise and fine alternative to traditional <code>if/else</code> statements in JavaScript. They are particularly useful for conditional expressions that return a value based on a condition.</p>
<p><strong>Why Ternaries Over</strong> <strong>if/else</strong>?</p>
<p>While <code>if/else</code> statements are versatile, they can sometimes lead to verbose code, especially when dealing with simple conditional logic. Ternary operators provide a more compact and readable syntax, making your code easier to understand and maintain.</p>
<p><strong>Syntax and Usage</strong></p>
<p>The syntax for a ternary operator is as follows:</p>
<pre><code class="lang-javascript">condition ? expression1 : expression2
</code></pre>
<p>If the <code>condition</code> is true, <code>expression1</code> is evaluated and returned. Otherwise, <code>expression2</code> is evaluated and returned.</p>
<p><strong>Pure Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age = <span class="hljs-number">19</span>;

<span class="hljs-keyword">const</span> isAdult = age &gt;= <span class="hljs-number">18</span>;
<span class="hljs-keyword">const</span> message = isAdult ? <span class="hljs-string">'You are an adult.'</span> : <span class="hljs-string">'You are a minor.'</span>;
<span class="hljs-built_in">console</span>.log(message);
</code></pre>
<p>The above example will return a message based on the value of the <code>age</code> variable. Can you predict what will be displayed in the console?</p>
<p><strong>Example in React:</strong></p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">(<span class="hljs-params">{ isLoggedIn }</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        {isLoggedIn ? (
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Welcome, user!<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>Please log in.<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>
    );
};
</code></pre>
<p>In this React component, the ternary operator renders different content based on the <code>isLoggedIn</code> prop conditionally.</p>
<p><strong>Benefits of Ternary Operators:</strong></p>
<ul>
<li><p><strong>Concise syntax:</strong> Ternary operators provide a more compact way to express conditional logic.</p>
</li>
<li><p><strong>Readability:</strong> They can improve code readability by making conditional expressions more concise and easier to understand.</p>
</li>
<li><p><strong>Efficiency:</strong> Sometimes, ternary operators are more efficient than <code>if/else</code> statements.</p>
</li>
</ul>
<p>By incorporating ternary operators into your JavaScript code, you can write more elegant and efficient programs.</p>
<h2 id="heading-how-to-use-arrow-functions">How to Use Arrow Functions</h2>
<p>Arrow functions, introduced in ES6, provide a concise syntax for defining functions. They are particularly useful in functional programming paradigms and can significantly improve code readability and maintainability.</p>
<p><strong>What are Arrow Functions?</strong></p>
<p>Arrow functions are a shorthand syntax for declaring functions. They have a simpler structure compared to traditional function declarations or expressions. They are often used for short, inline functions.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myFunction = <span class="hljs-function">(<span class="hljs-params">arg1, arg2</span>) =&gt;</span> {
    <span class="hljs-comment">// Function body</span>
};
</code></pre>
<p><strong>Key Features:</strong></p>
<ul>
<li><p><strong>Implicit</strong> <strong>this</strong> <strong>binding:</strong> <a target="_blank" href="https://www.freecodecamp.org/news/javascript-arrow-functions-in-depth/#heading-arrow-functions-dont-have-this-binding">Arrow functions do not create their own <code>this</code> context</a>. Instead, they inherit the <code>this</code> value from the enclosing scope, which can be helpful in callback functions and event handlers.</p>
</li>
<li><p><strong>Concise syntax:</strong> The arrow function syntax is often shorter and more readable than traditional declarations.</p>
</li>
<li><p><strong>Implicit return:</strong> For single-line arrow functions with a <code>return</code> statement, the <code>return</code> keyword can be omitted.</p>
</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> greet = <span class="hljs-function"><span class="hljs-params">name</span> =&gt;</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
<span class="hljs-built_in">console</span>.log(greet(<span class="hljs-string">'Akande'</span>)); <span class="hljs-comment">// Output: Hello, Akande!</span>
</code></pre>
<h3 id="heading-using-arrow-functions-in-react">Using Arrow Functions in React</h3>
<p>Arrow functions are commonly used in React components for various purposes, including:</p>
<ul>
<li><strong>Event handlers:</strong></li>
</ul>
<pre><code class="lang-javascript">&lt;button onClick={<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">this</span>.handleClick()}&gt;Click me&lt;/button&gt;
</code></pre>
<p><strong>Explanation:</strong> Here, the arrow function is used as the event handler for the <code>onClick</code> event. This ensures that the <code>this</code> context within the handler refers to the component instance, allowing you to access the component's state and methods.</p>
<ul>
<li><strong>Map, filter, and reduce:</strong></li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> doubledNumbers = numbers.map(<span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> number * <span class="hljs-number">2</span>);
</code></pre>
<p><strong>Explanation:</strong> Arrow functions are often used with array methods like map, filter, and reduce to perform transformations on data. In this example, the map method creates a new array where each element is doubled, using an arrow function for the callback.</p>
<p><strong>Props</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> MyComponent = <span class="hljs-function">(<span class="hljs-params">{ name, onButtonClick }</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{onButtonClick}</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
    );
};
</code></pre>
<p><strong>Explanation:</strong> Arrow functions can be used to define props that are functions. In this example, the <code>onButtonClick</code> prop is a function that can be passed to the component. When the button is clicked, the <code>onButtonClick</code> function will be called.</p>
<p>By using arrow functions effectively, you can write more concise, readable, and maintainable React code.</p>
<h2 id="heading-short-circuiting-with-ampamp-and">Short-Circuiting with <code>&amp;&amp;</code> , <code>||</code>, and <code>??</code></h2>
<p>Short-circuiting is a JavaScript evaluation technique that can optimize conditional expressions. It involves stopping the evaluation of a logical expression as soon as the final result is determined.</p>
<p>Short-circuiting in logical operators means that, in certain conditions, the operator will immediately return the first value and not even look at the second value.</p>
<p>We can say that short-circuiting depends on the truthy and falsy values</p>
<p>Falsy values include: 0, empty string (‘’), <code>null</code>, <code>undefinded</code>.</p>
<p>Truty values are basically anything that is not fasly value.</p>
<h3 id="heading-when-do-logical-operators-short-circuit">When do logical operators short-circuit?</h3>
<h4 id="heading-logical-and-ampamp">Logical AND (&amp;&amp;)</h4>
<p>The <code>&amp;&amp;</code> operator short circuit when the left-hand side of the operator (first operand) is false (that is, it immediately returns the first value when it’s any of the falsy values). There is no short-circuit if the first operand is truthy, it will return the right-hand side of the operator(second operand).</p>
<p>This is known as short-circuiting to the left.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> isLoggedIn = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">const</span> greeting = isLoggedIn &amp;&amp; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Welcome, user!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
</code></pre>
<p>In this example, the greeting variable will only be assigned the JSX element if <code>isLoggedIn</code> is true. If <code>isLoggedIn</code> is false, the <code>&amp;&amp;</code> operator will short-circuit, and the JSX element will not be rendered.</p>
<h4 id="heading-logical-or">Logical OR (||)</h4>
<p>The <code>||</code> operator works in the opposite direction as the <code>&amp;&amp;</code> operator. The <code>||</code> operator short circuits when the first operand is true. That is, If the left-hand side of the <code>||</code> operator is true, it immediately returns the second value.</p>
<p>This is known as short-circuiting to the right.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> username = <span class="hljs-string">'Akande'</span>;
<span class="hljs-keyword">const</span> greeting = username || ‘Guest<span class="hljs-string">';</span>
</code></pre>
<p>This code will assign <code>greeting</code> the value of <code>username</code> if it's not any of the falsy values. Otherwise, it will assign the default value of <code>Guest</code>.</p>
<p><strong>Note</strong>: You have to be very careful when using the <code>||</code> operator in cases where you might actually wish to return the 0. .</p>
<p>For example</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> numberOfBooksRead = <span class="hljs-number">0</span>;
<span class="hljs-keyword">const</span> hasRead = numberOfBooksRead || ‘No data’;

<span class="hljs-comment">// hasRead = ‘’No data’</span>
</code></pre>
<p>The above will return <code>No data</code> because the first operand—<code>numberOfBooksRead</code> —is a falsy value. In this kind of situation, it’s better to use the nullish coalescing operator (<code>??</code>)</p>
<h4 id="heading-nullish-coalescing-operator">Nullish Coalescing Operator (??)</h4>
<p>Nullish coalescing operator (??) returns the left-hand side operand if it is not <code>null</code> or <code>undefined</code>. Otherwise, it returns the right-hand side operand.</p>
<p>The above example can now be written as</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> numberOfBooksRead = <span class="hljs-number">0</span>;
<span class="hljs-keyword">const</span> hasRead = numberOfBooksRead ?? ‘No data’;  

<span class="hljs-comment">// hasRead = 0;</span>
</code></pre>
<h3 id="heading-optional-chaining">Optional Chaining (?.)</h3>
<p>The optional chaining operator (<code>?.</code>) provides a safer way—in React—to access nested properties without throwing an error if a property is <code>undefined</code> or <code>null</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = { <span class="hljs-attr">address</span>: { <span class="hljs-attr">street</span>: <span class="hljs-string">'123 Main St'</span> } };
<span class="hljs-keyword">const</span> street = user?.address?.street;
</code></pre>
<p>In this example, <code>street</code> will be assigned the value of <code>123 Main St</code> if both <code>user</code> and <code>user.address</code> exist. If either is <code>null</code> or <code>undefined</code>, <code>street</code> will be <code>undefined</code> without throwing an error.</p>
<p>Effective usage of <a target="_blank" href="https://www.freecodecamp.org/news/short-circuiting-in-javascript/">short-circuiting</a> and <a target="_blank" href="https://www.freecodecamp.org/news/optional-chaining-javascript/">optional chaining</a> makes you write more concise and robust React components.</p>
<h2 id="heading-how-to-use-array-methods">How to Use Array Methods</h2>
<p>Arrays are fundamental data structures in JavaScript that store collections of elements. They are ordered and can contain elements of different data types.</p>
<h3 id="heading-essential-array-methods">Essential Array Methods</h3>
<ul>
<li><p><strong>map():</strong> Creates a new array by applying a function to each original array element. Use <code>map()</code> to update existing elements.</p>
</li>
<li><p><strong>filter():</strong> Creates a new array containing only elements that pass a test implemented by a provided function. Use <code>filter()</code> to delete elements.</p>
</li>
<li><p><strong>reduce():</strong> Applies a function to an accumulator and each array element to reduce it to a single value.</p>
</li>
<li><p><strong>sort():</strong> Sorts the elements of an array in place.</p>
</li>
</ul>
<h3 id="heading-advanced-array-methods">Advanced Array Methods</h3>
<ul>
<li><p><strong>flatMap():</strong> Flattens an array and applies a mapping function to each element.</p>
</li>
<li><p><strong>reduceRight():</strong> Similar to <code>reduce()</code>, but starts from the end of the array.</p>
</li>
<li><p><strong>find():</strong> Returns the first element in an array that satisfies a test implemented by a provided function.</p>
</li>
</ul>
<h3 id="heading-relating-array-methods-to-react">Relating Array Methods to React</h3>
<p>Array methods are indispensable for working with data in React components. They can transform, filter, and aggregate data to render dynamic UI elements.</p>
<p>Example using <code>map()</code> to update elements:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> items = [<span class="hljs-string">'apple'</span>, <span class="hljs-string">'banana'</span>, <span class="hljs-string">'orange'</span>];
<span class="hljs-keyword">const</span> updatedItems = items.map(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> item === <span class="hljs-string">'apple'</span> ? <span class="hljs-string">'grapefruit'</span> : item);
</code></pre>
<p>In this example, the <code>map()</code> method creates a new array where the element <code>'apple'</code> is replaced with <code>'grapefruit'</code>.</p>
<p>Example using <code>filter()</code> to delete elements:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> evenNumbers = numbers.filter(<span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> number % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>);
</code></pre>
<p>In this example, the <code>filter()</code> method creates a new array containing only the even numbers from the original array.</p>
<p>Example using <code>reduce()</code> to aggregate data:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> sum = numbers.reduce(<span class="hljs-function">(<span class="hljs-params">acc, curr</span>) =&gt;</span> acc + curr, <span class="hljs-number">0</span>);
</code></pre>
<p>In this example, the <code>reduce()</code> method calculates the sum of all elements in the numbers array.</p>
<p>Example using <code>flatMap()</code> to flatten an array:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> nestedArrays = [[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>], [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]];
<span class="hljs-keyword">const</span> flattenedArray = nestedArrays.flatMap(<span class="hljs-function"><span class="hljs-params">array</span> =&gt;</span> array);
</code></pre>
<p>In this example, the <code>flatMap()</code> method flattens the nested arrays into a single array.</p>
<h3 id="heading-chaining-array-methods">Chaining Array Methods</h3>
<p>You can chain multiple array methods together to perform complex transformations on data concisely and efficiently.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> users = [
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'Akande'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'Toheeb'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> },
    { <span class="hljs-attr">name</span>: <span class="hljs-string">'Olalekan'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">35</span> }
];

<span class="hljs-keyword">const</span> adultUsers = users
.filter(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.age &gt;= <span class="hljs-number">18</span>)
.map(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> ({ <span class="hljs-attr">name</span>: user.name, <span class="hljs-attr">age</span>: user.age }));
</code></pre>
<p>In this example, we first filtered the users based on their age and then mapped over the filtered array to create a new array with only the name and age properties.</p>
<p>By mastering <a target="_blank" href="https://www.freecodecamp.org/news/the-javascript-array-handbook/">array methods</a>, you can write more efficient and expressive React components that effectively handle and manipulate data.</p>
<h2 id="heading-how-to-fetch-data">How to Fetch Data</h2>
<p>Data is the lifeblood of web applications, and React is no exception. Fetching data from external sources, such as APIs, is a fundamental task in React development. This data is used to populate components, update the UI, and provide a dynamic user experience.</p>
<h3 id="heading-promises-and-fetch">Promises and Fetch</h3>
<p>Promises represent the eventual completion (or failure) of an asynchronous operation. The <code>fetch()</code> API is a built-in JavaScript function that returns a Promise representing the fetching of a resource.</p>
<p><strong>Example using</strong> <code>fetch()</code>:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://api.example.com/data'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
    .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {
    <span class="hljs-comment">// Handle the data here</span>
    <span class="hljs-built_in">console</span>.log(data);
    })
    .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {
    <span class="hljs-comment">// Handle errors here</span>
    <span class="hljs-built_in">console</span>.error(error);
    };
</code></pre>
<h3 id="heading-asyncawait">Async/Await</h3>
<p>The <code>async/await</code> syntax provides a cleaner way to work with Promises. It allows you to write asynchronous code in a more synchronous-looking style.</p>
<p>Example using <code>async/await</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
        <span class="hljs-built_in">console</span>.log(data);
    } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
    }
}

fetchData();
</code></pre>
<h3 id="heading-fetching-data-in-react-components">Fetching Data in React Components</h3>
<p>In React components, you typically fetch data within lifecycle methods like <code>componentDidMount</code> or <code>useEffect</code>. This ensures that data is fetched after the component is mounted and any initial state is set.</p>
<p>Example:</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">import</span> React, { useEffect, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">const</span> [data, setData] = useState(<span class="hljs-literal">null</span>);

useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {
        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
            <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
            setData(data);
            } <span class="hljs-keyword">catch</span> (error) {
            <span class="hljs-built_in">console</span>.error(error);
            }
        };

    fetchData();
}, []);

    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        {data ? (
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Data: {JSON.stringify(data)}<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>Loading...<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>
    );
}
</code></pre>
<p>In this example, the <code>useEffect</code> hook is used to fetch data when the component mounts. The <code>useState</code> hook is used to manage the loading state and display the fetched data.</p>
<h3 id="heading-error-handling">Error Handling</h3>
<p>It's essential to handle errors that may occur during data fetching. You can use <code>try/catch</code> blocks to catch exceptions and provide appropriate feedback to the user.</p>
<p>By understanding <a target="_blank" href="https://www.freecodecamp.org/news/the-javascript-promises-handbook/"><strong>Promises</strong></a>, <a target="_blank" href="https://www.freecodecamp.org/news/javascript-fetch-api-for-beginners/"><strong>Fetch API</strong></a>, <a target="_blank" href="https://www.freecodecamp.org/news/asynchronous-programming-in-javascript-examples/"><strong>async/await</strong></a>, and <a target="_blank" href="https://www.freecodecamp.org/news/try-catch-in-javascript/"><strong>Error handling</strong></a>, you can effectively fetch and manage data in your React applications.</p>
<h2 id="heading-you-can-start-react-now">You Can Start React Now</h2>
<p>This article explores the essential JavaScript concepts that form the foundation for successful React development.</p>
<p>By mastering template literals, destructuring, ternaries, arrow functions, short-circuiting, array methods, fetch API, and asynchronous/await, you'll be well-equipped to tackle the challenges and opportunities that React presents.</p>
<h3 id="heading-further-learning"><strong>Further Learning</strong></h3>
<p>To deepen your understanding of React, consider checking out the following:</p>
<ul>
<li><p><a target="_blank" href="%5Bhttps://legacy.reactjs.org/docs/getting-started.html%5D(https://legacy.reactjs.org/docs/getting-started.html)**"><strong>Official React Documentation</strong></a></p>
</li>
<li><p><a target="_blank" href="https://create-react-app.dev/"><strong>Create React App</strong></a>: A popular tool for setting up React projects quickly</p>
</li>
<li><p><strong>Online Courses</strong>: Platforms like <a target="_blank" href="https://www.freecodecamp.org/"><strong>freeCodeCamp</strong></a>, <strong>Udemy</strong>, and <strong>Coursera</strong> offer comprehensive React courses.</p>
</li>
<li><p><strong>React Community</strong>: Engage with the React community on forums, social media, and meetups to learn from others and stay updated on the latest trends.</p>
</li>
</ul>
<h3 id="heading-call-to-action">Call to Action</h3>
<p>Now that you have a strong JavaScript foundation, it's time to dive into React and build amazing web applications. Don't be afraid to experiment, make mistakes, and learn from your experiences. The React community is welcoming and supportive, so don't hesitate to ask for help when needed.</p>
<p><strong>Remember:</strong> The journey of mastering React is ongoing. Stay curious, keep learning, and enjoy the process of creating innovative web experiences.</p>
<p>Don't forget to share and recommend this article for anyone who might need it.</p>
<p><img src="https://thumbs2.imgbox.com/ef/4c/4hKjdQ6N_t.jpeg" alt="Thank You Memoji" width="600" height="400" loading="lazy"></p>
<p>Thanks for reading. Let's connect on <a target="_blank" href="https://x.com/devtoheeb">X</a> or <a target="_blank" href="https://www.linkedin.com/in/akande-olalekan-toheeb-2a69a0221">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Design-first vs Logic-first Approach – How Should You Start Your Front-end Projects? ]]>
                </title>
                <description>
                    <![CDATA[ Front-end development is the aspect of web development that involves building user-friendly, dynamic and intuitive interfaces. A front-end developer is primarily concerned about the interface design that the user interacts with and the user’s experie... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/design-first-vs-logic-first-approach/</link>
                <guid isPermaLink="false">66d06c6332b24b6177fc573c</guid>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Timothy Olanrewaju ]]>
                </dc:creator>
                <pubDate>Thu, 29 Aug 2024 12:41:07 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724861983210/118e84bc-0153-4b01-b880-e12fe012b7a5.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Front-end development is the aspect of web development that involves building user-friendly, dynamic and intuitive interfaces. A front-end developer is primarily concerned about the interface design that the user interacts with and the user’s experience while using the application.</p>
<p>When starting a project, every front-end developer faces the dilemma of whether to design the interface first or implement the logical part of the application first. The design entails the visual elements displayed on the web application, while the logic refers to the underlying functionalities within the application that dictate its behavior and interaction with users.</p>
<p>In this article, we'll examine both approaches (including their merits and demerits), their best use cases, and how combining them can help achieve set project goals.</p>
<h2 id="heading-design-first-approach"><strong>Design-first Approach</strong></h2>
<p>The design-first approach prioritizes the user interface and user experience aspects of the application. Here, the development process begins with crafting the visual parts such as the navigation, fonts, images, icons, text and background colors, buttons, cards, forms, pop-ups, and so on.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724860712401/b0948dc5-8d2e-4f79-95a4-3e2657f467bd.jpeg" alt="computer screen showing visual layout" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The user experience is also paramount in this approach considering the ease-of-use and accessibility of the application. The main concern of the developer using this approach is how the interface looks to the users. It involves an extensive design of how the elements are laid out and positioned, suitable color scheming and adherence to user interface design principles.</p>
<h3 id="heading-advantages-of-the-design-first-approach"><strong>Advantages of the Design-first Approach</strong></h3>
<p>Adopting the approach of giving utmost attention to the appearance at the early stage of an application’s development can be beneficial in many aspects:</p>
<ul>
<li><p><strong>Clear Visual Reference:</strong> Developers can use the initial design as a visual guide for the final product. This ensures there is less ambiguity about how a product looks for team members, especially designers and stakeholders.</p>
</li>
<li><p><strong>User-Centric Development:</strong> It is a fundamental principle in software development to prioritize users' needs. With a design-first approach, the end user’s experience is at the forefront while starting. Employing this method, it is easier for the developer to tailor the product to be more polished and user-friendly.</p>
</li>
<li><p><strong>Early Feedback:</strong> Feedback is necessary while developing software as it gives room for testing and iterative improvements in the design. Allows for adjustments to be done before investing time in complex logic implementation.</p>
</li>
</ul>
<h3 id="heading-disadvantages-of-the-design-first-approach"><strong>Disadvantages of the Design-first approach</strong></h3>
<p>There are potential challenges associated with the design-first approach such as:</p>
<ul>
<li><p><strong>Potential Rework:</strong> In some scenarios, a significant rework might be needed if the design does not align with technical capabilities. With the logic coming after the design, developers would most likely adjust designs or overhaul an entire section.</p>
</li>
<li><p><strong>Delayed Functionality:</strong> With priorities assigned to design, the core functionalities meant to be integrated into the software may be delayed and lead to a visually pleasing but ‘empty’ application.</p>
</li>
<li><p><strong>Over-emphasis on Aesthetics:</strong> Imagine your dream car with its glamorous bodywork but without an engine to make it function and serve its purpose of being a means of transportation. The same goes for building software with the design-first approach. There is a risk of placing more importance on looks over functionality.</p>
</li>
</ul>
<h3 id="heading-best-use-case-scenarios-for-the-design-first-approach"><strong>Best Use-Case Scenarios for the Design-first Approach</strong></h3>
<p>Having understood what the design-first approach entails, there are scenarios or projects to which this approach is best suited:</p>
<ul>
<li><p><strong>Building Consumer-facing Products:</strong> Customer-facing products are software for the general public rather than business. More emphasis is placed on design and ease of use because they are intended for a broad audience. Factors such as aesthetics, user experience and engagement are pivotal in building these types of applications. Failure to deliver a visually appealing and intuitive interface can make or break the product’s success. Examples of customer-facing products are social media platforms, e-commerce apps, data visualization projects, and so on.</p>
</li>
<li><p><strong>Building Brand-Oriented Projects:</strong> A company’s brand identity encapsulates its values, mission, message and visual elements. As a developer building an application for a company, the brand identity should be intertwined with the aesthetics or user experience. The design-first approach is necessary in such cases as it ensures that every aspect of the product is a true reflection of the brand, aligning perfectly with its identity.</p>
</li>
<li><p><strong>Building content-heavy websites and landing pages:</strong> Websites such as news sites or blogs focus on content layout and content readability which makes design-first perfect for such projects. Landing pages and portfolio sites should also employ this approach as visual impact is paramount.</p>
</li>
<li><p><strong>Prototyping:</strong> In the early stages of product development, a design-first approach can be employed to develop a prototype or Minimum Viable Product (MVP). Prototypes and MVPs are used to test key concepts, impress investors/stakeholders and garner useful user feedback.</p>
</li>
</ul>
<h2 id="heading-logic-first-approach"><strong>Logic-first Approach</strong></h2>
<p>The logic-first approach focuses on the core functionalities, data structure, data flow and architecture before the design aspects. In this method, developers are concerned about the intricacies that involves organizing, updating, retrieving and storing data as regards front-end. Underlying functionalities are extensively worked on before attaching to user interface elements for user interaction, which gives desired results.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724861233496/0854cc54-5777-4212-a0a8-44a256c9d307.jpeg" alt="programmer handling logic" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h3 id="heading-advantages-of-the-logic-first-approach"><strong>Advantages of the Logic-first Approach</strong></h3>
<p>Starting an application’s development by focusing on the logical aspects can yield good results such as:</p>
<ul>
<li><p><strong>Strong Architectural Foundation:</strong> By establishing the core logic early, a strong base for the application is formed. This approach aids complex business logic handling and data processing ensuring the application’s base is solid, scalable and maintainable.</p>
</li>
<li><p><strong>Performance Optimization:</strong> The logic-first approach focuses on the systematic fine-tuning of processes such as handling the amount of HTTP requests, API calls, error handling, memory leak prevention, amount of rendering, caching, and so on. With design elements not in the way of the logically-inclined developer, there are no constraints during development.</p>
</li>
<li><p><strong>Early Problem Detection:</strong> By addressing logic first, the identification of technical challenges that may arise later during the application development process is detected earlier. This gives room for necessary adjustments to be done and reduces the risk of a significant rework later.</p>
</li>
</ul>
<h3 id="heading-disadvantages-of-the-logic-first-approach"><strong>Disadvantages of the Logic-first Approach</strong></h3>
<p>While the approach has its merits, it also comes with certain drawbacks that developers should consider. Below, we explore some of the key disadvantages associated with this method.</p>
<ul>
<li><p><strong>Design Compromise:</strong> With logic-first, the design may become a ‘second thought’, leading to an application that is functional but devoid of aesthetic appeal. This might put off users at first interaction because the allure of good user interfaces matters a lot.</p>
</li>
<li><p><strong>User Experience Neglect:</strong> The sole aim of user experience is to satisfy users. An application’s UI might look appealing but fail to create a seamless, efficient and enjoyable impression on the user. Adopting a logic-first approach relegates the user experience to the background and hampers the enjoyability of the app.</p>
</li>
</ul>
<h3 id="heading-best-use-case-scenarios-for-the-logic-first-approach"><strong>Best Use-Case Scenarios for the Logic-first Approach</strong></h3>
<p>Projects that suit this approach emphasize performance, data processing and complex logic. This approach works well with:</p>
<ul>
<li><p><strong>Enterprise Applications:</strong> These are large software built for the corporate world which makes data integrity, security and performance crucial in its development. Starting with logic ensures the application can meet these requirements before designing.</p>
</li>
<li><p><strong>API-Centric Platforms:</strong> With the rise of Application Programming Interface (API) in the technology landscape, it is common to see applications heavily relying on APIs. By extensively consolidating the data flow and logic involved, developers can ensure smooth interactions between the front-end and back-end in the application development process.</p>
</li>
<li><p><strong>Performance-Critical Applications:</strong> The logic-first approach favors building applications where efficiency and speed are critical. Examples of such applications are real-time data processing tools and financial platforms.</p>
</li>
</ul>
<h2 id="heading-hybrid-approach"><strong>Hybrid Approach</strong></h2>
<p>This approach combines the design-first and logic-first approaches used in front-end development. The hybrid approach aims to leverage the strengths of both approaches while lessening their weaknesses.</p>
<p><strong>Key Components of the Hybrid Approach</strong></p>
<p>Certain practices embody the hybrid approach which can be applied in various software development scenarios:</p>
<ul>
<li><p><strong>Parallel Development:</strong> It involves the design and logic teams collaborating concurrently instead of following a sequential process. This offers benefits such as improved efficiency, continuous feedback and swift problem-solving.</p>
</li>
<li><p><strong>Low-Fidelity Prototyping:</strong> Involves creating basic, simplified versions of a product that emphasize key design concepts and core functionalities without showing the detailed final product. It helps in early validation, iterative improvement and risk mitigation.</p>
</li>
<li><p><strong>Component-Based Development:</strong> Involves building reusable components that typically consist of both design and logic. The advantages of using components in developing applications are re-usability, consistency and easy maintenance.</p>
</li>
<li><p><strong>Agile Methodologies:</strong> Using iterative development cycles to alternate between design and logic-focused approaches. It allows for flexibility, room for continuous improvements and balanced focus.</p>
</li>
</ul>
<h3 id="heading-advantages-of-the-hybrid-approach"><strong>Advantages of the Hybrid Approach</strong></h3>
<p>Sharing the focus between the two approaches comes with benefits such as:</p>
<ul>
<li><p><strong>Concurrent Progress:</strong> Working on design and logic together ensures that neither aspect is neglected during the development process. This leads to a product that is both visually appealing and functional.</p>
</li>
<li><p><strong>Improved Communication:</strong> Combining both approaches leads to better collaborations between designers and developers. This ensures designs are feasible and logical aspects seemingly easier to incorporate.</p>
</li>
<li><p><strong>Flexibility:</strong> Rather than waiting for an aspect to be done and reworked later, the hybrid method allows both to develop together and adjustments made in real time.</p>
</li>
</ul>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>The choice between design-first and logic-first approaches depends on individual preference, team capacity, project type, target market or technical requirements.</p>
<p>Developers with a good understanding of each approach’s strengths and weaknesses can make informed decisions that align with their project goals and objectives.</p>
<p>The hybrid approach can be employed to balance out the inadequacies of both of the one-sided approaches. The hybrid approach offers the best of both worlds in the process of crafting both a visually appealing and functionally sound product.</p>
<p>Ultimately, it's up to each individual or team to select the approach that will lead to the best possible product outcome.</p>
<p>If you enjoyed reading this article, you could <a target="_blank" href="https://buymeacoffee.com/timothyolanrewaju">Buy Me a Coffee</a>.</p>
<p>You can also connect with me on <a target="_blank" href="https://www.linkedin.com/in/timothy-olanrewaju750/">LinkedIn</a> for more insightful posts and articles.</p>
<p>See you in the next one!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Flutter Tutorial – How to Develop an App with Flutter From Scratch ]]>
                </title>
                <description>
                    <![CDATA[ Recently, I've been working on a marketing strategy for a new app based on the Flutter framework. An entire development team has been teaching me the ins and outs of Flutter as a cross-platform technology.  And from what I've learned, I believe that ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-develop-a-flutter-app-from-scratch/</link>
                <guid isPermaLink="false">66be14b77448141502702273</guid>
                
                    <category>
                        <![CDATA[ Flutter ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oleh Romanyuk ]]>
                </dc:creator>
                <pubDate>Fri, 26 Apr 2024 18:11:29 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/1060---539.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Recently, I've been working on a marketing strategy for a new app based on the Flutter framework. An entire development team has been teaching me the ins and outs of Flutter as a cross-platform technology. </p>
<p>And from what I've learned, I believe that the framework is accessible to almost anyone, even those with few technical skills.</p>
<p>In this tutorial, you will learn how to build your first Flutter app, from developing the concept to publishing on the App Store. </p>
<p>I'll teach you how to properly set up your development environment and code with the main Flutter code language – Dart. Some key concepts like state management, UI construction, and widgets will prepare you to create and launch a polished app. I'll even guide you through publishing your app to the App Store</p>
<p>So find a comfortable seat and get ready, as we're about to dive in. </p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>First of all, you have to decide on an environment. I advise you to choose either Visual Studio Code or Android Studio. The first one is lightweight and is a nice option that works well across different kinds of operating systems. Android Studio is just as powerful, if you plan on building Android apps. </p>
<p>If you're a beginner, take a look at VS Code with the Flutter extension, as it offers a user-friendly experience and it's a really good starting point. Just make sure your PC meets the minimum system requirements for Flutter development, as mentioned in <a target="_blank" href="https://docs.flutter.dev/get-started/install/windows/desktop">the official Flutter documentation</a>.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-mobile-app-development-with-flutter">Mobile App Development with Flutter</a></li>
<li><a class="post-section-overview" href="#heading-11-simple-steps-to-create-your-first-flutter-app">11 Simple Steps to Create Your First Flutter App</a></li>
<li><a class="post-section-overview" href="#heading-step-1-start-with-an-idea-or-vision-for-your-future-app">Step 1: Start with an Idea or Vision for Your Future App</a></li>
<li><a class="post-section-overview" href="#heading-step-2-install-the-flutter-sdk-on-your-computer">Step 2: Install the Flutter SDK on Your Computer</a></li>
<li><a class="post-section-overview" href="#heading-step-3-install-libraries-and-plugins-to-make-coding-easier">Step 3: Install Libraries and Plugins to Make Coding Easier</a></li>
<li><a class="post-section-overview" href="#heading-step-4-time-to-code">Step 4: Time to Code!</a></li>
<li><a class="post-section-overview" href="#heading-step-5-organize-your-project">Step 5: Organize your Project</a></li>
<li><a class="post-section-overview" href="#heading-step-6-code-the-ui-elements-and-interactions-widgets">Step 6: Code the UI Elements and Interactions (Widgets)</a></li>
<li><a class="post-section-overview" href="#heading-step-7-do-splash-screenwriting">Step 7: Do Splash Screenwriting</a></li>
<li><a class="post-section-overview" href="#heading-step-8-demonstrating-changes">Step 8: Demonstrating Changes</a></li>
<li><a class="post-section-overview" href="#heading-step-9-test-your-app">Step 9: Test Your App</a></li>
<li><a class="post-section-overview" href="#heading-step-10-code-styles">Step 10: Code Styles</a></li>
<li><a class="post-section-overview" href="#heading-step-11-publish-your-app">Step 11: Publish Your App</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-mobile-app-development-with-flutter">Mobile App Development with Flutter</h2>
<p>Let's kick off with some useful information about our framework. Basically, Flutter is an open-source kit developed by Google that allows you to build mobile apps, as well as network and integrated apps. </p>
<p>The key thing to remember about Flutter is that once you write code, you can upload your app to Android, iOS, and the web. Then, you can install it on multiple systems, including a PC. This really saves you a lot of time and effort compared to building separate apps for each platform.</p>
<p>Before we get started, let's learn why Flutter is extremely useful for mobile development.</p>
<h3 id="heading-advantages-of-flutter">Advantages of Flutter</h3>
<p>As I already mentioned, Flutter works with multiple systems and platforms at once, covering Android and iOS as well as Windows, Linux, and MacOS. Imagine – it's a single code base that rules them all! </p>
<p>Another advantage is that Flutter has a low entry barrier because of its simple syntax. For example, if you want to display some text, you easily create a widget called "Text", assign a style and color, add some text – and there you have it. It sounds simple – and it is.</p>
<h3 id="heading-limitations-of-flutter">Limitations of Flutter</h3>
<p>Before you decide to use Flutter, you should understand the whole picture. There are native technologies like Kotlin and Swift that have their unique advantages. </p>
<p>The first is that they provide the lowest possible delay and the smoothest possible user experience. They're perfect for applications that require low response times, like financial trading apps.</p>
<p>The second benefit is excellent performance and optimization. You have no redundancy in these specific situations. But only in these situations. So if your application requires extensive use of the device's hardware, such as real-time 3D graphics or sensor integration, you should consider going native.</p>
<h3 id="heading-back-end-development-with-flutter">Back-end Development with Flutter</h3>
<p>But, if you've decided to go the Flutter way, there's an important thing to consider: Flutter is a front-end framework, and it requires a back-end framework for complex applications. In short, if your app has state that needs to be stored, you need additional back-end technology. </p>
<p>I prefer Node.js because it can be launched anywhere, but you may use any other viable service. For a startup, a good example is free Firebase Cloud Functions. And as I've already mentioned, Dart is the main code language of Flutter, so you can also write a back-end with its help.</p>
<p>But choosing a decent back-end for your Flutter app is a whole other topic. I recommend you read the article “<a target="_blank" href="https://www.dhiwise.com/post/decoding-the-art-of-choosing-the-perfect-flutter-backend">Decoding the Art of Choosing the Perfect Flutter Backend: A Guide for Developers</a>”.</p>
<p>Otherwise, feel free to join me in this tutorial – let's begin!</p>
<h2 id="heading-11-simple-steps-to-create-your-first-flutter-app">11 Simple Steps to Create Your First Flutter App</h2>
<h3 id="heading-step-1-start-with-an-idea-or-vision-for-your-future-app">Step 1: Start with an Idea or Vision for Your Future App</h3>
<p>Many tools can help you at this stage, but the one you choose will depend on your design skills. </p>
<p>You can find visual inspiration on Dribbble, Pinterest, and many other websites. But when it comes to creating a design, there are three ways to go:</p>
<p>If you have no design skills, consider using Canva for app design and MockFlow for wireframes.</p>
<p>If you have some skills, then jump into Figma and you'll enjoy its many functionalities. Create your wireframes, and only after careful consideration develop the full-blown design. </p>
<p>Note that you can also use plugins like <a target="_blank" href="https://www.figma.com/community/plugin/1110606481076006495/figma2flutter">Figma2Flutter</a> and <a target="_blank" href="https://www.figma.com/community/plugin/844008530039534144/figmatoflutter">FigmaToFlutter</a> to turn your design into working Flutter code. So, the first step can easily be the last in creating your first Flutter app. </p>
<p>But I encourage you to read on and get an idea of the whole process. The code auto-created by one of the plugins may have bugs, and you'll need to be able to fix them.</p>
<p><img src="https://lh7-us.googleusercontent.com/Ia_FGjqAIgXnhIgIektxVcy7Cz5tt0HIHPZUfYDmaaeEemW4-b85f-5l6gKNt-m4TlvAtvDgXHPtpuPoAzxZvpoOhqnV2wXyq2KLUTvsyVX1cReuL8StA-b0Ni7scnnkV8sQ93_UT3ORN7ZiLT1gjfU" alt="Image" width="600" height="400" loading="lazy">
<em>Figma2Flutter is a great source of plugins</em></p>
<p>And finally, if you're stuck, find a designer. It can be a professional freelancer, a design agency, or just a friend with design skills. Either way, you'll still have the option of transforming your design using the Figma2Flutter or FigmaToFlutter plugins.</p>
<h3 id="heading-step-2-install-the-flutter-sdk-on-your-computer">Step 2: Install the Flutter SDK on Your Computer</h3>
<p>This step is very easy. Follow the link to the <a target="_blank" href="https://docs.flutter.dev/get-started/install">Flutter download page</a>. Choose your operating system and platform. Don't forget to check the software requirements. </p>
<p>Here, you might need to get some better hardware or install some extra packages, but I think you can do it using the tutorial on the Flutter website.</p>
<p><a target="_blank" href="https://docs.flutter.dev/get-started/install/windows/desktop">The Flutter tutorial</a> provides different options for a text editor or an integrated development environment (IDE). So, install the one you prefer, such as Android Studio, and install the Flutter SDK. When you're done with the tutorial, come back here, and we'll continue.</p>
<h3 id="heading-step-3-install-libraries-and-plugins-to-make-coding-easier">Step 3: Install Libraries and Plugins to Make Coding Easier</h3>
<p>Flutter libraries are like toolkits that come with pre-built parts to help you create code faster and easier. They come packed with all sorts of useful things like buttons, forms, animations and more. You can use them for everything from designing user interfaces to managing data and handling interactions. </p>
<p>Now, let's talk about plugins in Flutter. They are like special tools that help your application do more. </p>
<p>These plugins connect your Flutter code to the native features of your device, such as the camera or GPS. You can also easily add extra functionality to your app without having to write all the code on your own. Just write some initial code, hit enter and you'll get several lines of code from the example.</p>
<p><img src="https://lh7-us.googleusercontent.com/90Szu_VCkBADwx-I817QjLhKju50Rcl5K5vdq_D0L6gAS-8L29_fflJjQof4l5hZAuOOzmiraI3TKefuHgJR4Zm3cBfg35NCL14t2B_t8174787S65ygVulzay9ffHAFzoNSiL7jiSLfDNRpnY-zRIQ" alt="Image" width="600" height="400" loading="lazy">
<em>Settings -&gt; Plugins</em></p>
<p>You can also find practical ideas for your app on <a target="_blank" href="https://flutterawesome.com/">Flutter Awesome</a> and <a target="_blank" href="https://pub.dev/">pub.dev</a> with official libraries and community support. These sites host third-party developers who build their libraries on <a target="_blank" href="https://github.com">GitHub</a> and share them here. They’ve been tested on real projects and include a wide range of features such as connecting to servers, using Bluetooth, and adding visual effects. </p>
<p>Also, libraries are rated according to their popularity and quality. A high rating increases the chances that the library you choose will have as few bugs as possible.</p>
<p>If you run into trouble, don't worry! You can turn to <a target="_blank" href="https://flutterawesome.com/">Flutter Awesome</a> and <a target="_blank" href="https://pub.dev/">pub.dev</a> for help. Since Flutter is open source, you'll be able to find the latest updates and get help from other Flutter developers. And if there's a new problem, it's likely to be fixed in the next Flutter update. Easy peasy!</p>
<h3 id="heading-step-4-time-to-code">Step 4: Time to Code!</h3>
<p>Flutter is built and translated into machine code using the Dart programming language. Host devices understand this code, ensuring fast and effective performance. It’s an open, object-oriented programming language developed by Google. </p>
<p>Here are some of the key features of Dart:</p>
<ul>
<li>Object-oriented with classes, inheritance, and mixins</li>
<li>Statically typed for early error detection</li>
<li>Supports both just-in-time (JIT) and ahead-of-time (AOT) compilation</li>
<li>Automatic memory management with garbage collection</li>
<li>Built-in asynchronous programming resource</li>
<li>Consistent and simple syntax</li>
</ul>
<p>Dart is a programming language that allows you to describe any logic in a mobile application in an easy-to-understand way. Its features, such as the reactive programming version and asynchronous features, make it suitable for building high-performance, responsive apps that can run on iOS and Android. </p>
<p>Though not as widely adopted as some other languages, Dart's tight integration with Flutter has made it increasingly popular for mobile app improvement.</p>
<p>Now, let’s get back to the code! Just create your project on a standard blank page with the ability to launch and test your app.</p>
<p>Here’s our simple Flutter app, which displays a "Hello, Flutter!" message. It demonstrates the basic form of a Flutter app, along with the main access aspect, defining a static widget, and building a MaterialApp with a Scaffold, AppBar, and a targeted Text widget:</p>
<pre><code class="lang-dart"><span class="hljs-keyword">import</span> <span class="hljs-string">'package:flutter/material.dart'</span>;

<span class="hljs-keyword">void</span> main() {
  runApp(MyApp());
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyApp</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">StatelessWidget</span> </span>{
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text(<span class="hljs-string">'My First Flutter App'</span>),
        ),
        body: Center(
          child: Text(
            <span class="hljs-string">'Hello, Flutter!'</span>,
            style: TextStyle(fontSize: <span class="hljs-number">24</span>),
          ),
        ),
      ),
    );
  }
}
</code></pre>
<p>I strongly advise you to break your code into logical parts:</p>
<ul>
<li>UI</li>
<li>server communication</li>
<li>business logic</li>
<li>images</li>
<li>translation and more</li>
</ul>
<p>The plan allows you to organize your code and structure it easily.  </p>
<p>The next step is no less important than the coding itself. Choosing the right state management is like the basics of Flutter app development. There, you’ll get to know different insights like factors, Model-View-ViewModel architecture, and the difference between two popular Flutter management patterns. </p>
<p>So, what are we waiting for, let’s get right to it.</p>
<h3 id="heading-step-5-organize-your-project">Step 5: Organize your Project</h3>
<h4 id="heading-choose-the-right-state-management-solution">Choose the right state management solution</h4>
<p>State management controls the state of user interface elements such as text fields, buttons, and checkboxes in a graphical user interface (UI). It ensures that the state of other UI controls affect the state of a particular UI control. This technique is critical to ensure a smooth user experience in your app </p>
<p>To choose the right state management, consider factors such as the complexity of your project, your familiarity with different state management solutions, and the specific needs of your project. Google recommends starting with something basic like Vanilla, which is simple and easy to use.</p>
<p>Now let's look at the Model-View-ViewModel (MVVM) architecture, which is an important part of state management. And you have to choose between Provider and BloC. The whole difference between these two popular Flutter state management patterns is the following: </p>
<ul>
<li>For smaller projects and short deadlines, you can use Provider MVVM. But beware: the tradeoff is slightly slower performance and lower scalability.</li>
<li>For mid-size and large projects, Google suggests using BLoC. Such an approach allows you to manage the flexibility and the scale of your code. </li>
</ul>
<p>If you haven’t decided what to use for your project yet, here are some pages with descriptions and examples from the official library documentation:</p>
<ol>
<li><a target="_blank" href="https://pub.dev/packages/flutter_bloc">https://pub.dev/packages/flutter_bloc</a></li>
<li><a target="_blank" href="https://pub.dev/packages/provider">https://pub.dev/packages/provider</a></li>
<li><a target="_blank" href="https://docs.flutter.dev/data-and-backend/state-mgmt">https://docs.flutter.dev/data-and-backend/state-mgmt</a></li>
</ol>
<p>So, choose a state management option that fits your app.</p>
<h4 id="heading-separate-folders-for-screens">Separate folders for screens</h4>
<p>You should keep your code clean. To do this, it's a good idea to create separate folders for each screen, where the code files are stored. </p>
<p>For example, you'd have one folder for the splash screen and another for the login screen. Also, keep the user interface code separate from the business logic code, in separate files.</p>
<p>Your prepared Directory Structure should look something like this:</p>
<p><img src="https://lh7-us.googleusercontent.com/U5DSbWDz5PicgCi690wdIzoxFlkUVz9p-z0jHq74AHs3Cvu18kIpiQ2eo47sMo4Bkbwwi4_kKcyv-EU-ZmuNt368IzJvoLC-VEGDjpoSBIdTHyf0-CBNzkJcHg-1IqoURIBHVXj8pci-2dBVJ3xkBsk" alt="Image" width="600" height="400" loading="lazy">
<em>My folder organization</em></p>
<h4 id="heading-highly-decomposed-system">Highly decomposed system</h4>
<p>When you start working with a screen, you should carefully break it down into small parts. For example, on the main screen, there is a list of goods. This element should be in a separate file and even a single element of a list should be in a different file. </p>
<p>The more your system is decomposed, the easier it will be for you in the future to change a piece of code, as well as support and scale your product. </p>
<p>Here are some tips on how can you break down a system into smaller components effectively:</p>
<ul>
<li>Start by defining the goals, features, potential users, and limitations of your system to set clear boundaries.</li>
<li>Divide the system into smaller, independent pieces for easier management.</li>
<li>Assign specific functionality and interfaces to each component and how they interact.</li>
<li>To achieve the system goals, test all components and their interactions.</li>
<li>To optimize performance, refine components based on feedback.</li>
</ul>
<h4 id="heading-colors-and-styles">Colors and styles</h4>
<p>When you have the screens' structure, you can code the basic transition between them and the styles of an app. Flutter makes it easy to manage all your styles in one place, like button colors, fonts, and icons, so you can customize them easily. You code them in one chosen style—a bright or dark style scheme.</p>
<p>The next step is to code simple transitions and patterns that will make your app fit your style choices. As you'll see in the code example below, Flutter makes it very easy to control styles. This allows you to test and customize the look and feel of your app as much as you want.</p>
<p><img src="https://lh7-us.googleusercontent.com/Kzimy6hu5i143WNcWPIPCkLkoB1wz9LpZCEmHZ-UJ-ByYiysAI5QG42YaqXjk0Icelxx-SdxmHGwoBDnvPMhnOTCniDnO_cA4Xxd5siib0dnXfMbyGCzNJ9hpBJBd1WZw5ZRj9cCut-wsFwbOgMpARo" alt="Image" width="600" height="400" loading="lazy">
<em>My file for managing themes</em></p>
<p>And here’s some useful code as an example, so you can experiment and try your own ideas to your heart's content.</p>
<pre><code class="lang-dart"><span class="hljs-meta">@override</span>
Widget build(BuildContext context) {
 <span class="hljs-keyword">return</span> TextField(
   controller: controller,
   focusNode: focusNode,
   style: AppStyles.getCitySearchTextStyle(),
   decoration: InputDecoration(
     hintText: context.tr().searchHint,
     hintStyle: AppStyles.getSearchHintStyle(),
     contentPadding: AppPaddings.horizontalPaddingM,
     isDense: <span class="hljs-keyword">true</span>,
     border: InputBorder.none,
     focusedBorder: InputBorder.none,
     enabledBorder: InputBorder.none,
     errorBorder: InputBorder.none,
     disabledBorder: InputBorder.none,
   ),
 );
}
</code></pre>
<h4 id="heading-setting-up-the-router">Setting up the router</h4>
<p>There is a robust navigation tool for managing transitions between specific monitors within the application. There are two main navigation techniques you can use in Flutter:</p>
<ul>
<li>Navigator: this is a navigation widget that is built into Flutter. It allows you to slide and lift the screen from the stack, providing a simple forward and backward navigation experience. You can use named and anonymous routes to understand the application's video display units.</li>
<li>Routing Library: you can use a library like go_router or auto_router if you need more complex navigation. This package provides features such as deep link analysis and fine-grained control of navigation stacks.</li>
</ul>
<p>Here’s also the <a target="_blank" href="https://docs.flutter.dev/cookbook/navigation">Flutter navigation documentation</a>, in case you need something.</p>
<p>Now you should set up the router as shown in the example on the screen and let me know if everything worked well for you:</p>
<h4 id="heading-simple-navigation-between-screens">Simple navigation between screens</h4>
<p>Using the <code>Navigator.Push</code> approach and <code>MaterialPageRoute</code>, this example shows a way to navigate between screens (or routes) in a Flutter app.</p>
<pre><code class="lang-dart">Navigator.push(
  context,
  MaterialPageRoute(builder: (context) =&gt; SecondScreen())
</code></pre>
<p><img src="https://lh7-us.googleusercontent.com/cv3qVAKCIT0XjdyyFJg9Lt6Vu9zLdENES21LD9_z9JJJSUV_rL6Wiu0kRakHjSR6jgzl77-0U45GQkgX9tUEQbAKTvCEawJp7o4HSjIUrJ1u0rWAfvIx3jELK2E64Eb9xBtDQYS-GFACr64SK0WLRLg" alt="Image" width="600" height="400" loading="lazy">
<em>My file for managing the router</em></p>
<p>So, now you can start setting up languages for your app because it’s as important as having the right UI elements in the project.</p>
<h4 id="heading-languages">Languages</h4>
<p>You'll want to localize your app, so that users can select different languages or have it automatically localized.</p>
<p>Google provides recommendations on the approach that best suits your needs and technical requirements which you can <a target="_blank" href="https://docs.flutter.dev/ui/accessibility-and-internationalization/internationalization">read more about here</a>.</p>
<p>Start by creating a file of translations for one language. If needed, you can add more languages later.</p>
<p><img src="https://lh7-us.googleusercontent.com/DOZzrnB6iANF95EyDh9EnlFeGJ057zLaudUk7Ej5pP-5z12SMT7W5Ceh3Laf10i7izm7mCloUz29goBSyh4G25LqTWeo8hu1kJXfLHU3baEAaWk0l3lcamLBlTZqkMYLIQzvxylphHh6fZKigPcTvaY" alt="Image" width="600" height="400" loading="lazy">
<em>My localization into Ukrainian</em></p>
<pre><code class="lang-dart"><span class="hljs-keyword">return</span> Center(
 child: Text(Localization.from(context).continueText),
)
</code></pre>
<p>Once you finish this part, you will have the basic elements of an app – styles, localization, screen structures, and transitions. And then, you can start programming each screen.</p>
<h3 id="heading-step-6-code-the-ui-elements-and-interactions-widgets">Step 6: Code the UI Elements and Interactions (Widgets)</h3>
<p>At this stage, you'll code the basic elements of a screen's UI and the logic that will control the UI. For example, you might develop a logic for browsing a list of products from a remote server by selecting an item from a goods list. Then you write code that converts a particular data model into an item.</p>
<p>Flutter uses ready-made widgets. In fact, Flutter is all about widgets. One of the innovative things about them is that they're reusable UI components that you can integrate directly into the app instead of building them from scratch. Compare this to different strategies that use exclusive objects (layouts, perspectives, controllers), where Flutter has a single, unique object model.</p>
<p>Every object in Flutter is a widget – from buttons to pads to text, and existing building blocks to the lowest levels of customization. You'll be using the same tools that the Flutter team uses to build theirs.</p>
<p>Widgets in Flutter are available for rendering but they can also cause a problem with the overall structure. You'll need to plan the form because large apps can require up to ten layers of code to create a primary element. For an excellent article with lots of ready-made widgets, check out <a target="_blank" href="https://proandroiddev.com/my-flutter-adventure-widgets-8ea08a7067eb">this guide</a>. </p>
<p>Otherwise, here's a short but useful list of must-have code elements for your basic app:</p>
<h4 id="heading-element-1-create-lists">Element 1: Create lists</h4>
<p>This part of the code demonstrates a way to create a list of items using <code>ListView.Builder</code>. It takes a list of items and generates <code>ListTile</code> widgets for each item, allowing you to address faucet events on the gadgets:</p>
<pre><code class="lang-dart">
  <span class="hljs-keyword">final</span> <span class="hljs-built_in">List</span>&lt;<span class="hljs-built_in">String</span>&gt; items =
      <span class="hljs-built_in">List</span>&lt;<span class="hljs-built_in">String</span>&gt;.generate(<span class="hljs-number">10</span>, (<span class="hljs-built_in">int</span> index) =&gt; <span class="hljs-string">"Item with number <span class="hljs-subst">$index</span>"</span>);

  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> Scaffold(
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (BuildContext context, <span class="hljs-built_in">int</span> index) {
          <span class="hljs-keyword">return</span> ListTile(
            title: Text(items[index]),
            onTap: () {
              ScaffoldMessenger.of(context)
                  .showSnackBar(SnackBar(content: Text(<span class="hljs-string">'Item <span class="hljs-subst">$index</span> tapped!'</span>)));
            },
          );
        },
      ),
    );
  }
</code></pre>
<p>Here is how your list should look after coding:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/image-29.png" alt="Image" width="600" height="400" loading="lazy">
<em>View of the list</em></p>
<h4 id="heading-element-2-api-request">Element 2: API request</h4>
<p>This code shows how to get data from an API using the HTTP bundle. It makes a GET request to the desired URL and handles the response, processing any fetched records or managing errors:</p>
<pre><code class="lang-dart">Future&lt;<span class="hljs-keyword">void</span>&gt; fetchData() <span class="hljs-keyword">async</span> {
  <span class="hljs-keyword">final</span> response = <span class="hljs-keyword">await</span> http.<span class="hljs-keyword">get</span>(<span class="hljs-built_in">Uri</span>.parse(<span class="hljs-string">'https://api.example.com/data'</span>));
  <span class="hljs-keyword">if</span> (response.statusCode == <span class="hljs-number">200</span>) {
    <span class="hljs-keyword">final</span> data = json.decode(response.body);
    <span class="hljs-comment">// Process fetched data here</span>
    <span class="hljs-built_in">print</span>(data);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-comment">// Handle error</span>
    <span class="hljs-built_in">print</span>(<span class="hljs-string">'Failed to fetch data: <span class="hljs-subst">${response.statusCode}</span>'</span>);
  }
}
</code></pre>
<h4 id="heading-element-3-styling-text">Element 3: Styling text</h4>
<p>Here, you can see a demonstration of how to display two texts in column and style textual content in Flutter the usage of the <code>TextStyle</code> magnificence, which allows you to customize styles like coloring, font size, font weight and font style:</p>
<pre><code class="lang-dart">
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">const</span> Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: &lt;Widget&gt;[
            Text(
              <span class="hljs-string">'Hello!'</span>,
              style: TextStyle(
                color: Colors.red,
                fontSize: <span class="hljs-number">36</span>,
                fontWeight: FontWeight.bold,
                fontStyle: FontStyle.italic,
              ),
            ),
            Text(
              <span class="hljs-string">'Flutter'</span>,
              style: TextStyle(
                color: Colors.blue,
                fontSize: <span class="hljs-number">18</span>,
                fontWeight: FontWeight.bold,
                fontStyle: FontStyle.italic,
              ),
            ),
          ],
        ),
      ),
    );
  }
</code></pre>
<p>The result looks great, doesn't it?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/image-30.png" alt="Image" width="600" height="400" loading="lazy">
<em>View of the styled text</em></p>
<h4 id="heading-element-4-custom-styled-buttons">Element 4: Custom-styled buttons</h4>
<p>This one shows a way to create a custom-styled button using the <code>MaterialButton</code> widget. It allows you to personalize properties such as height, top, shape, color and a widget (in this situation, a text widget with custom styling):</p>
<pre><code class="lang-dart">
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> Scaffold(
      body: Center(
        child: MaterialButton(
          elevation: <span class="hljs-number">0</span>,
          height: <span class="hljs-number">50</span>,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(<span class="hljs-number">20</span>),
          ),
          color: Colors.blue,
          onPressed: () {
            ScaffoldMessenger.of(context)
                .showSnackBar(<span class="hljs-keyword">const</span> SnackBar(content: Text(<span class="hljs-string">"Button tapped!"</span>)));
          },
          child: <span class="hljs-keyword">const</span> Padding(
            padding: EdgeInsets.all(<span class="hljs-number">16</span>),
            child: Text(
              <span class="hljs-string">"Hello button"</span>,
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.white,
                fontSize: <span class="hljs-number">12</span>,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
      ),
    );
  }
</code></pre>
<p>Hello-button is ready!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/image-31.png" alt="Image" width="600" height="400" loading="lazy">
<em>View of the custom styled button</em></p>
<h4 id="heading-element-5-icons">Element 5: Icons</h4>
<p>This one suggests a way to display an icon (in this situation, a celebrity icon) in your Flutter app, allowing you to customize its color and length:</p>
<pre><code class="lang-dart">Icon(
  Icons.star,
  color: Colors.yellow,
  size: <span class="hljs-number">24</span>,
)
</code></pre>
<h4 id="heading-element-6-displaying-images-from-the-network">Element 6: Displaying images from the network</h4>
<p>By specifying the photo URL, width, top and health, this code demonstrates how to display a photo from a network URL using the <code>Image.Network</code> widget:</p>
<pre><code class="lang-dart">Image.network(
  <span class="hljs-string">'https://example.com/image.jpg'</span>,
  width: <span class="hljs-number">200</span>,
  height: <span class="hljs-number">200</span>,
  fit: BoxFit.cover,
)
</code></pre>
<h4 id="heading-element-7-simple-animated-container">Element 7: Simple animated container</h4>
<p>This code creates an active container that changes its size (width and top) when a true set (<code>_isExpanded</code>) is changed, with a smooth animation described using the required period and curve:</p>
<pre><code class="lang-dart">AnimatedContainer(
  width: _isExpanded ? <span class="hljs-number">200</span> : <span class="hljs-number">100</span>,
  height: _isExpanded ? <span class="hljs-number">200</span> : <span class="hljs-number">100</span>,
  color: Colors.blue,
  duration: <span class="hljs-built_in">Duration</span>(milliseconds: <span class="hljs-number">500</span>),
  curve: Curves.easeInOut,
)
</code></pre>
<h4 id="heading-element-8-handling-text-input">Element 8: Handling text input</h4>
<p>This code demonstrates how to take care of textual content input using the TextField widget, providing a callback property to handle text changes and such decorations (like label) to the data entry process:</p>
<pre><code class="lang-dart">
  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">const</span> Scaffold(
      body: Padding(
        padding: EdgeInsets.all(<span class="hljs-number">16.0</span>),
        child: TextField(
          decoration: InputDecoration(
            focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.greenAccent, width: <span class="hljs-number">5.0</span>),
            ),
            enabledBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.red, width: <span class="hljs-number">5.0</span>),
            ),
            hintText: <span class="hljs-string">'Enter your name'</span>,
          ),
        ),
      ),
    );
  }
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/image-32.png" alt="Image" width="600" height="400" loading="lazy">
<em>View of the text handling</em></p>
<h3 id="heading-step-7-do-splash-screenwriting">Step 7: Do Splash Screenwriting</h3>
<p>Each application starts with a splash screen that displays a logo or a loading indicator while the app is getting ready. After that, the app loads the necessary data and the splash screen appears.</p>
<p>So, let's create our first screen and things will get a lot easier from there. You already have a lot of widgets in your arsenal, but you can copy and paste some of the code below. You can see more of my code on the screen, but I'll leave the rest for you to improve.</p>
<p>Below, you can see my images for writing a splash screen:</p>
<p><img src="https://lh7-us.googleusercontent.com/tPabzLQbBRwNIBLaitdmqZdqbUGuGwiNVD_X-dgGiOKMZLUbv50BYL_bU1lLxHTtMI25xScW2QeQ9qRItt_aXp5w_C9xGj7xWLpjtE-rq5AN0pr5AqaI5UGaMd4e2FWS-ey_v2Od31wwBpSzvxamKDY" alt="Image" width="600" height="400" loading="lazy">
<em>My splash screen code</em></p>
<pre><code class="lang-dart">IntrinsicWidth(
 child: Column(
   mainAxisSize: MainAxisSize.min,
   children: [
     <span class="hljs-keyword">const</span> FlutterLogo(
       size: <span class="hljs-number">250</span>,
     ),
     <span class="hljs-keyword">const</span> Gap(AppSizes.sizeM),
     Container(
       padding: AppPaddings.allPaddingXS,
       decoration: <span class="hljs-keyword">const</span> BoxDecoration(
         color: AppColors.alabaster,
         borderRadius: AppBordersRadius.borderRadiusAll100,
       ),
       child: <span class="hljs-keyword">const</span> LinearProgressIndicator(
         backgroundColor: AppColors.alabaster,
         borderRadius: AppBordersRadius.borderRadiusAll100,
         minHeight: AppSizes.sizeSSM,
       ),
     )
   ],
 ),
)
</code></pre>
<p><img src="https://lh7-us.googleusercontent.com/OAsCqqs-qai8W6FMItKdWqdjCM_DaBW4jnBD02yvOVGRIGAIFoMmBTDTLg2H1atQQdwc8MOVos18GnJTBiHvL8RqVmYkk4T9jQiqzlPn9-sSr30ywM8TVCZR9M1H7Z-RkEFekHfDGrxxB5utONCbOYs" alt="Image" width="600" height="400" loading="lazy">
<em>This is how the screen looks from the previous code</em></p>
<h3 id="heading-step-8-demonstrating-changes">Step 8: Demonstrating Changes</h3>
<p>Once you finish a section of your code, press a button in Android Studio to quickly see the changes on your screen. </p>
<p>This is one of Flutter's key features. You don't have to restart your project or rebuild the entire application every time you make a change. With Flutter, you can use hot reload or hot restart. Press a button and your changes will appear on your phone or website in a second.</p>
<p>Here’s how your changes may look on your screen:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/IMG_1562.JPG" alt="Image" width="600" height="400" loading="lazy">
<em>Demonstrating changes</em></p>
<p>At the moment, your app is almost ready, but here are a few important steps left. One of them is testing. That’s the only way you can check that everything is working fine. And if it doesn’t – you can easily see the mistake and fix it.</p>
<h3 id="heading-step-9-test-your-app">Step 9: Test Your App</h3>
<p>To make sure your app works and everything is built correctly, you need to test it. For example, you might have programmed one feature and accidentally broken the other. Also, if you have any platform-dependent elements, such as Bluetooth or NFC, you’ll need to check how they work in your application.  </p>
<p>But testing can have positive and negative test cases. Positive cases should always be tested. For example, an app should work with a correct login and password. Negative cases are when a QA engineer tries to "break" a product by entering the wrong types of data (instead of email, we enter "11111111"). Negative cases are needed to minimize user errors and to write understandable check prompts ("Please, enter your email here").</p>
<p>As you can see, this underscores the importance of thorough testing. By simulating user errors, we can ensure our apps are working fine and deliver a smooth UX. </p>
<p>In the example below with a login, you can see the proper testing functionality:</p>
<pre><code class="lang-dart">  <span class="hljs-meta">@override</span>
  Widget build(BuildContext context) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">const</span> Scaffold(
      body: Padding(
        padding: <span class="hljs-keyword">const</span> EdgeInsets.all(<span class="hljs-number">16.0</span>),
        child: Column(
          children: [
           TextField(
            controller: textEditingController,
            decoration: <span class="hljs-keyword">const</span> InputDecoration(
             focusedBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.greenAccent, width: <span class="hljs-number">5.0</span>),
            ),
            enabledBorder: OutlineInputBorder(
              borderSide: BorderSide(color: Colors.red, width: <span class="hljs-number">5.0</span>),
                borderSide: BorderSide(color: Colors.red, width: <span class="hljs-number">5.0</span>),
            ),
            hintText: <span class="hljs-string">'Enter your name'</span>,
          ),
        ),
        <span class="hljs-keyword">const</span> SizedBox(
         height: <span class="hljs-number">16</span>,
        ),
        MaterialButton(
         elevation: <span class="hljs-number">0</span>,
         height:<span class="hljs-number">50</span>,
         shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(<span class="hljs-number">20</span>),
         ),
         color: Colors.blue,
         onPressed:(){
          <span class="hljs-keyword">if</span> (textEditingController.text.trim().isEmpty){
           ScaffoldMessenger.of(context).showSnackBar(
            <span class="hljs-keyword">const</span> SnackBar(
             content: Text(<span class="hljs-string">"You should enter your name"</span>),
            ),
           );
          }<span class="hljs-keyword">else</span>{
         ScaffoldMessenger.of(context).showSnackBar(
         SnackBar(
         content:Text(
         <span class="hljs-string">"Your name is <span class="hljs-subst">${textEditingController.text.trim()}</span>"</span>,
        ),
       ),
      );
     }
    },
    child: <span class="hljs-keyword">const</span> Padding(
     padding: EdgeInsets.all(<span class="hljs-number">16</span>),
     child: Text(
      <span class="hljs-string">"Display my name"</span>,
      textAlign: TextAlign.center,
      style: TextStyle(
       color: Colors.white,
       fontSize: <span class="hljs-number">12</span>
       fontWeight: FontWeight.bold,
      ),
     ),
    ),
   ),
  ],
 ),
),
);
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/image-33.png" alt="Image" width="600" height="400" loading="lazy">
<em>the testing view</em></p>
<h3 id="heading-step-10-code-styles">Step 10: Code Styles</h3>
<p>To maintain a consistent style, it's important to follow certain standards when coding. Google recommends a certain code style – a way of calling variables or methods and dimensions. Libraries and plugins (analyzers) for Android Studio mark up code and suggest changes as you write your code. </p>
<p>Here are a few of them I can recommend:</p>
<ul>
<li><a target="_blank" href="https://pub.dev/packages/dio">Dio</a> for network requests</li>
<li><a target="_blank" href="https://pub.dev/packages/bloc_concurrency">Flutter bloc + bloc + bloc</a> concurrency to use BLoC state management</li>
<li><a target="_blank" href="https://docs.flutter.dev/data-and-backend/state-mgmt/simple">Provider</a> to use Provider state management</li>
<li><a target="_blank" href="https://pub.dev/packages/auto_route">Auto_route</a> + <a target="_blank" href="https://pub.dev/packages/auto_route_generator">Auto Route Generator</a> for routing</li>
</ul>
<p>There are a lot more you can find, from plugins to cache any network image to native splash generations. Code styles are required to ensure code quality and future code support for the largest projects.</p>
<p>You can <a target="_blank" href="https://docs.flutter.dev/tools/formatting">read more in the Flutter docs here</a>.</p>
<h3 id="heading-step-11-publish-your-app">Step 11: Publish Your App</h3>
<p>When you’re done coding and testing your app, you should test its performance on the platforms where you plan to have it – iOS, Android, and Web. </p>
<p>The first step is to publish a developer account creation on each system. After that, you'll need to pay a certain amount of money (once a year in Apple's case) and then download the apps. Then, <a target="_blank" href="https://support.google.com/googleplay/android-developer/answer/9859152?hl=en">Google and Apple employees review the apps</a> for compliance with requirements, standards and laws. If all goes well, the application will be released.</p>
<p>After overcoming any challenges, remember that a successful launch is just the beginning. Take a look at the images below and make sure your app is ready to be discovered by users:</p>
<p><img src="https://lh7-us.googleusercontent.com/V7Dinp2-PzzMP_WXNlPyjiD8TmyWMRPlzH-NA_zPspEDSlCMFvF2hWNjenMg_pFNmY_w8trDKBNOKhTXDVhuVQ9NNcSlSNIPyW8qzFM38zRLLyY_aj-jCSpLabSkiFP7zHsmjDFsHL5INg1rvD1UD-w" alt="Image" width="600" height="400" loading="lazy">
<em>Google Play release dashboard</em></p>
<p><img src="https://lh7-us.googleusercontent.com/s0yHjjeKHt38vxojQONVe1FKAbh4RqjeFHFprV2kKkAcfiFYiF9UYr-FCrF8O1u3J1wyuo7eAMzfICA57wfbPEgmGEyRrHwuKuewICvsATNuxg6DZLV60mAhHrE8_IuNIM46-Nd4epEYZGAxoBRyJfI" alt="Image" width="600" height="400" loading="lazy">
<em>App Store release dashboard</em></p>
<p>To publish your Flutter app to the App Store, you have to complete a few steps. </p>
<p>First of all, register for the Apple Developer Program and upload certificates to sign your app. After that, create an App Store Connect account to manage your app. Now, using Xcode, upload your app for App Store distribution. When everything is done, your last step is to enter details such as screenshots, description, and pricing for your app. </p>
<p>Sounds pretty easy, doesn't it? If you are looking for more information, just visit the <a target="_blank" href="https://developer.apple.com/ios/submit/">Apple developer page</a> to learn more.</p>
<p>Almost the same goes for the Google Play Store. Sign up for a Google Play Developer account and link it to a Google Wallet Merchant Account for in-app purchases (if necessary). Then, just make sure that your app meets their technical requirements and guidelines. This includes things like app signing, privacy policy, and content rating. </p>
<p>During the third step, you have to fill in details about your app that users will see in the Play Store. Now, upload your app bundle or just an APK file and configure pricing and distribution settings. You may have to wait a little, as Google will take some time to review your app to ensure it fits their policies.</p>
<p>Once your app is approved, you can finally publish it to the Google Play Store and make it available for users! This was just an overview – so to learn more about the process, <a target="_blank" href="https://support.google.com/googleplay/android-developer/answer/9859751">visit the official page</a> and get as much information as you need.</p>
<p>Now, you're ready to take the world. Just make sure you carefully check all the settings before publishing your app. You can set a clear date and time for publishing your Flutter app, manage production releases, and more. To be honest with you, there are way more features than you can imagine, so I'll let you do it by yourself.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>All right, now your app is ready. In this tutorial, I've given you the fundamentals of building a basic Flutter mobile app. Don't be afraid to take your unique idea and to run with it. </p>
<p>As I’ve already told you, the Flutter community is a treasure of information, so, feel free to jump in and explore it! </p>
<p>By the way, here's another golden piece of advice from me to keep in your developer toolbox: start simple, keep your code clean and organized, and test as you build. With these basics and a bit of effort, you'll quickly build a great Flutter app!</p>
<p>I would also like to thank my development partner in crime Mikhailo, who was helping me all the time creating this guide for you. Without his technical expertise, I wouldn't even know how to properly tell you about all these instructions, thanks again!</p>
<h3 id="heading-do-you-have-an-idea-for-a-flutter-project">Do you have an idea for a Flutter project?</h3>
<p>My company Covent IT is an early adopter of the <a target="_blank" href="https://coventit.com/services/flutter-development">Flutter framework</a> and a well-established mobile app development company in general. In case you have a promising project in mind, feel free to <a target="_blank" href="https://coventit.com/contact-us">request a consultation for a Flutter project</a><em>.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Manually Deploy a React and TypeScript Project on Netlify ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, I'll teach you how to manually deploy a React and TypeScript project with Vite on Netlify. I will show you a few quick and simple steps to get live versions of your projects up and running. To follow along with this tutorial, there ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/manually-deploy-a-react-and-typescript-project-on-netlify/</link>
                <guid isPermaLink="false">66ba5226e727ef4561965aa7</guid>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Netlify ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Losalini Rokocakau ]]>
                </dc:creator>
                <pubDate>Fri, 12 Apr 2024 18:02:59 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/cover-image-4.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, I'll teach you how to manually deploy a React and TypeScript project with Vite on Netlify. I will show you a few quick and simple steps to get live versions of your projects up and running.</p>
<p>To follow along with this tutorial, there are a few prerequisites:</p>
<ol>
<li>An existing React and TypeScript project with Vite that you want to deploy.</li>
<li>Visual Studio Code (VSCode) editor or any other code editor such as Sublime.</li>
<li>Optionally, you can just use a command line/terminal instead of your code editor's built-in terminal.</li>
<li>An existing Netlify account that you've already logged into.</li>
</ol>
<p>Let's go ahead with our deployment!</p>
<h3 id="heading-what-to-expect">What to expect</h3>
<p>You will deploy your project manually on Netlify, rename your site on the platform, and be able to have a live version of your project.</p>
<h2 id="heading-how-to-deploy-your-react-and-typescript-project">How to Deploy Your React and TypeScript Project</h2>
<h3 id="heading-1-open-up-your-existing-project-on-vscode">1. Open up your existing project on VSCode</h3>
<p>Open up your project in the code editor of your choice.</p>
<h3 id="heading-2-build-the-project">2. Build the project</h3>
<p>Open the terminal in VSCode and use the code below to build your project:</p>
<pre><code>npm run build
</code></pre><p>This should generate a <em>dist</em> folder in your root directory where your projects' minified version is created and stored.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/fig-2-0.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 2.0</strong> Running the project in the terminal which creates the dist folder in the project structure.</em></p>
<h3 id="heading-3-drag-and-drop-your-dist-folder-in-netlify">3. Drag and Drop your Dist Folder in Netlify</h3>
<p>On Netlify under Team Overview, click on the Add New Site button. It should have three options:</p>
<ol>
<li>Import an existing project</li>
<li>Start from a template</li>
<li>Deploy manually</li>
</ol>
<p>Select the third choice to deploy manually.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/fig-3-0.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 3.0</strong> Clicking on the Add new site button shows the three options to choose from. Select "Deploy Manually".</em></p>
<p>It should lead you to the page as seen in the below image:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/fig-3-1.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 3.1</strong> Drag &amp; drop view when choosing to deploy manually.</em></p>
<p>Click on the page and navigate into your project's file path.</p>
<p>Upload the dist folder that was previously generated in your project onto Netlify.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/fig-3-2.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 3.2</strong> Navigating into the project's folder &amp; uploading the dist folder onto Netlify.</em></p>
<p>It will take a few seconds or minutes to get your project deployed.</p>
<p>Once deployment is successful, you will see a page similar to the one below. By default, it gives a randomly generated subdomain name to your site's URL. For example, in my case, it is <em>delightful-pie-bba293.</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/fig-3-3.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 3.3</strong> Deployment is successful.</em></p>
<p>Your site's name is the subdomain of Netlify's domain.</p>
<pre><code>https:<span class="hljs-comment">//&lt;your-site-name&gt;.netlify.app</span>
</code></pre><h3 id="heading-4-rename-your-site">4. Rename your site</h3>
<p>Click on the Site Configuration that is on the lefthand sidebar.</p>
<p>In the Site Information under Site Details, click on the Change Site Name button.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/fig-4-0.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 4.0</strong> Viewing the Site Details under the Site Configuration.</em></p>
<p>This should give you a pop-up to change your site's name.</p>
<p>Change the name of your site to whatever you like:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/fig-4-1-1.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 4.1</strong> Changing the name of your site.</em></p>
<p>Head back to the Site Overview where you can find the URL of your site. Your site's URL is found right underneath your project's name.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/figure-4-2.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 4.2</strong> Site Overview where you can find your site's URL.</em></p>
<p>Click on the URL to view your site!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/fig-4-3-1.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 4.3</strong> Viewing my site from the newly created URL.</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Now, you have live versions of your projects and you're able to deploy them manually on Netlify. </p>
<p>There are additional steps to take in order to add a custom domain but we're not covering that in this tutorial. </p>
<p>This also makes it easier to reference your projects in the meantime on your résumés, portfolio site, or anywhere else.</p>
<p>Thanks for powering through this article and happy coding! 🩷</p>
<h3 id="heading-additional-resources">📝Additional Resources:</h3>
<ol>
<li>This article is a summarized version of this <a target="_blank" href="https://www.youtube.com/watch?v=7T4w0QJtL-o">video</a>. If you'd prefer to watch and follow along, then that is the video to watch.</li>
<li>There are many other platforms such as <a target="_blank" href="https://www.cloudflare.com/en-gb/">Cloudflare</a>, <a target="_blank" href="https://www.heroku.com/">Heroku</a>, or <a target="_blank" href="https://vercel.com/">Vercel</a> to deploy your projects on. This <a target="_blank" href="https://www.youtube.com/watch?v=gcwQg8-wqQ0">video</a>, for instance, shows you how to deploy your projects onto Vercel.</li>
</ol>
<h3 id="heading-connect-with-me">🔍Connect with me!</h3>
<p>Follow me on <a target="_blank" href="https://twitter.com/chelmerrox">X</a> and <a target="_blank" href="http://www.linkedin.com/in/losalini-rokocakau">LinkedIn</a> if you like my work and want to stay updated for more.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ One-Click AI Web Development Tutorial - Learn how to Turn Figma Designs into Working Code using AI [Full Course] ]]>
                </title>
                <description>
                    <![CDATA[ There are many ways that AI can help speed up web development. We just posted a course on the freeCodeCamp.org YouTube channel that will show you how to convert Figma designs into working code with just one click using AI. Ania Kubów developed this c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/ai-web-development-tutorial-figma-designs/</link>
                <guid isPermaLink="false">66b20062a2135cc2539a2113</guid>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Thu, 11 Apr 2024 14:12:38 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/locofy.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>There are many ways that AI can help speed up web development. We just posted a course on the freeCodeCamp.org YouTube channel that will show you how to convert Figma designs into working code with just one click using AI.</p>
<p>Ania Kubów developed this course. She is one of our most popular instructors. She will show you how to transform your Figma designs into code using Locofy, and also how to prepare to deploy the complete application.</p>
<p>You will learn to easily create an Airbnb clone. This app isn't just a static display of properties; it's a dynamic platform where users can sign up, sign in, and interact with property data in real-time. This course will take you from a raw design in Figma to a live application, covering every step in between.</p>
<h2 id="heading-course-contents">Course Contents</h2>
<p>The course starts with an introduction to Figma, a leading tool in collaborative web design that allows for real-time UI and UX development. You will then dive into the actual design of the 'localhost' app (that's the name of the Airbnb clone), laying the groundwork for the transformative steps ahead.</p>
<p>The heart of the course is the introduction to Locofy Lightning and LocoAI, tools that convert Figma designs into high-quality, production-ready frontend code. This AI-driven process is not only efficient but also adaptable, providing code that's ready for further customization if needed. Locofy provided a grant to make this course possible.</p>
<p>This tutorial isn't just about converting designs into code; it's about making that code functional and interactive. You'll learn how to sync the generated code to GitHub, integrate a database, set up authentication, and finally, deploy the app using Netlify.</p>
<p>With technologies like React for the frontend, Node.js for the backend, MongoDB for database management, and Netlify for deployment, you are in for a comprehensive development experience.</p>
<h2 id="heading-why-this-course">Why This Course?</h2>
<ol>
<li><strong>Hands-on Learning</strong>: From design to deployment, you'll get hands-on experience with every aspect of building a web application.</li>
<li><strong>AI-Powered Efficiency</strong>: Discover how AI can streamline the development process, turning complex designs into usable code in an instant.</li>
<li><strong>Expert Guidance</strong>: Ania Kubów, with her extensive experience and clear teaching style, will be your guide, ensuring you understand each step of the process.</li>
</ol>
<p>Whether you're a seasoned developer looking to integrate AI into your workflow or a beginner eager to explore the intersection of design and coding, this course is designed to offer valuable insights and practical skills. Watch the full course on <a target="_blank" href="https://youtu.be/-kLs1NGt3ys">the freeCodeCamp.org YouTube channel</a> (2-hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/-kLs1NGt3ys" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create Tables Using the React-Data-Table-Component Library in React & TypeScript ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, I'll teach you how to use the react-data-table-component library in your React projects. You'll learn how to render a table that has features such as pagination, searching/filtering, and sorting.  I'll walk you through each step, fr... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/create-tables-using-the-react-datatable-component-library/</link>
                <guid isPermaLink="false">66ba5222256e9dbeab31aa92</guid>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ user experience ]]>
                    </category>
                
                    <category>
                        <![CDATA[ User Interface ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Losalini Rokocakau ]]>
                </dc:creator>
                <pubDate>Wed, 27 Mar 2024 15:40:38 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/cover-image-21.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, I'll teach you how to use the <em>react-data-table-component</em> library in your React projects. You'll learn how to render a table that has features such as pagination, searching/filtering, and sorting. </p>
<p>I'll walk you through each step, from setting up a React and TypeScript project with Vite to using the <em>react-data-table-component</em> library to render a table.</p>
<p>To follow along with this tutorial, there are a few prerequisites:</p>
<ol>
<li>A basic understanding of React and TypeScript</li>
<li>Basic knowledge of Bootstrap, which we'll use for styling</li>
<li>For Windows OS users, know how to use the PowerShell terminal (as you'll need an interactive terminal to create the project with Vite)</li>
<li>Node v20.11.1 installed</li>
<li>npm v10.2.4 installed</li>
<li>A code editor such as Visual Studio Code (VS Code) or Atom</li>
</ol>
<p>Let's start creating the project!</p>
<h3 id="heading-what-will-we-build">What will we build</h3>
<p>By the end of this tutorial, you will have built a table that displays a person's ID, name, height, and eye color.</p>
<p>The table will also have a search bar where users can search for a person based on the value of any of the four properties mentioned above.</p>
<p>Each row in the table will be selectable and each column will be sortable when the column header is clicked by a user.</p>
<h2 id="heading-1-create-a-react-and-typescript-project">1. Create a React and TypeScript Project</h2>
<p>In the command line, create the project with the command below:</p>
<pre><code>npm create vite@latest
</code></pre><p>Name the project <code>react-data-table-tutorial</code> .</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/fig-1-0-1.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 1.0</strong> Creating the React &amp; TypeScript project with Vite on PowerShell command line. Naming the project react-data-table-tutorial.</em></p>
<p>Navigate to React with the up and down keys to select React. Choose React as the library you're going to use.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/fig-1-1-1.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 1.1</strong> Selecting React as our framework by navigating to it on the list with up &amp; down arrow keys on the keyboard.</em></p>
<p>Similar to the step above, navigate to TypeScript and choose it as the language to use.</p>
<p>The next step is to change directories into the project's folder. Once you've done that, open the project in your code editor as seen in Figure 1.2 below. I'll be using the VS Code editor in this tutorial.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/fig-1-2-2.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 1.2</strong> Changing the folder into the react-data-table-tutorial directory and opening the contents of the folder into a code editor.</em></p>
<h2 id="heading-2-remove-the-default-code-set-by-react">2. Remove the Default Code Set by React</h2>
<p>This step is just to remove any default code and stylings in the files found in the <em>src</em> folder. </p>
<p>First, remove all default styling in the <em>App.css</em> file and replace it with the stylings below.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">background-color</span>: white;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">160px</span> <span class="hljs-number">500px</span>;
}
</code></pre>
<p>Then remove the following from the <em>App.tsx</em> file:</p>
<ul>
<li>the imported statements of the <code>useState</code> hook, <code>reactLogo</code>, and the <code>viteLogo</code><em>.</em></li>
<li>The destructured array and <code>useState</code> hook for the count variable and <code>setCount</code> function.</li>
<li>The returned JSX wrapped within the fragment of the <code>App</code> component.</li>
</ul>
<p>The <code>App</code> component should look like the code-block below after all of those changes:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>;

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

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h2 id="heading-3-install-the-libraries-well-need">3. Install the Libraries We'll Need</h2>
<p>In the project, you will need to install a few libraries:</p>
<ol>
<li><em>styled-components</em> v3.23+</li>
<li><em>react-data-table-component</em> v16.8.0+</li>
<li><em>Bootstrap</em> v5.3.3</li>
</ol>
<p>You will need to install the <em>styled-components</em> library to use with the <em>react-data-table-component</em> library.</p>
<p>In the command line, install all of these by using the commands below:</p>
<pre><code>npm install styled-components
</code></pre><pre><code>npm install react-data-table-components
</code></pre><pre><code>npm install bootstrap@<span class="hljs-number">5.3</span><span class="hljs-number">.3</span>
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2024/03/fig-3-0.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 3.0</strong> Installing the libraries on Visual Studio Code's built-in terminal.</em></p>
<p>The installed libraries are listed under dependencies in the <em>package.json</em> file.</p>
<pre><code class="lang-json">{
   <span class="hljs-comment">// rest of the code in the file</span>
    <span class="hljs-attr">"dependencies"</span>: {
        <span class="hljs-attr">"boostrap"</span>: <span class="hljs-string">"^5.3.3"</span>,
        <span class="hljs-attr">"react"</span>: <span class="hljs-string">"^18.2.0"</span>,
        <span class="hljs-attr">"react-data-table-component"</span>: <span class="hljs-string">"^7.6.2"</span>,
        <span class="hljs-attr">"react-dom"</span>: <span class="hljs-string">"^18.2.0"</span>,
        <span class="hljs-attr">"styled-components"</span>: <span class="hljs-string">"^6.1.8"</span>,
    }
    <span class="hljs-comment">// rest of the code in the file</span>
}
</code></pre>
<h2 id="heading-4-import-bootstrap-in-the-app-component">4. Import Bootstrap in the App Component</h2>
<p>In the <em>App.tsx</em> file, import the Bootstrap library at the top of the file.</p>
<p>This will allow us to use Bootstrap stylings throughout the project.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">"./App.css"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"bootstrap/dist/js/bootstrap.bundle.min.js"</span>;

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

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h2 id="heading-5-create-a-table-component">5. Create a Table Component</h2>
<p>In the <em>src</em> folder, create a sub-directory and name it <em>components</em>. By convention, this is to hold all of the components of the project.</p>
<p>In the <em>components</em> folder, create a file called <em>Table.tsx</em>. This is for our <code>Table</code> component.</p>
<p>Create a function component called <code>Table</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/fig-4-0.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 5.0</strong> Create the Table component in the components sub-directory within the src folder.</em></p>
<h2 id="heading-6-import-the-react-data-table-component-library-to-start-using-it">6. Import the react-data-table-component Library to Start Using it</h2>
<p>Import the <em>react-data-table-component</em> library into the <code>Table</code> component.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> DataTable <span class="hljs-keyword">from</span> <span class="hljs-string">"react-data-table-component"</span>;

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

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Table;
</code></pre>
<h2 id="heading-7-create-the-table-in-the-table-component">7. Create the Table in the Table Component</h2>
<p>Create a <code>&lt;div&gt;</code> container within the fragment and add Bootstrap styling of <code>container</code> and <code>my-5</code> to place the table in the center of the page.</p>
<p>Add the <code>DataTable</code> component as the child of the <code>&lt;div&gt;</code> container.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> DataTable <span class="hljs-keyword">from</span> <span class="hljs-string">'react-data-table-component'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Table</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"container my-5"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">DataTable</span> /&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/&gt;</span></span>
    );
}
</code></pre>
<p>Pass the columns and rows of the table as props to the <code>DataTable</code> component.</p>
<p>The column headers of the table are objects that will be stored in an array. The rows of the table will also be stored in a similar way. The array of objects for both will have these structures:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> columns = [
    {
        <span class="hljs-attr">name</span>: <span class="hljs-string">"ID"</span>,
        <span class="hljs-attr">selector</span>: <span class="hljs-function"><span class="hljs-params">row</span> =&gt;</span> row.id
    },
    {
        <span class="hljs-attr">name</span>: <span class="hljs-string">"Full Name"</span>,
        <span class="hljs-attr">selector</span>: <span class="hljs-function"><span class="hljs-params">row</span> =&gt;</span> row.fullName
    },
    {
        <span class="hljs-attr">name</span>: <span class="hljs-string">"Height"</span>,
        <span class="hljs-attr">selector</span>: <span class="hljs-function"><span class="hljs-params">row</span> =&gt;</span> row.height
    },
    {
        <span class="hljs-attr">name</span>: <span class="hljs-string">"Weight"</span>,
        <span class="hljs-attr">selector</span>: <span class="hljs-function"><span class="hljs-params">row</span> =&gt;</span> row.weight
    },
];
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> rows = [
    {
        <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
        <span class="hljs-attr">fullName</span>: <span class="hljs-string">"John Doe"</span>,
        <span class="hljs-attr">height</span>: <span class="hljs-string">"1.75m"</span>,
        <span class="hljs-attr">weight</span>: <span class="hljs-string">"89kg"</span>,
    },
    {
        <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>,
        <span class="hljs-attr">fullName</span>: <span class="hljs-string">"Jane Doe"</span>,
        <span class="hljs-attr">height</span>: <span class="hljs-string">"1.64m"</span>,
        <span class="hljs-attr">weight</span>: <span class="hljs-string">"55kg"</span>,
    },
    {
        <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>,
        <span class="hljs-attr">fullName</span>: <span class="hljs-string">"Sheera Maine"</span>,
        <span class="hljs-attr">height</span>: <span class="hljs-string">"1.69m"</span>,
        <span class="hljs-attr">weight</span>: <span class="hljs-string">"74kg"</span>,
    },
];
</code></pre>
<p>These constants are then passed into the <code>DataTable</code> component as such:</p>
<pre><code class="lang-jsx">&lt;DataTable columns={columns} data={rows} /&gt;
</code></pre>
<p>Create a <code>columns</code> constant that is an array of objects that has four columns headers for <code>personID</code>, <code>fullName</code>, <code>height</code>, and <code>eyeColor</code>.</p>
<p>Create a <code>rows</code> constant that is an array of objects that has 15 objects which is equivalent to data for 15 people.</p>
<p>Pass the two constants into their respective props in the <code>DataTable</code> component as seen in the next code-block.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Table</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> columns = [
        {
            <span class="hljs-attr">name</span>: <span class="hljs-string">"ID"</span>,
            <span class="hljs-attr">selector</span>: <span class="hljs-function">(<span class="hljs-params">row</span>) =&gt;</span> row.personID,
        },
        {
            <span class="hljs-attr">name</span>: <span class="hljs-string">"Full Name"</span>,
            <span class="hljs-attr">selector</span>: <span class="hljs-function">(<span class="hljs-params">row</span>) =&gt;</span> row.fullName,
        },
        {
            <span class="hljs-attr">name</span>: <span class="hljs-string">"Height"</span>,
            <span class="hljs-attr">selector</span>: <span class="hljs-function">(<span class="hljs-params">row</span>) =&gt;</span> row.height,
        },
        {
            <span class="hljs-attr">name</span>: <span class="hljs-string">"eyeColor"</span>,
            <span class="hljs-attr">selector</span>: <span class="hljs-function">(<span class="hljs-params">row</span>) =&gt;</span> row.eyeColor,
        },
    ];

    <span class="hljs-keyword">const</span> rows = [
        {
           <span class="hljs-attr">personID</span>: <span class="hljs-number">1</span>,
           <span class="hljs-attr">fullName</span>: <span class="hljs-string">"Kate Shein"</span>,
           <span class="hljs-attr">height</span>: <span class="hljs-string">"1.79m"</span>,
           <span class="hljs-attr">eyeColor</span>: <span class="hljs-string">"blue"</span>,
        },
        <span class="hljs-comment">//....remaining objects for the 2nd to 14th person</span>
        {
           <span class="hljs-attr">personID</span>: <span class="hljs-number">15</span>,
           <span class="hljs-attr">fullName</span>: <span class="hljs-string">"Isabella Thompson"</span>,
           <span class="hljs-attr">height</span>: <span class="hljs-string">"1.79m"</span>,
           <span class="hljs-attr">eyeColor</span>: <span class="hljs-string">"blue"</span>,
        },
    ];
}
</code></pre>
<p>You will also add the <code>fixedHeader</code> prop to the <code>DataTable</code> component to keep the column header fixed when a user scrolls down the table that has more than 10 records.</p>
<p>Give the table a title by passing the <code>title</code> prop to the component and its value is whatever you would like to call your table.</p>
<pre><code class="lang-javascript">&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"container"</span>&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">DataTable</span> 
        <span class="hljs-attr">columns</span>=<span class="hljs-string">{columns}</span> 
        <span class="hljs-attr">data</span>=<span class="hljs-string">{rows}</span> 
        <span class="hljs-attr">fixedHeader</span>
        <span class="hljs-attr">title</span>=<span class="hljs-string">"React-Data-Table-Component Tutorial."</span>
     /&gt;</span></span>
&lt;/div&gt;
</code></pre>
<p>Back in the <code>App</code> component, import the <code>Table</code> component and place it within the fragment.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">"./App.css"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"bootstrap/dist/js/bootstrap.bundle.min.js"</span>;
<span class="hljs-keyword">import</span> Table <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/Table"</span>;

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

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h2 id="heading-8-add-pagination-and-sorting-and-make-each-row-selectable">8. Add Pagination and Sorting, and Make Each Row Selectable</h2>
<h3 id="heading-pagination-and-selectablerows">Pagination and <code>selectableRows</code></h3>
<p>Add the <code>pagination</code> and <code>selectableRows</code> props to the <code>DataTable</code> component.</p>
<p>By default, the first page has the first 10 records. If there needs to be API calls from the server side for custom pagination, then you can use the <code>paginationServer</code> property along with the <code>paginationTotalRows</code><em>,</em> <code>onChangeRowsPerPage</code> and <code>onChangePage</code> properties which work in conjunction with a few other things.</p>
<p>But for now, let's stick with the <code>pagination</code> property.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">//...rest of the code in the function component</span>
&lt;div className=<span class="hljs-string">"container d-flex justify-content-center my-5"</span>&gt;
   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">DataTable</span>
        <span class="hljs-attr">columns</span>=<span class="hljs-string">{columns}</span>
        <span class="hljs-attr">data</span>=<span class="hljs-string">{rows}</span>
        <span class="hljs-attr">fixedHeader</span>
        <span class="hljs-attr">title</span>=<span class="hljs-string">"React-Data-Table-Component Tutorial"</span>
        <span class="hljs-attr">pagination</span>
        <span class="hljs-attr">selectableRows</span>
    /&gt;</span></span>
&lt;/div&gt;
<span class="hljs-comment">//...rest of the code in the function component</span>
</code></pre>
<h3 id="heading-sorting">Sorting</h3>
<p>In the <code>DataTable</code> component, add the <code>sortable</code> property to each object in the <code>columns</code> constant. Give it a boolean value of <code>true</code> so that sorting is applied to each column when a user clicks on the column headers.</p>
<pre><code class="lang-typescript"><span class="hljs-comment">//...rest of the code in the function component</span>
<span class="hljs-keyword">const</span> columns = [
    {
        name: <span class="hljs-string">'ID'</span>,
        selector: <span class="hljs-function">(<span class="hljs-params">row</span>) =&gt;</span> row.personID,
        sortable: <span class="hljs-literal">true</span>,
    },
    {
        name: <span class="hljs-string">'Full Name'</span>,
        selector: <span class="hljs-function">(<span class="hljs-params">row</span>) =&gt;</span> row.fullName,
        sortable: <span class="hljs-literal">true</span>,
    },
    {
        name: <span class="hljs-string">'Height'</span>,
        selector: <span class="hljs-function">(<span class="hljs-params">row</span>) =&gt;</span> row.height,
        sortable: <span class="hljs-literal">true</span>,
    },
    {
        name: <span class="hljs-string">'Eye Color'</span>,
        selector: <span class="hljs-function">(<span class="hljs-params">row</span>) =&gt;</span> row.eyeColor,
        sortable: <span class="hljs-literal">true</span>,
    },
];
<span class="hljs-comment">//...rest of the code in the function component</span>
</code></pre>
<h2 id="heading-9-add-searching-and-filtering">9. Add Searching and Filtering</h2>
<p>Add a <code>&lt;div&gt;</code> container above the <code>DataTable</code> component in the returned JSX. Also add the bootstrap <code>input-group</code> class to the <code>&lt;div&gt;</code>.</p>
<p>The child element of this new container will be the <code>&lt;input /&gt;</code> of type <code>search</code> and we'll use Bootstraps' stylings for it. Use the code below:</p>
<pre><code class="lang-jsx">&lt;input
    type=<span class="hljs-string">"search"</span>
    className=<span class="hljs-string">"form-control-sm border ps-3"</span>
    placeholder=<span class="hljs-string">"Search"</span>
/&gt;
</code></pre>
<p>An optional step is to add a search icon or use <a target="_blank" href="https://getbootstrap.com/docs/5.3/forms/input-group/">Bootstraps' default styling</a> for a search bar. However, we'll leave it out for now so we can focus solely on the searching functionality.</p>
<p>Now, let's import the <code>useState</code> hook into the <em>Table.tsx</em> file.</p>
<p>Use the hook and pass in the <code>rows</code> constant as the default value of our state variable. Within the destructured array will be our state variable called <code>data</code> and the setter function called <code>setData</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> [data, setData] = useState(rows);
</code></pre>
<p>Create a function called <code>handleSearch</code> that will be called when the <code>onChange</code> event listener is used on the search bar. </p>
<p>Pass in the event object, <code>e</code>, as its argument. Using type annotation, set the type of the event object to <code>React.ChangeEvent&lt;HTMLInputElement&gt;</code>.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> handleSearch = <span class="hljs-function">(<span class="hljs-params">e: React.ChangeEvent&lt;HTMLInputElement&gt;</span>) =&gt;</span> {
   <span class="hljs-comment">// the rest of the code will be defined in here</span>
};
</code></pre>
<p>Declare 5 variables of Boolean type as seen below:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> handleSearch = <span class="hljs-function">(<span class="hljs-params">e: React.ChangeEvent&lt;HTMLInputElement&gt;</span>) =&gt;</span> {
   <span class="hljs-keyword">let</span> searchValue: <span class="hljs-built_in">Boolean</span>;
   <span class="hljs-keyword">let</span> personIDValue: <span class="hljs-built_in">Boolean</span>;
   <span class="hljs-keyword">let</span> fullNameValue: <span class="hljs-built_in">Boolean</span>;
   <span class="hljs-keyword">let</span> heightValue: <span class="hljs-built_in">Boolean</span>;
   <span class="hljs-keyword">let</span> eyeColorValue: <span class="hljs-built_in">Boolean</span>;
};
</code></pre>
<p>Declare a new local constant called <code>newRows</code><em>.</em> In this constant, filter out and return the rows/data in the <em>rows</em> constant where the search input's value is the same as the value of the rows' <code>fullName</code> or <code>height</code> or <code>eyeColor</code> property.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> newRows = rows.filter(<span class="hljs-function">(<span class="hljs-params">row</span>) =&gt;</span> {
      personIDValue = row.personID
        .toString()
        .toLowerCase()
        .includes(e.target.value.toLowerCase());
      fullNameValue = row.fullName
        .toLowerCase()
        .includes(e.target.value.toLowerCase());
      heightValue = row.height
        .toLowerCase()
        .includes(e.target.value.toLowerCase());
      eyeColorValue = row.eyeColor
        .toLowerCase()
        .includes(e.target.value.toLowerCase());

      <span class="hljs-keyword">if</span> (personIDValue) {
        searchValue = personIDValue;
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (fullNameValue) {
        searchValue = fullNameValue;
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (heightValue) {
        searchValue = heightValue;
      } <span class="hljs-keyword">else</span> {
        searchValue = eyeColorValue;
      }

      <span class="hljs-keyword">return</span> searchValue;
});
</code></pre>
<p>Pass <code>newRows</code> into the setter function, <code>setData</code><em>.</em></p>
<pre><code class="lang-typescript">setData(newRows);
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-comment">// definition of the columns constant</span>

<span class="hljs-comment">// definition of the rows constant</span>

<span class="hljs-keyword">const</span> [data, setData] = useState(rows);

<span class="hljs-comment">// Handle Search</span>
<span class="hljs-keyword">const</span> handleSearch = <span class="hljs-function">(<span class="hljs-params">e: React.ChangeEvent&lt;HTMLInputElement&gt;</span>) =&gt;</span> {
    <span class="hljs-keyword">let</span> searchValue: <span class="hljs-built_in">Boolean</span>;
    <span class="hljs-keyword">let</span> personIDValue: <span class="hljs-built_in">Boolean</span>;
    <span class="hljs-keyword">let</span> fullNameValue: <span class="hljs-built_in">Boolean</span>;
    <span class="hljs-keyword">let</span> heightValue: <span class="hljs-built_in">Boolean</span>;
    <span class="hljs-keyword">let</span> eyeColorValue: <span class="hljs-built_in">Boolean</span>;

    <span class="hljs-keyword">const</span> newRows = rows.filter(<span class="hljs-function">(<span class="hljs-params">row</span>) =&gt;</span> {
      personIDValue = row.personID
        .toString()
        .toLowerCase()
        .includes(e.target.value.toLowerCase());
      fullNameValue = row.fullName
        .toLowerCase()
        .includes(e.target.value.toLowerCase());
      heightValue = row.height
        .toLowerCase()
        .includes(e.target.value.toLowerCase());
      eyeColorValue = row.eyeColor
        .toLowerCase()
        .includes(e.target.value.toLowerCase());

      <span class="hljs-keyword">if</span> (personIDValue) {
        searchValue = personIDValue;
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (fullNameValue) {
        searchValue = fullNameValue;
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (heightValue) {
        searchValue = heightValue;
      } <span class="hljs-keyword">else</span> {
        searchValue = eyeColorValue;
      }

      <span class="hljs-keyword">return</span> searchValue;
    });

    setData(newRows);
};
</code></pre>
<p>Next step is to pass (not call the function) the <code>handleSearch</code> function into the <code>onChange</code> event listener. </p>
<pre><code class="lang-jsx">&lt;input
   type=<span class="hljs-string">"search"</span>
   className=<span class="hljs-string">"form-control-sm border ps-3"</span>
   placeholder=<span class="hljs-string">"Search"</span>
   onChange={handleSearch}
/&gt;
</code></pre>
<p>The value of the data property in the <code>DataTable</code> component will now be the state variable, <code>data</code> instead of <code>rows</code> that was initially passed in.</p>
<pre><code class="lang-jsx">&lt;DataTable
    columns={columns}
    data={data}
    fixedHeader
    title=<span class="hljs-string">"React-Data-Table-Component Tutorial."</span>
    pagination
    selectableRows
/&gt;
</code></pre>
<h2 id="heading-10-view-the-table">10. View the Table</h2>
<p>Run the project in the command line and view the table in a browser:</p>
<p><code>command line
npm run dev</code></p>
<p>The table should look something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/final-result-table.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Figure 11.0</strong> Preview of the resulting table created.</em></p>
<p>You can read through the <a target="_blank" href="https://react-data-table-component.netlify.app/?path=/docs/getting-started-intro--docs">documentation</a> for <em>react-data-table-component</em> as it has more in-depth coverage of the library's usage that goes beyond the scope of this article. </p>
<p>Don't fret if there's a difference in your table from the expected result. The source code in <a target="_blank" href="https://github.com/chelmerrox/react-data-table-tutorial">this repository</a> will guide you.</p>
<p>Happy coding and may your code run smoothly!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Best CSS Frameworks to Use in Your Projects ]]>
                </title>
                <description>
                    <![CDATA[ By Victor Ikechukwu CSS has come a long way over the past few years. In the past, you'd use CSS to create simple-looking web applications that rely on HTML tables and CSS floats as their layout systems. And now you can architect complex interactive u... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/best-css-frameworks-for-frontend-devs/</link>
                <guid isPermaLink="false">66d46171677cb8c6c15f317b</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS Framework ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 13 Feb 2024 21:18:47 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/BEST-CSS.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Victor Ikechukwu</p>
<p>CSS has come a long way over the past few years. In the past, you'd use CSS to create simple-looking web applications that rely on HTML tables and CSS floats as their layout systems. And now you can architect complex interactive user interfaces that are appealing with elegant designs.</p>
<p>But as advanced as CSS has become, writing out CSS styles from scratch for extensive web applications can be time-consuming. It can also lead to the repetition of styles, longer CSS files, cross-browser compatibility errors, and generally a more complex codebase.</p>
<p>To solve this challenge, CSS frameworks emerged as a solution. CSS frameworks introduced a means for developers to adopt a set of pre-defined and standardized CSS styles and components to create consistent, appealing, and responsive user interfaces.</p>
<p>But with so many CSS frameworks to choose from, deciding on the right framework for your application can be difficult. You'll want to conduct a proper comparison that accounts for the overall features of each CSS framework, so you can choose the most suitable option that fits your needs.</p>
<p>In this article, we’ll explore what CSS frameworks are, their benefits and limitations, and how you can get started using them. We’ll also look at the most prominent and used CSS frameworks you should know.</p>
<p>In the end, you'll have a good sense of how CSS frameworks work and which to use to meet your project's needs. Let's get started.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-css-frameworks">What are CSS Frameworks?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-should-you-use-css-frameworks">Why Should You Use CSS Frameworks?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-css-frameworks">Types of CSS Frameworks</a></p>
</li>
</ul>
<ul>
<li><a class="post-section-overview" href="#heading-9-css-frameworks-you-should-know">9 CSS Frameworks You Should Know</a></li>
</ul>
<ul>
<li><p><a class="post-section-overview" href="#heading-bootstrap">Bootstrap</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-tailwind-css">Tailwind CSS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-material-ui">Material UI</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-styled-components">styled-components</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-foundation">Foundation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-chakra-ui">Chakra UI</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-emotion">Emotion</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-bulma">Bulma</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-pure-css">Pure CSS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-choose-the-right-css-framework-for-your-project">How to Choose the Right CSS Framework for Your Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-final-thoughts">Final Thoughts</a></p>
</li>
</ul>
<h2 id="heading-what-are-css-frameworks">What are CSS Frameworks?</h2>
<p>CSS frameworks are a set of pre-written and ready-to-use CSS styles and stylesheets that provide a set of styles and components for styling markup. They streamline the development process by offering a foundation of reusable CSS styles for common design elements and layouts.</p>
<p>CSS frameworks are used to create familiar and consistent user interfaces, simplify responsive design, and enhance collaboration among development teams.</p>
<h2 id="heading-why-should-you-use-css-frameworks">Why Should You Use CSS Frameworks?</h2>
<p>CSS frameworks offer numerous benefits that make them indispensable tools for web development. Here are some advantages that CSS frameworks provide:</p>
<p><strong>Faster development time</strong>: CSS frameworks come with pre-built components and styles, eliminating the need to write everything from scratch. This speeds up the development process and allows developers to focus on customizing and fine-tuning specific aspects of their projects rather than building from scratch.</p>
<p><strong>Consistent style and design</strong>: CSS frameworks help provide a cohesive and consistent look across different components and pages. They ensure that all styles, UI elements, buttons, and typography maintain a unified design language, saving developers from spending excessive time on styling and ensuring a better user experience.</p>
<p><strong>Improve collaboration and maintainability</strong>: CSS frameworks usually offer well-documented libraries and established conventions, making it easier for developers to collaborate and maintain codebases. With a common codebase and extensive documentation, developers can easily understand and work with each other's code.</p>
<h2 id="heading-types-of-css-frameworks">Types of CSS Frameworks</h2>
<p>CSS frameworks aren’t a one-size-fits-all. They come in different forms, and each category has its own focus and advantages. Knowing the categories CSS frameworks can fit into will be helpful in letting you know what to expect from each framework.</p>
<p>Let's look at the main types of CSS frameworks now.</p>
<h3 id="heading-component-based-frameworks">Component-Based Frameworks</h3>
<p>This is the origin of CSS frameworks. Component-based frameworks offer a set of pre-built UI components that developers can plug into their applications to assemble interfaces quickly. The goal is to provide a modular and reusable design system that can help you create consistent and visually appealing web apps without starting from scratch every time.</p>
<h3 id="heading-utility-first-frameworks">Utility-First Frameworks</h3>
<p>The idea behind utility-first frameworks is that CSS should not be descriptive and should not heavily rely on your markup (for example, a “.header” class that signifies a navigation bar or website's header), but instead should be based on functionality (for example, “.text-align-center”).</p>
<p>Rather than confining your application’s design to only what is provided by the framework, utility-first frameworks offer CSS styles and classes that only do one thing (or a small set of things) as building blocks to extend and customize the design of your application beyond the limitations of a component-based framework.</p>
<h3 id="heading-css-in-js">CSS-in-JS</h3>
<p>With the rise of JavaScript libraries like React, CSS-in-JS frameworks were created to let developers manipulate styles directly in JavaScript by including CSS in their JavaScript markup.</p>
<p>CSS-in-JS utilizes the dynamic nature of JavaScript to provide a way of writing interactive CSS styles that are performant and based on user data and interactions.</p>
<p>There are more types of CSS frameworks available, but these three categories cover the most notable groups.</p>
<p>Note that there isn’t a fine line that separates these concerns. Most CSS frameworks can overlap into multiple categories – for example, a component-based framework can give you utilities, and a utility-based framework can give you components as well</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/screely-1707158060937-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>A diagram showing some categories of CSS frameworks and how the intertwine with each other</em></p>
<p>For example, consider the diagram above that shows how the three categories of CSS frameworks can intertwine.</p>
<h2 id="heading-9-css-frameworks-you-should-know">9 CSS Frameworks You Should Know</h2>
<p>Now that you have a clear understanding of what CSS frameworks are and their different types, let's have a look at some of the most prominent and most-used CSS frameworks you should know.</p>
<h2 id="heading-bootstrap">Bootstrap</h2>
<p>Bootstrap began as an internal tool at X (formerly, Twitter) to maintain a consistent look across the platform. Then it was open-sourced in 2011 for the wider web development community to use. <a target="_blank" href="https://getbootstrap.com/">Bootstrap</a> is one of the most widely used CSS frameworks, with a focus on responsive, mobile-first web design.</p>
<p>Bootstrap offers a robust collection of CSS and JavaScript components, such as its grid system and responsive UI components like buttons, navigation menus, and forms, that streamline the process of building clean and consistent web layouts.</p>
<p>Bootstrap has large community support and over a hundred thousand GitHub stars. And though it may seem bulky when compared to modern options, it's still one of the most used CSS frameworks you can use to build good-looking and thematically coherent web applications without needing to be an expert in CSS and web design.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/getbootstrap.com_-1.png" alt="alt_text" width="600" height="400" loading="lazy"></p>
<p><em>An image of the Bootstrap framework official website</em></p>
<h3 id="heading-how-to-use-bootstrap">How to use Bootstrap</h3>
<p>To get started with Bootstrap, you need to pull its source files into your project. In a JavaScript framework like React, you can install Bootstrap into your project using a package manager like npm.</p>
<pre><code class="lang-javascript">npm install bootstrap
</code></pre>
<p>Next, import Bootstrap’s CSS at the top of your application's main entry file, typically <code>src/index.js</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">'bootstrap/dist/css/bootstrap.min.css'</span>;
</code></pre>
<p>This will import Bootstrap CSS and make it available for use throughout your application. Now you can use Bootstrap components in your application like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">return</span> (

    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"container"</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello, Bootstrap in React!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"btn btn-primary"</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></span>

  );

}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>To learn more about Bootstrap, refer to the <a target="_blank" href="https://getbootstrap.com/docs/5.0/getting-started/introduction/">official Bootstrap documentation</a> for detailed guidance, examples, and additional resources.</p>
<h2 id="heading-tailwind-css">Tailwind CSS</h2>
<p><a target="_blank" href="https://github.com/tailwindlabs/tailwindcss">Tailwind CSS</a> is a utility-first CSS framework that allows you to rapidly build custom user interfaces directly in markup files.</p>
<p>As a utility-first framework, Tailwind abstracts from the constraints of a component-based framework, for example, Bootstrap.</p>
<p>Though component-based frameworks like Bootstrap excel at streamlining the process of building web layouts by providing pre-defined UI components, they’re opinionated in that you’re confined to the current design system and ecosystem of the framework. Trying to extend or customize your application’s layout beyond what the framework provides can prove to be a workaround.</p>
<p>Tailwind offers a robust system of utility and helper classes as building blocks that can be composed to build any design directly in your markup. With <a target="_blank" href="https://2023.stateofcss.com/en-US/css-frameworks/">Tailwind ranking as the second most used framework in the State of CSS 2023 survey at about 76%</a>, it's the best choice to rapidly prototype and speed up the development process in line with modern web standards.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/tailwindcss.com_-1.png" alt="alt_text" width="600" height="400" loading="lazy"></p>
<p><em>An image of the Tailwind CSS framework official website</em></p>
<h3 id="heading-how-to-use-tailwind-css">How to use Tailwind CSS</h3>
<p>Install <code>tailwindcss</code> via a package manager, and create your <code>tailwind.config.js</code> file to configure and customize Tailwind CSS for your application.</p>
<pre><code class="lang-javascript">npm install -D tailwindcss

npx tailwindcss init
</code></pre>
<p>Add the paths to all your template and markup files in your <code>tailwind.config.js</code> file as well as other configurations.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/** <span class="hljs-doctag">@type <span class="hljs-type">{import('tailwindcss').Config}</span> </span>*/</span>

<span class="hljs-built_in">module</span>.exports = {

  <span class="hljs-attr">content</span>: [<span class="hljs-string">"./src/**/*.{html,js,jsx,ts,tsx}"</span>],

  <span class="hljs-attr">theme</span>: {

    <span class="hljs-attr">extend</span>: {},

  },

  <span class="hljs-attr">plugins</span>: [],

}
</code></pre>
<p>Add the<code>@tailwind</code> directives for each of Tailwind’s layers to your main CSS file and ensure the CSS file is imported into the main entry file of your application.</p>
<pre><code class="lang-javascript">@tailwind base;

@tailwind components;

@tailwind utilities;
</code></pre>
<p>Now you can apply utility classes directly in your HTML markup to style your components.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Button</span>(<span class="hljs-params">{children}</span>) </span>{

  <span class="hljs-keyword">return</span> (

      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded"</span>&gt;</span>

        {children}

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

  );

}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Button;
</code></pre>
<p>You can learn more about setting up and using Tailwind CSS based on your project environment and advanced usage by going through the <a target="_blank" href="https://tailwindcss.com/docs/installation/framework-guides">official Tailwind CSS documentation</a>.</p>
<h2 id="heading-material-ui">Material UI</h2>
<p>Material UI is a component-based CSS framework for building user interfaces in React applications. It is based on Google's open-source design system, <a target="_blank" href="https://m3.material.io/">Material Design</a>, and provides a rich collection of pre-built components and styles.</p>
<p>As one of the <a target="_blank" href="https://github.com/mui/material-ui">largest UI communities</a> in the React ecosystem, Material UI offers a modern and visually appealing design system. It features a suite of customization options that make it easy for developers to implement custom design systems on top of the library, making it a popular choice for creating consistent UIs in React applications.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/mui.com_.png" alt="alt_text" width="600" height="400" loading="lazy"></p>
<p><em>An image of the MUI kit official website</em></p>
<h3 id="heading-how-to-use-material-ui">How to use Material UI</h3>
<p>Install Material UI's core package and any <a target="_blank" href="https://mui.com/material-ui/getting-started/installation/">additional dependencies</a> you need.</p>
<pre><code class="lang-javascript">npm install @mui/material @emotion/react @emotion/styled
</code></pre>
<p>Now you can Import any Material UI component into your React components and use them in your JSX code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> Button <span class="hljs-keyword">from</span> <span class="hljs-string">'@mui/material/Button'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ButtonUsage</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">variant</span>=<span class="hljs-string">"contained"</span>&gt;</span>Hello world<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span></span>;

}
</code></pre>
<p>Checkout <a target="_blank" href="https://mui.com/">Material UI documentation</a> for detailed usage guidelines, API references, and examples</p>
<h2 id="heading-styled-components">styled-components</h2>
<p><a target="_blank" href="https://styled-components.com/">styled-components</a> is one of the most prominent CSS-in-JS libraries. It provides a seamless way to create and manage CSS styles within JavaScript files and components.</p>
<p>While it was originally designed specifically for the React ecosystem, styled-components have advanced so that you can now use it with vanilla JavaScript or other JavaScript frameworks like Vue.</p>
<p>As the <a target="_blank" href="https://2023.stateofcss.com/en-US/css-in-js/">most popular CSS-in-JS library by GitHub stars and weekly NPM downloads</a>, styled-components offers a highly flexible and intuitive approach to styling, making it easier to build reusable and self-contained UI components.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/styled-components.com_.png" alt="alt_text" width="600" height="400" loading="lazy"></p>
<p><em>An image of the Styled-components official website</em></p>
<h3 id="heading-how-to-use-styled-components">How to use styled-components</h3>
<p>Install the styled-components package via npm or yarn.</p>
<pre><code class="lang-javascript">npm install styled-component
</code></pre>
<p>Now, you can define your styled components by importing the styled function and using it to create styled versions of HTML elements or custom components.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> styled, { css } <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>

<span class="hljs-keyword">const</span> Title = styled.h1<span class="hljs-string">`

  font-size: 1.5em;

  text-align: center;

  color: #BF4F74;

`</span>;

render(

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

    Title&gt;

      Hello World!

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

  &lt;/div&gt;

);
</code></pre>
<p>Refer to the official <a target="_blank" href="https://styled-components.com/">styled-components documentation</a> for comprehensive guides, examples, and advanced features.</p>
<h2 id="heading-foundation">Foundation</h2>
<p><a target="_blank" href="https://get.foundation/">Foundation</a> is the closest alternative to Bootstrap. It's not just a CSS framework, but a comprehensive toolkit for <a target="_blank" href="https://get.foundation/sites.html">styling web applications</a>, architecting <a target="_blank" href="https://get.foundation/emails.html">email templates</a>, which are known to be notoriously hard, and <a target="_blank" href="https://zurb.com/playground/motion-ui">integrating with ZURB’s Motion UI</a> to create advanced CSS animations.</p>
<p>It includes common UI components like Bootstrap but is more utility-focused and gives developers more options for customizing components. With almost too many features, it can be considerably more complex and harder to fully understand how everything works compared to other frameworks.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/get.foundation_.png" alt="alt_text" width="600" height="400" loading="lazy"></p>
<p><em>An image of the Foundation framework official website</em></p>
<h3 id="heading-how-to-use-foundation">How to use Foundation</h3>
<p>You can install Foundation in your project with a package manager.</p>
<pre><code class="lang-javascript">npm install foundation-sites
</code></pre>
<p>Now you can use its styles and components in your application.</p>
<pre><code class="lang-javascript">&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"card"</span> style=<span class="hljs-string">"width: 300px;"</span>&gt;

  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card-divider"</span>&gt;</span>

    This is a header

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

  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"assets/img/generic/rectangle-1.jpg"</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"card-section"</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">h4</span>&gt;</span>This is a card.<span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>It has an easy to override visual style.<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">div</span>&gt;</span></span>
</code></pre>
<p>Consult <a target="_blank" href="https://get.foundation/frameworks-docs.html">Foundation’s official documentation</a> for detailed instructions, examples, and additional resources.</p>
<h2 id="heading-chakra-ui">Chakra UI</h2>
<p>The brainchild of Nigerian developer Segun Adebayo, <a target="_blank" href="https://chakra-ui.com/">Chakra UI</a> falls into the same category as MUI as a component library and CSS framework for React applications. It emphasizes accessibility, developer ergonomics, and a customizable design system.</p>
<p>Chakra UI provides a collection of well-designed and accessible components that can be easily customized to match your project's branding and style.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/chakra-ui.com_--1-.png" alt="alt_text" width="600" height="400" loading="lazy"></p>
<p><em>An image of the Chakra CSS framework official website</em></p>
<h3 id="heading-how-to-use-chakra-ui">How to use Chakra UI</h3>
<p>To get started, install the Chakra UI package via a package manager.</p>
<pre><code class="lang-javascript">npm i @chakra-ui/react @emotion/react @emotion/styled framer-motion
</code></pre>
<p>After installing Chakra UI, you need to wrap your application or specific components with the <code>ChakraProvider</code> to make the Chakra UI components available.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-comment">// 1. import `ChakraProvider` component</span>

<span class="hljs-keyword">import</span> { ChakraProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">'@chakra-ui/react'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-comment">// 2. Wrap ChakraProvider at the root of your app</span>

  <span class="hljs-keyword">return</span> (

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

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

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

  )

}
</code></pre>
<p>Now you can use Chakra UI's components in your JSX code to build your user interface.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { Button} <span class="hljs-keyword">from</span> <span class="hljs-string">'@chakra-ui/react'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ButtonUsage</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">colorScheme</span>=<span class="hljs-string">'blue'</span>&gt;</span>Hello world<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span></span>;

}
</code></pre>
<p>To learn more, you can check out the <a target="_blank" href="https://chakra-ui.com/">Chakra UI documentation</a> for detailed usage guidelines, component examples, and theming options</p>
<h2 id="heading-emotion">Emotion</h2>
<p><a target="_blank" href="https://emotion.sh/">Emotion</a> is built off the concepts of styled-components to be a more performant, lightweight, and feature-rich CSS-in-JS library. It does this by utilizing features such as source maps, labels, and testing utilities.</p>
<p>Emotion is framework-agnostic and has a syntax that is as close to CSS as possible, making it easier to adopt.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-12-at-1.35.08-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Image of the Emotion homepage</em></p>
<h3 id="heading-how-to-use-emotion">How to use Emotion</h3>
<p>The <a target="_blank" href="https://www.npmjs.com/package/@emotion/css">@emotion/css</a> package is framework-agnostic and it's the simplest way to use Emotion. To get started, install the package via a package manager.</p>
<pre><code class="lang-javascript">npm i @emotion/css
</code></pre>
<p>Now you can use Emotion's CSS API to generate and compose CSS styles.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { css } <span class="hljs-keyword">from</span> <span class="hljs-string">'@emotion/css'</span>

<span class="hljs-keyword">const</span> color = <span class="hljs-string">'white'</span>

render(

  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>

    <span class="hljs-attr">className</span>=<span class="hljs-string">{css</span>`

      <span class="hljs-attr">padding:</span> <span class="hljs-attr">32px</span>;

      <span class="hljs-attr">background-color:</span> <span class="hljs-attr">hotpink</span>;

      <span class="hljs-attr">font-size:</span> <span class="hljs-attr">24px</span>;

      <span class="hljs-attr">border-radius:</span> <span class="hljs-attr">4px</span>;

      &amp;<span class="hljs-attr">:hover</span> {

        <span class="hljs-attr">color:</span> ${<span class="hljs-attr">color</span>};

      }

    `}

  &gt;</span>

    Hover to change color.

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

)
</code></pre>
<p>Refer to the official <a target="_blank" href="https://emotion.sh/docs/introduction">Emotion documentation</a> for detailed instructions, usage examples, and advanced features.</p>
<h2 id="heading-bulma">Bulma</h2>
<p><a target="_blank" href="https://bulma.io/">Bulma</a> is a modern and lightweight CSS framework that offers a flexible grid system and a variety of CSS styles and components. It focuses on simplicity, modularity, and ease of use.</p>
<p>Bulma emphasizes that it is "environment agnostic," meaning that it is just the style layer on top of the logic, so it integrates capably with any JS environment.</p>
<p>Bulma is more of a collection of CSS classes than UI components. It has a clean and intuitive syntax and is less complex and easier to understand compared to other component-based frameworks like Foundation and Bootstrap. This makes it an ideal choice for beginners or developers who value simplicity and want to quickly build responsive websites.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/bulma.io_.png" alt="alt_text" width="600" height="400" loading="lazy"></p>
<p><em>An image of the Bulma CSS framework official website</em></p>
<h3 id="heading-how-to-use-bulma">How to use Bulma</h3>
<p>To get started, you need to download Bulma for your project.</p>
<pre><code class="lang-javascript">npm install bulma
</code></pre>
<p>Next, import Bulma CSS styles into your project's main stylesheet.</p>
<pre><code class="lang-javascript">@<span class="hljs-keyword">import</span> <span class="hljs-string">'bulma/css/bulma.css'</span>;
</code></pre>
<p>Now, you're ready to start styling your project using Bulma's classes and components.</p>
<p>You can learn more about customizing Bulma's styles, overriding CSS variables, or modifying the Sass source files from <a target="_blank" href="https://bulma.io/documentation/">the official documentation</a>.</p>
<h2 id="heading-pure-css">Pure CSS</h2>
<p><a target="_blank" href="https://purecss.io/">Pure CSS</a> is a minimalistic and lightweight CSS framework that aims to provide a set of small, responsive CSS modules and styles as a starting point for styling web applications without imposing any design decisions. It has one of the smallest bundle sizes of 3.5KB (compressed) when all modules are used.</p>
<p>Pure CSS is suitable for projects where a minimal design approach is desired or when you prefer to write your styles from scratch.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/pure-css.png" alt="alt_text" width="600" height="400" loading="lazy"></p>
<p><em>An image of the Pure.CSS official website</em></p>
<h3 id="heading-how-to-use-pure-css">How to use Pure CSS</h3>
<p>You can add Pure CSS to your page via the free jsDelivr CDN. Add the following <code>&lt;link&gt;</code> element to your page's <code>&lt;head&gt;</code>, before your project's stylesheets.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://cdn.jsdelivr.net/npm/purecss@3.0.0/build/pure-min.css"</span> <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha384-X38yfunGUhNzHpBaEBsWLO+A0HDYOQi8ufWDkZ0k9e0eXz/tH3II7uKZ9msv++Ls"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;</span>
</code></pre>
<p>Refer to the official <a target="_blank" href="https://purecss.io/">Pure CSS documentation</a> for detailed usage guidelines, examples, and additional resources.</p>
<h2 id="heading-how-to-choose-the-right-css-framework-for-your-project">How to Choose the Right CSS Framework for Your Project</h2>
<p>As your applications grow and become bigger, adopting a CSS framework is an invaluable option when it comes to speeding up your workflow.</p>
<p>CSS frameworks help you build good-looking and professional web pages while maintaining consistency in design. But not all frameworks compare equally, as some provide more benefits and advantages.</p>
<p>When choosing the ideal CSS framework for your project, it is crucial to keep in mind various factors that can greatly impact how successful and efficient working with the framework will be for your project.</p>
<p>Some key aspects to consider are:</p>
<ul>
<li><p><strong>Customizability</strong>: The level of customization the framework offers. Does the framework let you customize and extend your styles beyond the framework’s design system to suit your specific needs and preferences? Or is it opinionated and vendor-locked so that you become confined to the framework’s design-system and ecosystem?</p>
</li>
<li><p><strong>Learning curve</strong>: Another factor to consider is the learning curve associated with implementing the framework. How user-friendly is the framework for new learners? What’s the developer experience like? Are there enough documentation and resources available for you to learn and utilize the frameworks effectively?</p>
</li>
<li><p><strong>Community support</strong>: The availability of a supportive and active community is also an important consideration. Dedicated communities of developers who actively contribute to the frameworks' growth and provide assistance to fellow developers (and you!) are a great resource.</p>
</li>
<li><p><strong>How it fits your project</strong>: Lastly, ensuring that the CSS framework you choose is compatible with your project goals and matches its branding and design requirements is essential.</p>
</li>
</ul>
<table><tbody><tr><td><p>A comparison table that compares different factors across the CSS frameworks mentioned in this article</p></td><td><p></p></td><td><p></p></td><td><p></p></td><td><p></p></td><td><p></p></td><td><p></p></td><td><p></p></td><td><p></p></td><td><p></p></td></tr><tr><th><p>Framework</p></th><th><p>Approach</p></th><th><p>Type</p></th><th><p>Customization</p></th><th><p>Community</p></th><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th></tr><tr><th><p>Bootstrap</p></th><td><p>Component-based, uses pre-styled components</p></td><td><p>CSS framework</p></td><td><p>Moderate, offers variables for customization</p></td><td><p>Large and established community</p></td></tr><tr><th><p>Tailwind CSS</p></th><td><p>Utility-first, uses utility classes to build designs</p></td><td><p>Utility framework</p></td><td><p>Highly customizable, based on utility classes</p></td><td><p>Growing community</p></td><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th></tr><tr><th><p>Material UI</p></th><td><p>Component-based, uses pre-styled components</p></td><td><p>React UI framework</p></td><td><p>Moderate, offers variables for customization</p></td><td><p>Strong React community</p></td><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th></tr><tr><th><p>styled-components</p></th><td><p>CSS-in-JS, allows writing CSS within JavaScript</p></td><td><p>Styling library</p></td><td><p>Highly customizable, CSS-in-JS approach</p></td><td><p>Growing adoption</p></td><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th></tr><tr><th><p>Foundation</p></th><td><p>Modular, customizable grid system and components</p></td><td><p>CSS framework</p></td><td><p>High, modular components allow extensive customization</p></td><td><p>Smaller compared to Bootstrap</p></td><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th></tr><tr><th><p>Chakra UI</p></th><td><p>Component-based, focused on accessibility</p></td><td><p>React UI framework</p></td><td><p>Moderate, offers variables for customization</p></td><td><p>Growing community</p></td><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th></tr><tr><th><p>Emotion</p></th><td><p>CSS-in-JS, lightweight and high-performance</p></td><td><p>Styling library</p></td><td><p>Highly customizable with CSS-in-JS</p></td><td><p>Increasing adoption</p></td><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th></tr><tr><th><p>Bulma</p></th><td><p>Modular, based on Flexbox, simple and flexible</p></td><td><p>CSS framework</p></td><td><p>Moderate, offers variables for customization</p></td><td><p>Decent user community</p></td><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th></tr><tr><th><p>Pure CSS</p></th><td><p>Minimalistic, small, and responsive</p></td><td><p>CSS framework</p></td><td><p>Limited, encourages using own styles</p></td><td><p>Smaller community</p></td><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th><th><p></p></th></tr></tbody></table>

<p>The table above gives an overview of the CSS frameworks we covered across different aspects, such as their approach, customization, learning curve, community support, available components, and styles.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>In the coming years, we can expect the emergence of new CSS frameworks and improvements to existing ones. The CSS frameworks discussed in this article are some of the most notable to use for your next project.</p>
<p>It all comes down to which fits with your goals and project requirements. By carefully evaluating and weighing these factors, you can make an informed decision and select the CSS framework that perfectly aligns with your needs and objectives.</p>
<p>Whether you opt for the versatility and flexibility of Tailwind CSS or the simplicity of Pure.CSS, all frameworks offer valuable solutions that can significantly streamline your development time, ensure brand consistency, and improve code maintenance.</p>
<p>So, go ahead and choose the framework that best suits your project, and embark on a journey towards creating visually stunning and highly functional web applications!</p>
<hr>
<p>If you found this article helpful, you can follow me on <a target="_blank" href="http://twitter.com/Victor_codejs">Twitter</a> or connect with me on <a target="_blank" href="https://www.linkedin.com/in/iam-victor-ikechukwu/">LinkedIn</a>. Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ nth-child() vs nth-of-type() Selectors in CSS – What’s the Difference? ]]>
                </title>
                <description>
                    <![CDATA[ The :nth-child() and :nth-of-type() CSS selectors select items from a group of HTML elements. But they work in different ways. Here is the main distinction between them: nth-child() selects its items from any group of elements. nth-of-type() selects... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/nth-child-vs-nth-of-type-selector-in-css/</link>
                <guid isPermaLink="false">66ba0e08d14c87384322b682</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Wed, 31 Jan 2024 18:33:32 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/nth-child-vs-nth-of-type-css-selector-freecodecamp-featured-codesweetly.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The <code>:nth-child()</code> and <code>:nth-of-type()</code> CSS selectors select items from a group of HTML elements. But they work in different ways.</p>
<p>Here is the main distinction between them:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/01/nth-child-vs-nth-of-type-selector-in-css-codesweetly.png" alt="nth-child vs nth-of-type selector in CSS" width="600" height="400" loading="lazy">
<em>nth-child() selects its items from any group of elements. nth-of-type() selects its items from a specified type of element.</em></p>
<ul>
<li><code>:nth-child()</code> selects items from a general group of elements. For instance, selecting a <code>&lt;p&gt;</code> node from a mixed group that includes <code>&lt;h1&gt;</code>, <code>&lt;div&gt;</code>, and <code>&lt;section&gt;</code>.</li>
<li><code>:nth-of-type()</code> selects items from a specified group of elements. For instance, selecting a <code>&lt;p&gt;</code> node from a group of <code>&lt;p&gt;</code> siblings.</li>
</ul>
<p>This article uses examples to show you exactly how the two selectors work in CSS so that you can understand their similarities and differences.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-the-css-nth-child-selector">What is the CSS :nth-child() Selector?</a><ul>
<li><a class="post-section-overview" href="#heading-syntax-of-the-css-nth-child-selector">Syntax of the CSS :nth-child() Selector</a></li>
<li><a class="post-section-overview" href="#heading-examples-of-the-css-nth-child-selector">Examples of the CSS :nth-child() Selector</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-is-the-css-nth-of-type-selector">What is the CSS :nth-of-type() Selector?</a><ul>
<li><a class="post-section-overview" href="#heading-syntax-of-the-css-nth-of-type-selector">Syntax of the CSS :nth-of-type() Selector</a></li>
<li><a class="post-section-overview" href="#heading-examples-of-the-css-nth-of-type-selector">Examples of the CSS :nth-of-type() Selector</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-overview">Overview</a></li>
</ol>
<p>So, without any further ado, let’s get started with the <code>:nth-child()</code> selector.</p>
<h2 id="heading-what-is-the-css-nth-child-selector">What is the CSS <code>:nth-child()</code> Selector?</h2>
<p>The CSS <code>:nth-child()</code> selector selects one or more child <a target="_blank" href="https://codesweetly.com/web-tech-terms-h#html-element">elements</a> among their direct siblings regardless of node types.</p>
<h3 id="heading-syntax-of-the-css-nth-child-selector">Syntax of the CSS <code>:nth-child()</code> Selector</h3>
<p>The CSS <code>:nth-child()</code> selector accepts one argument only. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">html-element</span><span class="hljs-selector-pseudo">:nth-child(value)</span> {
  style declarations
}
</code></pre>
<p>The <code>value</code> argument can be one of the following:</p>
<ol>
<li>A number: For example, using <code>3</code> represents the third child.</li>
<li>The keyword <code>even</code> or <code>odd</code>: We use it to represent even or odd children.</li>
<li>The formula <code>An+B</code>: We use it to express a series of numbers. For instance, <code>2n+3</code> expresses these numbers: <code>[(2x0)+3]</code>, <code>[(2x1)+3]</code>, <code>[(2x2)+3]</code>, <code>[(2x3)+3]</code>, and so on.</li>
</ol>
<p>Note the following:</p>
<ul>
<li><code>:nth-child()</code> is a CSS <a target="_blank" href="https://codesweetly.com/css-pseudo-selectors#what-is-a-css-pseudo-class-selector">pseudo-class</a> selector.</li>
<li>The <code>:nth-child()</code> selector works on direct siblings only.</li>
<li>In the <code>An+B</code> formula,<ul>
<li><code>A</code> is an <a target="_blank" href="https://codesweetly.com/web-tech-terms-i#integer">integer</a> value of your choice.</li>
<li><code>n</code> is the multiplier that automatically increases from zero (<code>0</code>).</li>
<li><code>+</code> (or <code>-</code>) is the addition (or subtraction) <a target="_blank" href="https://codesweetly.com/web-tech-terms-o#operator">operator</a>.</li>
<li><code>B</code> is an optional offset value for increasing (or decreasing) the result derived after multiplying <code>A</code> and <code>n</code>.</li>
</ul>
</li>
</ul>
<h3 id="heading-examples-of-the-css-nth-child-selector">Examples of the CSS <code>:nth-child()</code> Selector</h3>
<p>Below are examples of how to use the CSS <code>:nth-child()</code> pseudo-class selector.</p>
<h4 id="heading-apply-deeppink-to-the-element-that-is-the-third-child-to-its-parent-element">Apply DeepPink to the <code>&lt;p&gt;</code> element that is the third child to its parent element</h4>
<p>The <code>:nth-child()</code> selector below selects the <code>&lt;p&gt;</code> element that is the third child to its parent element.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:nth-child(3)</span> {
  <span class="hljs-attribute">color</span>: DeepPink;
}
</code></pre>
<p>If the snippet below is the HTML document for the above <a target="_blank" href="https://codesweetly.com/css-ruleset">CSS ruleset</a>, browsers will apply <code>DeepPink</code> to the second <code>&lt;p&gt;</code> element only.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>First heading 1 element<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>First paragraph element<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>Second paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>First heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Third paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>First heading 3 element<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Fourth paragraph element<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>Fifth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-child/js-3c8dkj"><strong>Try Editing It</strong></a></p>
<p>The <code>:nth-child()</code> selector works on direct siblings only. For instance, you can re-write the HTML snippet above to include nested elements as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">article</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Article's first heading 1 element<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's first paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Article's first heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's second paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h3</span>&gt;</span>Article's first heading 3 element<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's third paragraph element<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>Article's fourth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h2</span>&gt;</span>Article's second heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's fifth paragraph element<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>Article's sixth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">article</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-child/js-harjmu"><strong>Try Editing It</strong></a></p>
<p>The <code>p:nth-child(3)</code> selector will apply <code>DeepPink</code> only to the fourth <code>&lt;p&gt;</code> node because it is the third child of its parent element.</p>
<h4 id="heading-apply-deeppink-to-every-odd-child-that-is-a-node">Apply DeepPink to every odd child that is a <code>&lt;p&gt;</code> node</h4>
<p>The <code>:nth-child()</code> selector below selects every odd child element that is a <code>&lt;p&gt;</code> node.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:nth-child(odd)</span> {
  <span class="hljs-attribute">color</span>: DeepPink;
}
</code></pre>
<p><strong>Note:</strong> <code>1</code> is the <a target="_blank" href="https://codesweetly.com/web-tech-terms-i#index">index</a> position of the first child element.</p>
<p>Assuming the snippet below is the HTML document for the above CSS ruleset, browsers will apply <code>DeepPink</code> to the fourth <code>&lt;p&gt;</code> element only.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>First heading 1 element<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>First paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>First heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Second paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>First heading 3 element<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Third paragraph element<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>Fourth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-child/js-p2tsnq"><strong>Try Editing It</strong></a></p>
<h4 id="heading-apply-deeppink-to-every-even-child-that-is-a-node">Apply <code>DeepPink</code> to every even child that is a <code>&lt;p&gt;</code> node</h4>
<p>The <code>:nth-child()</code> selector below selects every even child element that is a <code>&lt;p&gt;</code> node.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:nth-child(even)</span> {
  <span class="hljs-attribute">color</span>: DeepPink;
}
</code></pre>
<p><strong>Note:</strong> <code>1</code> is the index position of the first child element.</p>
<p>Assuming the snippet below is the HTML document for the above CSS ruleset, browsers will apply <code>DeepPink</code> to the first, second, fourth, and sixth <code>&lt;p&gt;</code> elements.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">article</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Article's first heading 1 element<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's first paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Article's first heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's second paragraph element<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>Article's third paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h3</span>&gt;</span>Article's first heading 3 element<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's fourth paragraph element<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>Article's fifth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h2</span>&gt;</span>Article's second heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's sixth paragraph element<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>Article's seventh paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">article</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-child/js-c9bvm5"><strong>Try Editing It</strong></a></p>
<h4 id="heading-apply-deeppink-to-the-third-child-element-seventh-eleventh-and-so-on-that-is-a-node">Apply DeepPink to the third child element, seventh, eleventh, and so on that is a <code>&lt;p&gt;</code> node</h4>
<p>The <code>:nth-child()</code> selector below selects every <code>&lt;p&gt;</code> child element whose index is a multiple of two (<code>2</code>) with an offset of three (<code>+3</code>).</p>
<p><strong>Note:</strong> <code>1</code> is the index position of the first child element.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:nth-child(2n+3)</span> {
  <span class="hljs-attribute">color</span>: DeepPink;
}
</code></pre>
<p><strong>Fun Quiz:</strong> If the snippet below is the HTML document for the above CSS ruleset, which of the elements will the browser style?</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>First paragraph element<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>Second paragraph element<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>Third paragraph element<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>Fourth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Fifth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Sixth paragraph element<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>Seventh paragraph element<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>Eight paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Nineth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Tenth paragraph element<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>Eleventh paragraph element<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>Twelfth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-child/js-ri4zjg"><strong>Try Editing It</strong></a></p>
<h4 id="heading-apply-deeppink-to-the-first-child-third-fifth-and-so-on-that-is-a-node">Apply DeepPink to the first child, third, fifth, and so on that is a <code>&lt;p&gt;</code> node</h4>
<p>The <code>:nth-child()</code> selector below selects every <code>&lt;p&gt;</code> child element whose index is a multiple of two (<code>2</code>) with an offset of negative three (<code>-3</code>).</p>
<p><strong>Note:</strong> <code>1</code> is the index position of the first child element.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:nth-child(2n-3)</span> {
  <span class="hljs-attribute">color</span>: DeepPink;
}
</code></pre>
<p><strong>Fun Quiz:</strong> If the snippet below is the HTML document for the above CSS ruleset, which of the elements will the browser style?</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>First paragraph element<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>Second paragraph element<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>Third paragraph element<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>Fourth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Fifth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Sixth paragraph element<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>Seventh paragraph element<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>Eight paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Nineth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Tenth paragraph element<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>Eleventh paragraph element<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>Twelfth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-child/js-jc7gyl"><strong>Try Editing It</strong></a></p>
<h4 id="heading-apply-deeppink-to-the-nodes-that-are-one-of-the-first-three-children-of-their-parent">Apply DeepPink to the <code>&lt;p&gt;</code> nodes that are one of the first three children of their parent</h4>
<p>The <code>:nth-child()</code> selector below applies DeepPink to <code>&lt;p&gt;</code> nodes if they are one of their parent’s first three elements.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:nth-child(-n+3)</span> {
  <span class="hljs-attribute">color</span>: DeepPink;
}
</code></pre>
<p><strong>Fun Quiz:</strong> If the snippet below is the HTML document for the above CSS ruleset, which of the elements will the browser style?</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">article</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Article's first heading 1 element<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's first paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Article's first heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's second paragraph element<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>Article's third paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h3</span>&gt;</span>Article's first heading 3 element<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's fourth paragraph element<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>Article's fifth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h2</span>&gt;</span>Article's second heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's sixth paragraph element<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>Article's seventh paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">article</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-child/js-rjuvvs"><strong>Try Editing It</strong></a></p>
<p>Note that:</p>
<ul>
<li><code>1</code> is the index position of the first child element.</li>
<li>The <code>-n+3</code> syntax always selects the first three children because:<ul>
<li><code>-1 + 3 = 2</code></li>
<li><code>-2 + 3 = 1</code></li>
<li><code>-3 + 3 = 0</code></li>
</ul>
</li>
</ul>
<p>So, now that we know how the CSS <code>:nth-child()</code> selector works, let’s discuss <code>:nth-of-type()</code> so we can see the difference.</p>
<h2 id="heading-what-is-the-css-nth-of-type-selector">What is the CSS <code>:nth-of-type()</code> Selector?</h2>
<p>The CSS <code>:nth-of-type()</code> selector selects one or more child <a target="_blank" href="https://codesweetly.com/web-tech-terms-h#html-element">elements</a> among their direct siblings of the same node type.</p>
<h3 id="heading-syntax-of-the-css-nth-of-type-selector">Syntax of the CSS <code>:nth-of-type()</code> Selector</h3>
<p>The CSS <code>:nth-of-type()</code> accepts one argument only. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">html-element</span><span class="hljs-selector-pseudo">:nth-of-type(value)</span> {
  style declarations
}
</code></pre>
<p>The <code>value</code> argument can be one of the following:</p>
<ol>
<li>A number: For instance, using <code>3</code> represents the third element type.</li>
<li>The keyword <code>even</code> or <code>odd</code>: We use it to represent even or odd element types.</li>
<li>The formula <code>An+B</code>: We use it to express a series of numbers. For instance, <code>2n+3</code> expresses these numbers: <code>[(2x0)+3]</code>, <code>[(2x1)+3]</code>, <code>[(2x2)+3]</code>, <code>[(2x3)+3]</code>, and so on.</li>
</ol>
<p>Note the following:</p>
<ul>
<li><code>:nth-of-type()</code> is a CSS <a target="_blank" href="https://codesweetly.com/css-pseudo-selectors#what-is-a-css-pseudo-class-selector">pseudo-class</a> selector.</li>
<li>The <code>:nth-of-type()</code> selector works on direct siblings only.</li>
<li>In the <code>An+B</code> formula,<ul>
<li><code>A</code> is an <a target="_blank" href="https://codesweetly.com/web-tech-terms-i#integer">integer</a> value of your choice.</li>
<li><code>n</code> is the multiplier that automatically increases from zero (<code>0</code>).</li>
<li><code>+</code> (or <code>-</code>) is the addition (or subtraction) <a target="_blank" href="https://codesweetly.com/web-tech-terms-o#operator">operator</a>.</li>
<li><code>B</code> is an optional offset value for increasing (or decreasing) the result derived after multiplying <code>A</code> and <code>n</code>.</li>
</ul>
</li>
</ul>
<h3 id="heading-examples-of-the-css-nth-of-type-selector">Examples of the CSS <code>:nth-of-type()</code> Selector</h3>
<p>Below are examples of how to use the CSS <code>:nth-of-type()</code> pseudo-class selector.</p>
<h4 id="heading-apply-deeppink-to-the-third-element-type">Apply DeepPink to the third <code>&lt;p&gt;</code> element type</h4>
<p>The <code>:nth-of-type()</code> selector below selects the third <code>&lt;p&gt;</code> element among its siblings of the same node type.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:nth-of-type(3)</span> {
  <span class="hljs-attribute">color</span>: DeepPink;
}
</code></pre>
<p>Assuming the snippet below is the HTML document for the above CSS ruleset, browsers will apply <code>DeepPink</code> to the third <code>&lt;p&gt;</code> element only.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>First heading 1 element<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>First paragraph element<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>Second paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>First heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Third paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>First heading 3 element<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Fourth paragraph element<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>Fifth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-of-type/js-txtema"><strong>Try Editing It</strong></a></p>
<p>The <code>:nth-of-type()</code> selector works on direct siblings only. For instance, you can re-write the HTML snippet above to include nested elements as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">article</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Article's first heading 1 element<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> Article's first paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Article's first heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's second paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h3</span>&gt;</span>Article's first heading 3 element<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's third paragraph element<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>Article's fourth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h2</span>&gt;</span>Article's second heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's fifth paragraph element<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>Article's sixth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">article</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-of-type/js-hv18yl"><strong>Try Editing It</strong></a></p>
<p>The <code>p:nth-of-type(3)</code> selector will apply <code>DeepPink</code> only to the fifth <code>&lt;p&gt;</code> node because it is the third <code>&lt;p&gt;</code> type of its parent element.</p>
<p>Therefore, if you add one more <code>&lt;p&gt;</code> node to the <code>&lt;section&gt;</code> element, the <code>p:nth-of-type(3)</code> selector will apply <code>DeepPink</code> to the fifth and sixth <code>&lt;p&gt;</code> items.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">article</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Article's first heading 1 element<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> Article's first paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Article's first heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's second paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h3</span>&gt;</span>Article's first heading 3 element<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's third paragraph element<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>Article's fourth paragraph element<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>Article's fifth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h2</span>&gt;</span>Article's second heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's sixth paragraph element<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>Article's seventh paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">article</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-of-type/js-ydvfhw"><strong>Try Editing It</strong></a></p>
<h4 id="heading-apply-deeppink-to-every-odd-element-type">Apply DeepPink to every odd <code>&lt;p&gt;</code> element type</h4>
<p>The <code>:nth-of-type()</code> selector below selects every <code>&lt;p&gt;</code> child element with an odd <a target="_blank" href="https://codesweetly.com/web-tech-terms-i#index">index</a>.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:nth-of-type(odd)</span> {
  <span class="hljs-attribute">color</span>: DeepPink;
}
</code></pre>
<p><strong>Note:</strong> <code>1</code> is the index position of the first child element.</p>
<p>Assuming the snippet below is the HTML document for the above CSS ruleset, browsers will apply <code>DeepPink</code> to the first and third <code>&lt;p&gt;</code> elements.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>First heading 1 element<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>First paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>First heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Second paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>First heading 3 element<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Third paragraph element<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>Fourth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-of-type/js-uhbpyv"><strong>Try Editing It</strong></a></p>
<h4 id="heading-apply-deeppink-to-every-even-element-type">Apply DeepPink to every even <code>&lt;p&gt;</code> element type</h4>
<p>The <code>:nth-of-type()</code> selector below selects every <code>&lt;p&gt;</code> child element with an even index.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:nth-of-type(even)</span> {
  <span class="hljs-attribute">color</span>: DeepPink;
}
</code></pre>
<p><strong>Note:</strong> <code>1</code> is the index position of the first child element.</p>
<p>Assuming the snippet below is the HTML document for the above CSS ruleset, browsers will apply <code>DeepPink</code> to the second, fifth, and sixth <code>&lt;p&gt;</code> elements.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">article</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Article's first heading 1 element<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> Article's first paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Article's first heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's second paragraph element<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>Article's third paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h3</span>&gt;</span>Article's first heading 3 element<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's fourth paragraph element<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>Article's fifth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h2</span>&gt;</span>Article's second heading 2 element<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Article's sixth paragraph element<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>Article's seventh paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">article</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-of-type/js-ueawgj"><strong>Try Editing It</strong></a></p>
<p><strong>Note:</strong> Browsers will apply <code>DeepPink</code> to the fifth paragraph because it is the second <code>&lt;p&gt;</code> node of the <code>&lt;section&gt;</code> element.</p>
<h4 id="heading-apply-deeppink-to-the-third-element-type-fifth-seventh-and-so-on">Apply DeepPink to the third <code>&lt;p&gt;</code> element type, fifth, seventh, and so on</h4>
<p>The <code>:nth-of-type()</code> selector below selects every <code>&lt;p&gt;</code> child element whose index is a multiple of two (<code>2</code>) with an offset of three (<code>+3</code>).</p>
<p><strong>Note:</strong> <code>1</code> is the index position of the first child element.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:nth-of-type(2n+3)</span> {
  <span class="hljs-attribute">color</span>: DeepPink;
}
</code></pre>
<p><strong>Fun Quiz:</strong> If the snippet below is the HTML document for the above CSS ruleset, which of the elements will the browser style?</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>First paragraph element<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>Second paragraph element<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>Third paragraph element<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>Fourth paragraph element<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>Fifth paragraph element<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>Sixth paragraph element<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>Seventh paragraph element<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>Eight paragraph element<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>Nineth paragraph element<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>Tenth paragraph element<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>Eleventh paragraph element<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>Twelfth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-of-type/js-mbfvqr"><strong>Try Editing It</strong></a></p>
<h4 id="heading-apply-deeppink-to-the-first-element-type-third-fifth-and-so-on">Apply DeepPink to the first <code>&lt;p&gt;</code> element type, third, fifth, and so on</h4>
<p>The <code>:nth-of-type()</code> selector below selects every <code>&lt;p&gt;</code> child element whose index is a multiple of two (<code>2</code>) with an offset of negative three (<code>-3</code>).</p>
<p><strong>Note:</strong> <code>1</code> is the index position of the first child element.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:nth-of-type(2n-3)</span> {
  <span class="hljs-attribute">color</span>: DeepPink;
}
</code></pre>
<p><strong>Fun Quiz:</strong> If the snippet below is the HTML document for the above CSS ruleset, which of the elements will the browser style?</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>First paragraph element<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>Second paragraph element<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>Third paragraph element<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>Fourth paragraph element<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>Fifth paragraph element<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>Sixth paragraph element<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>Seventh paragraph element<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>Eight paragraph element<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>Nineth paragraph element<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>Tenth paragraph element<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>Eleventh paragraph element<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>Twelfth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-of-type/js-inivqw"><strong>Try Editing It</strong></a></p>
<h4 id="heading-apply-deeppink-to-the-first-three-element-type">Apply DeepPink to the first three <code>&lt;p&gt;</code> element type</h4>
<p>The <code>:nth-of-type()</code> selector below applies <code>DeepPink</code> to the first three <code>&lt;p&gt;</code> child elements.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:nth-of-type(-n+3)</span> {
  <span class="hljs-attribute">color</span>: DeepPink;
}
</code></pre>
<p><strong>Fun Quiz:</strong> If the snippet below is the HTML document for the above CSS ruleset, which of the elements will the browser style?</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>First paragraph element<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>Second paragraph element<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>Third paragraph element<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>Fourth paragraph element<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>Fifth paragraph element<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>Sixth paragraph element<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>Seventh paragraph element<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>Eight paragraph element<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>Nineth paragraph element<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>Tenth paragraph element<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>Eleventh paragraph element<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>Twelfth paragraph element<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/selectors/nth-of-type/js-akcgtf"><strong>Try Editing It</strong></a></p>
<p><strong>Note:</strong></p>
<ul>
<li><code>1</code> is the index position of the first child element.</li>
<li>The <code>-n+3</code> syntax always selects the first three <code>&lt;p&gt;</code> child elements because:<ul>
<li><code>-1 + 3 = 2</code></li>
<li><code>-2 + 3 = 1</code></li>
<li><code>-3 + 3 = 0</code></li>
</ul>
</li>
</ul>
<h2 id="heading-overview">Overview</h2>
<p>In this article, we discussed the similarities and differences between the CSS <code>:nth-child()</code> and <code>:nth-of-type()</code> selectors. We also used examples to see how they work.</p>
<p>Thanks for reading!</p>
<h3 id="heading-and-heres-a-useful-reactjs-resource">And here’s a useful React.JS resource:</h3>
<p>I wrote a book about <a target="_blank" href="https://amzn.to/48NjBdY">Creating NPM Packages</a>!</p>
<p>It is a beginner-friendly guidebook for mastering the art of creating, testing, and publishing NPM libraries in the React and JavaScript ecosystem.</p>
<p>It uses a scalable project to explain the fundamentals of building and managing NPM packages from scratch.</p>
<p><a target="_blank" href="https://amzn.to/48NjBdY"><img src="https://www.freecodecamp.org/news/content/images/2024/01/creating-npm-package-reactjs-book-codesweetly.png" alt="Creating NPM Package ReactJS book is now available at Amazon" width="600" height="400" loading="lazy"></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[ How to Build AI Apps – A Frontend Developer's Guide ]]>
                </title>
                <description>
                    <![CDATA[ By Mahmud Adeleye Artificial Intelligence: The New Frontier for Frontend Developers The demand for AI-powered applications is growing at a fast pace. As a front-end developer, you can take advantage of this trend and advance your career by integratin... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/frontend-ai-guide/</link>
                <guid isPermaLink="false">66d460138812486a37369d07</guid>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Artificial Intelligence ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 23 Jan 2024 22:05:41 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/Mojito-Cocktail-Recipe-Blog-Banner--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Mahmud Adeleye</p>
<h2 id="heading-artificial-intelligence-the-new-frontier-for-frontend-developers">Artificial Intelligence: The New Frontier for Frontend Developers</h2>
<p>The demand for AI-powered applications is growing at a fast pace. As a front-end developer, you can take advantage of this trend and advance your career by integrating your skills in frontend development with AI technologies. </p>
<p>This integration allows you to build intelligent applications that improve user experiences and provide valuable insights that can positively impact a user's decisions.</p>
<p>To highlight the exciting opportunities out there right now, consider these statistics:</p>
<ol>
<li>In 2023, <a target="_blank" href="https://www.theinformation.com/articles/what-we-can-learn-from-ai-startups-in-y-combinators-latest-batch">more than 60% of startups accepted into the renowned Y Combinator</a> were focused on AI.</li>
<li>Despite a <a target="_blank" href="https://news.crunchbase.com/venture/global-funding-data-analysis-ai-eoy-2023/">slowdown in global investments, funding to AI startups surged and reached an impressive $50 billion in 2023.</a></li>
</ol>
<p>In this guide, we'll cover the following:</p>
<ol>
<li>The role of frontend developers in advancing AI innovation.</li>
<li>Key steps to follow when integrating AI services into your frontend workflow</li>
<li>How to ensure the optimal performance and security of the AI apps you build.</li>
<li>Lastly, we will incorporate the tips in 1-3 to build an AI Website Critic that can roast your websites and portfolio apps using React and OpenAI's GPT4-Vision Model.</li>
</ol>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li>Knowledge of HTML</li>
<li>Basic understanding of React hooks</li>
<li>Node and npm installed on your local computer.</li>
</ul>
<h2 id="heading-the-role-of-frontend-developers-in-crafting-ai-driven-experiences">The Role of Frontend Developers in Crafting AI-driven Experiences</h2>
<p>Frontend developers play a crucial role in crafting AI-driven experiences by leveraging their expertise in user interface design, data visualization, and technical implementation. </p>
<p>They are responsible for creating the user interface, designing the interaction flows, and integrating AI functionality seamlessly into the app. </p>
<p>Frontend developers also collaborate with back-end developers and data scientists to ensure the efficient and accurate functioning of AI algorithms.</p>
<p>In addition, frontend developers play a critical role in the performance of web apps that leverage the latest AI models. They are responsible for optimizing the app's performance, ensuring cross-platform compatibility, and implementing responsive designs that adapt to different devices and screen sizes.</p>
<h2 id="heading-how-to-integrate-ai-services-into-your-frontend-workflow">How to Integrate AI Services Into Your Frontend Workflow</h2>
<p>To integrate AI services into your frontend workflow, you should follow a systematic approach that includes these steps:</p>
<ol>
<li>Identify the task or problem that AI capabilities can solve or enhance.</li>
<li>Research and evaluate AI companies that provide APIs and node SDKs for the specific AI capabilities required for the task or problem you identified. By understanding the offerings of different AI companies, you can choose the most suitable AI services to integrate into your applications. </li>
</ol>
<p>Let's take a look at some popular AI models and their core tasks:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>AI Model</td><td>Task</td></tr>
</thead>
<tbody>
<tr>
<td>GPT-4</td><td>Multimodal model (capable of text, image etc)</td></tr>
<tr>
<td>Stable Diffusion</td><td>Text to Image Generative AI Model</td></tr>
<tr>
<td>Mistral 7B</td><td>Multimodal model (capable of text, image etc)</td></tr>
<tr>
<td>Voicebox</td><td>Speech generative AI model</td></tr>
<tr>
<td>DALL·E 3</td><td>Text to Image Generative AI Model</td></tr>
</tbody>
</table>
</div><p>You can explore more of these models on <a target="_blank" href="https://replicate.com/explore">Replicate Explore</a> and <a target="_blank" href="https://huggingface.co/models">Huggingface explore models</a> pages.</p>
<ol start="3">
<li>Integrate the selected AI services into your frontend application by leveraging the provided APIs and node SDKs. This involves understanding the documentation and guidelines the AI companies offer to ensure seamless integration and proper utilization of the AI capabilities.</li>
<li>Test and validate the integrated AI services within your frontend application to ensure accurate and efficient functionality. This step is crucial for identifying and addressing technical issues or optimization requirements.</li>
</ol>
<p>It's also important to design with empathy by providing clear explanations and visualizations, giving users a sense of control and ownership over AI-generated outputs. </p>
<h3 id="heading-example-application">Example application</h3>
<p>Let's go over an example. Suppose you want to make a custom meme generator. In that case, you should search for AI models specifically trained to work with images, such as Stability's Stable Diffusion and OpenAI's DALL·E 3.</p>
<p>After that, you can explore the best APIs and SDKs that you can use to take advantage of these AI models and create a basic sample. </p>
<p>To illustrate, let's use the Replicate Node SDK, which provides a convenient method to interact with the Stable Diffusion AI model and set up a basic Node.js program that we can later integrate into our React application.</p>
<p>Step 1. Get your token from https://replicate.com/account
Step 2: Install the Node SDK with the npm command: <code>npm install replicate</code>
Step 3: Query the Stable Diffusion AI model via the replicate SDK.</p>
<pre><code><span class="hljs-keyword">const</span> Replicate = <span class="hljs-built_in">require</span>(<span class="hljs-string">"replicate"</span>);
<span class="hljs-keyword">const</span> replicate = <span class="hljs-keyword">new</span> Replicate({

  <span class="hljs-attr">auth</span>: <span class="hljs-string">""</span>, <span class="hljs-comment">// defaults to process.env.REPLICATE_API_TOKEN</span>
});

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">iLoveCats</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> model = <span class="hljs-string">"stability-ai/stable-diffusion:27b93a2413e7f36cd83da926f3656280b2931564ff050bf9575f1fdf9bcd7478"</span>;
  <span class="hljs-keyword">const</span> input = {
    <span class="hljs-attr">prompt</span>: <span class="hljs-string">"a cat wearing a suit"</span>,
  };
  <span class="hljs-keyword">const</span> output = <span class="hljs-keyword">await</span> replicate.run(model, { input });
  <span class="hljs-built_in">console</span>.log(output[<span class="hljs-number">0</span>]);

}

iLoveCats()
</code></pre><p>When you log the output, you get an image URL that you can easily display in your frontend app. <code>https://replicate.delivery/pbxt/ng6Tb0HNdzYwFZXMNv3qmIBxc2GIwU4t7edephtDvuWZ5wNSA/out-0.png</code></p>
<figure>
    <img src="https://www.freecodecamp.org/news/content/images/2024/01/catsuit.png" alt="A cat in a suit" width="600" height="400" loading="lazy">
    <figcaption>A cat in a suit.</figcaption>
</figure>

<h2 id="heading-how-to-optimize-for-performance-and-security-in-ai-driven-frontend-applications">How to Optimize for Performance and Security in AI-driven Frontend Applications</h2>
<p>Optimizing for performance and security in AI-driven frontend apps is essential for creating a smooth user experience and for data protection as well. </p>
<p>Thankfully, the techniques listed below are similar to standard practices in traditional frontend development. This overlap means that developers who are familiar with conventional frontend optimization and security practices can more easily adapt and apply those skills to the unique demands of AI-driven applications:</p>
<ol>
<li>Employ lazy loading and code-splitting techniques to reduce initial loading times and improve performance.</li>
<li>Utilize caching and resource optimization techniques to minimize unnecessary API calls and improve data retrieval speed.</li>
<li>Implementing secure API endpoints and authentication mechanisms to ensure only authorized access to AI services and data.</li>
</ol>
<h2 id="heading-how-to-build-an-ai-website-critic-using-react-and-openais-gpt4-vision-model"><strong>How to Build an AI Website Critic using React and OpenAI's GPT4-Vision Model</strong></h2>
<p>In this section, we will build a React app that utilizes a Vision model to analyze images of websites and provide feedback. To do this, we will follow the previously described 4-step workflow for integrating AI services into frontend apps.   </p>
<p>Since we need for a vision model that can analyze images, we should look at the available options in the market, which you can find <a target="_blank" href="https://replicate.com/collections/vision-models">here</a> and <a target="_blank" href="https://huggingface.co/models?pipeline_tag=visual-question-answering&amp;sort=downloads">here</a>. <a target="_blank" href="https://encord.com/blog/gpt-vision-vs-llava/">After examining the performance benchmarks of available vision models</a>, we will go with OpenAI's GPT-4 vision model.  </p>
<p>OpenAI's GPT-4 vision model is a state-of-the-art AI model released in late 2023. It can accept images as inputs, analyze them, and provide detailed feedback based on the prompts. </p>
<p>Apart from performance reasons, we will use it for our Website Critique application because it offers relatively cheaper pricing than other vision models, and has an easy-to-use API endpoint bundled with the popular OpenAI developer interface.</p>
<p>It's now time to integrate it into our React app.</p>
<h3 id="heading-step-1-install-react-vite">Step 1: Install React + Vite</h3>
<p>You can do that with the following command:</p>
<pre><code>npm create vite@latest my-website-critic -- --template react
</code></pre><h3 id="heading-step-2-install-openai-node-package">Step 2: Install OpenAI Node package</h3>
<p>Open the generated project folder in your favorite IDE and install the OpenAI Node package, which you will use to interact with the GPT4 Vision model.</p>
<p>Here's how to install it:</p>
<pre><code>cd my-website-critic
npm install openai
</code></pre><h3 id="heading-step-3-install-the-react-markdown-package">Step 3: Install the React markdown package</h3>
<p>This will help you format the model's textual responses in a readable format.</p>
<pre><code>npm install react-markdown
</code></pre><h3 id="heading-step-4-run-npm-install">Step 4: Run npm install</h3>
<p>Now run <code>npm install</code>:</p>
<pre><code>  npm install
  npm run dev
</code></pre><h3 id="heading-step-5-manage-state-in-react">Step 5: Manage state in React</h3>
<p>In this step, you will use React's <strong><code>useState</code></strong> and <strong><code>useEffect</code></strong> hooks for managing the state and handling the asynchronous request to OpenAI's API in <code>src/App.jsx</code>.</p>
<figure>
    <img src="https://i.ibb.co/sWM573X/Screenshot-2024-01-18-at-10-34-28-AM.png" alt="freeCodeCamp hero section" width="600" height="400" loading="lazy">
    <figcaption>freeCodeCamp hero section</figcaption>
</figure>


<p>For our image input, we will be using a screenshot of the freeCodeCamp homepage hero section uploaded to a image storage platform like <a target="_blank" href="https://imgbb.com/">IMGBB</a>. Feel free to use any image URL you want.</p>
<p>Here's the code - I'll explain it below:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> { useState, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> OpenAI <span class="hljs-keyword">from</span> <span class="hljs-string">'openai'</span>;
<span class="hljs-keyword">import</span> ReactMarkdown <span class="hljs-keyword">from</span> <span class="hljs-string">'react-markdown'</span>;

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [response, setResponse] = useState(<span class="hljs-literal">null</span>);
  <span class="hljs-keyword">const</span> [isLoading, setIsLoading] = useState(<span class="hljs-literal">false</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> openai = <span class="hljs-keyword">new</span> OpenAI({
      <span class="hljs-attr">apiKey</span>: <span class="hljs-string">"YOUR_OPENAI_API_KEY"</span>,
      <span class="hljs-attr">dangerouslyAllowBrowser</span>: <span class="hljs-literal">true</span>,
    });

    <span class="hljs-keyword">const</span> fetchUICriticResponse = <span class="hljs-keyword">async</span> () =&gt; {
      setIsLoading(<span class="hljs-literal">true</span>);
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> openai.chat.completions.create({
          <span class="hljs-attr">model</span>: <span class="hljs-string">"gpt-4-vision-preview"</span>,
          <span class="hljs-attr">messages</span>: [
            {
              <span class="hljs-attr">role</span>: <span class="hljs-string">"user"</span>,
              <span class="hljs-attr">content</span>: [
                { <span class="hljs-attr">type</span>: <span class="hljs-string">"text"</span>, <span class="hljs-attr">text</span>: <span class="hljs-string">"You're an expert UI critic. What can I improve in this website?"</span> },
                {
                  <span class="hljs-attr">type</span>: <span class="hljs-string">"image_url"</span>,
                  <span class="hljs-attr">image_url</span>: {
                    <span class="hljs-string">"url"</span>: <span class="hljs-string">"https://i.ibb.co/sWM573X/Screenshot-2024-01-18-at-10-34-28-AM.png"</span>,
                  },
                },
              ],
            },
          ],
          <span class="hljs-string">"max_tokens"</span>: <span class="hljs-number">1500</span>
        });
        <span class="hljs-keyword">if</span> (result &amp;&amp; result.choices &amp;&amp; result.choices.length &gt; <span class="hljs-number">0</span> &amp;&amp; result.choices[<span class="hljs-number">0</span>].message) {
          <span class="hljs-built_in">console</span>.log(<span class="hljs-number">1</span>, result);
          setResponse(result.choices[<span class="hljs-number">0</span>].message.content);
        }
      } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error fetching AI response:"</span>, error);
      } <span class="hljs-keyword">finally</span> {
        setIsLoading(<span class="hljs-literal">false</span>);
      }
    };

    fetchUICriticResponse();
  }, []);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Hi! UI Expert Here<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
      {isLoading ? (
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      ) : response ? (
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>My Feedback:<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">ReactMarkdown</span>&gt;</span>{response}<span class="hljs-tag">&lt;/<span class="hljs-name">ReactMarkdown</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>No response received.<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>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>In the above component:</p>
<ul>
<li>The <strong><code>useEffect</code></strong> hook runs the <code>fetchUICriticResponse</code> function when the component mounts.</li>
<li>The <strong><code>useState</code></strong> hooks manage the AI response (<strong><code>response</code></strong>) and the loading state (<strong><code>isLoading</code></strong>).</li>
<li><code>fetchUICriticResponse</code> is an asynchronous function that fetches the response using the OpenAI API.</li>
<li>The component renders a loading message while the response is being fetched. Once the fetch is complete, it displays the response or a fallback message using the React Markdown package we installed earlier.</li>
</ul>
<p>You should get a result similar to the image below containing the result of the GPT4 Vision model analysis of the provided image and prompt given.</p>
<figure>
    <img src="https://i.ibb.co/DCNSHy7/critic.png" alt="result of the GPT4 Vision model analysis" width="600" height="400" loading="lazy">
    <figcaption>result of the GPT4 Vision model analysis.</figcaption>
</figure>

<p>As you can see, the analysis goes through each element on the page and offers feedback – both positive, and more constructive – on things like navigation clarity, whitespace usage, search functions, and so on.</p>
<p><strong>Note:</strong> Handling API keys directly in the frontend is not recommended due to security concerns. The example is just for learning. In production, create an <code>.env</code> file and put your <code>YOUR_OPENAI_API_KEY</code> in it.</p>
<h2 id="heading-whats-next">What's Next?</h2>
<p>You can enhance these code examples by creating a simple input field for users to enter their image links. You may also set up an image uploader to allow users to upload images from their local device.</p>
<p>Please refer to the <a target="_blank" href="https://platform.openai.com/docs/guides/vision">official documentation</a> for instructions on how to achieve this.</p>
<p>When deciding which AI applications to develop, it is crucial to consider the intended impact, user requirements, and available resources. </p>
<p>Some other potential AI application ideas include a language translation app and a virtual personal assistant.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If you're interested in incorporating AI into your frontend apps, start by exploring open and closed-source AI models. You'll also want to understand how to work with APIs and external libraries. </p>
<p>You should also focus on familiarizing yourself with handling AI model responses and interactivity.</p>
<p>With this knowledge, you can position yourself for the several consumer-ready AI innovations that will spring up and require the services of a frontend developer skilled in building AI-powered apps.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Add Custom Buttons to a Date Picker in Flatpickr ]]>
                </title>
                <description>
                    <![CDATA[ If you've ever had to use a date picker in a web frontend project, chances are that you've used flatpickr.  For the unacquainted, flatpickr is one of the most popular date picker libraries in the open source-verse. It's framework-agnostic, highly cus... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-add-custom-buttons-to-flatpickr/</link>
                <guid isPermaLink="false">66ba2c9bab41bfc0b9b131da</guid>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ User Interface ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Idris Abdul-Lateef ]]>
                </dc:creator>
                <pubDate>Wed, 17 Jan 2024 16:34:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/b01117c062c14a0d7f54f256baf09808482b6505_2_1024x512.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you've ever had to use a date picker in a web frontend project, chances are that you've used flatpickr. </p>
<p>For the unacquainted, <a target="_blank" href="https://flatpickr.js.org/">flatpickr</a> is one of the most popular date picker libraries in the open source-verse. It's framework-agnostic, highly customizable, and lightweight.</p>
<p>I recently had to use it in a Next.js codebase and there was a peculiar use case I had. The built-in behavior is that dates are applied immediately when selected, and thereafter the date picker disappears. </p>
<p>What I really wanted, however, was to be able to pick dates and not have the modal disappear the moment I did so. I wanted to be able to keep picking dates and only have it applied when I clicked on an "Apply" button. I also wanted a "Clear" button to clear applied dates.</p>
<p>Ordinarily, flatpickr's API has methods you can work with to get these functionalities, but you won't get buttons on the date picker itself. </p>
<p>Even while there is a <a target="_blank" href="https://flatpickr.js.org/plugins/#confirmdate">plugin</a> that adds a button to the date picker to manually apply dates, it doesn't work for date ranges (which was what I needed it for) and the button's look didn't really blend with the overall theme of the app I was building. </p>
<p>I had no other option but to come up with my own solution. But how do you get your own buttons to appear on flatpickr's date picker?</p>
<h2 id="heading-how-to-set-up-flatpickr">How to Set Up flatpickr</h2>
<p>First things first, install the package:</p>
<pre><code class="lang-bash">npm install flatpickr
</code></pre>
<p>Next, you need a <code>DatePicker</code> component that will encapsulate the custom date picker and make it reusable. This component should have an <code>onChange</code> prop which will be passed a callback that will be called whenever a date is applied:</p>
<pre><code class="lang-tsx">// DatePicker.tsx

const DatePicker: React.FC&lt;DatePickerProps&gt; = ({ onChange }) =&gt; {
  return &lt;div&gt;&lt;/div&gt;
}

export default DatePicker

interface DatePickerProps {
  onChange: (date: Date[]) =&gt; void
}
</code></pre>
<p>Next, you'll need to set up flatpickr itself. You're going to bring in some exports from the flatpickr package. In the markup, you'll add a text input element, which will be the date picker input, and pass it an element ref variable that'll be used to instantiate the flatpickr instance with a couple of configuration options:</p>
<pre><code class="lang-tsx">// DatePicker.tsx

import { ElementRef, useEffect, useRef, useState } from "react"
import flatpickr from "flatpickr"

import { Instance as Flatpickr } from "flatpickr/dist/types/instance"
import "flatpickr/dist/flatpickr.min.css"

const DatePicker: React.FC&lt;DatePickerProps&gt; = ({ onChange }) =&gt; {
  const [flatpickrInstance, setFlatpickrInstance] = useState&lt;Flatpickr&gt;()
  const datePickerRef = useRef&lt;ElementRef&lt;"input"&gt;&gt;(null)

  useEffect(() =&gt; {
    if (datePickerRef.current) {
      const flatpickrInstance = flatpickr(datePickerRef.current, {
        static: true,
        closeOnSelect: false,
      })

      setFlatpickrInstance(flatpickrInstance)
    }

    return () =&gt; flatpickrInstance?.destroy()
  }, [])

  return (
    &lt;div&gt;
      &lt;input ref={datePickerRef} type="text" placeholder="Select date..." /&gt;
    &lt;/div&gt;
  )
}
...
</code></pre>
<p>For the configuration options, <code>static</code> is set to true so the date picker modal is anchored to the date picker input and <code>closeOnSelect</code> is false so the date picker modal doesn't disappear when a date is selected. </p>
<p>This is how the date picker looks so far:
<img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-14-153953.png" alt="Screenshot-2024-01-14-153953" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-add-the-buttons">How to Add the Buttons</h2>
<p>We've arrive at the main attraction of the day. From the snippet below, you'll notice two new imports: <code>createPortal</code> from react-dom and a pre-styled <code>Button</code> component. <code>createPortal</code> is going to play a very special role as you'll see.</p>
<pre><code class="lang-tsx">// DatePicker.tsx

import { ElementRef, useEffect, useRef, useState } from "react"
import { createPortal } from "react-dom"
import flatpickr from "flatpickr"
import Button from "./Button"

import { Instance as Flatpickr } from "flatpickr/dist/types/instance"
import "flatpickr/dist/flatpickr.min.css"

...
</code></pre>
<p>Moving on to the body of the <code>DatePicker</code> component, you'll notice some changes too. </p>
<p>There's <code>dates</code> which will store selected date(s) (or an empty array if no date is selected) and <code>applyDate</code> which will hold the callback to call when the 'Apply' button is clicked. </p>
<p>In the configuration object, you'll find two flatpickr hooks: <code>onChange</code> that gets triggered whenever a date is picked and receives an array of the currently selected dates, and <code>onClose</code> that gets triggered when the date picker modal is closed. </p>
<p>Within the body of these hooks are implementations that specify the date picker's behavior.</p>
<pre><code class="lang-tsx">// DatePicker.tsx

...
const DatePicker: React.FC&lt;DatePickerProps&gt; = ({ onChange }) =&gt; {
  const [flatpickrInstance, setFlatpickrInstance] = useState&lt;Flatpickr&gt;()
  const datePickerRef = useRef&lt;ElementRef&lt;"input"&gt;&gt;(null)
  const dates = useRef&lt;Date[]&gt;([])
  const [applyDate, setApplyDate] = useState(() =&gt; () =&gt; {})

  useEffect(() =&gt; {
    if (datePickerRef.current) {
      const flatpickrInstance = flatpickr(datePickerRef.current, {
        static: true,
        closeOnSelect: false,
        onChange: (selectedDates) =&gt; {
          if (selectedDates.length === 0) {
            onChange([])
            dates.current = []
          }

          setApplyDate(() =&gt; {
            return () =&gt; {
              dates.current = selectedDates
              onChange(selectedDates)
              flatpickrInstance.close()
            }
          })
        },
        onClose: () =&gt; {
          flatpickrInstance.setDate(dates.current)
        },
      })

      setFlatpickrInstance(flatpickrInstance)
    }

    return () =&gt; flatpickrInstance?.destroy()
  }, [])


  return (
    &lt;div&gt;  
...
</code></pre>
<p>We've gotten to the part where you finally put the custom buttons inside the date picker. This is where <code>createPortal</code> comes to shine. </p>
<p>The <code>flatpickrInstance</code> has a property, <code>calendarContainer</code>, which holds a reference to the date picker's containing <code>div</code> element. This is where you'll project the custom buttons, just beneath the calendar part of the date picker, using <a target="_blank" href="https://react.dev/reference/react-dom/createPortal">react portal</a>.</p>
<pre><code class="lang-tsx">// DatePicker.tsx

...
  return (
    &lt;div&gt;
      &lt;input ref={datePickerRef} type="text" placeholder="Select date..." /&gt;
      {flatpickrInstance &amp;&amp;
        createPortal(
          &lt;div className="flex justify-center gap-3 py-2"&gt;
            &lt;Button
              text="Clear"
              bgColor="#F8F8F8"
              textColor="#292A2E"
              onClick={() =&gt; {
                flatpickrInstance.clear(true)
                flatpickrInstance.close()
              }}
            /&gt;
            &lt;Button
              text="Apply"
              bgColor="#569ff7"
              textColor="#FFF"
              onClick={applyDate}
            /&gt;
          &lt;/div&gt;,
          flatpickrInstance.calendarContainer
        )}
    &lt;/div&gt;
  )
}

export default DatePicker
...
</code></pre>
<p>Put together, this is the final code output:</p>
<pre><code class="lang-tsx">// DatePicker.tsx

import { ElementRef, useEffect, useRef, useState } from "react"
import { createPortal } from "react-dom"
import flatpickr from "flatpickr"
import Button from "./Button"

import { Instance as Flatpickr } from "flatpickr/dist/types/instance"
import "flatpickr/dist/flatpickr.min.css"

const DatePicker: React.FC&lt;DatePickerProps&gt; = ({ onChange }) =&gt; {
  const [flatpickrInstance, setFlatpickrInstance] = useState&lt;Flatpickr&gt;()
  const datePickerRef = useRef&lt;ElementRef&lt;"input"&gt;&gt;(null)
  const dates = useRef&lt;Date[]&gt;([])
  const [applyDate, setApplyDate] = useState(() =&gt; () =&gt; {})

  useEffect(() =&gt; {
    if (datePickerRef.current) {
      const flatpickrInstance = flatpickr(datePickerRef.current, {
        static: true,
        closeOnSelect: false,
        onChange: (selectedDates) =&gt; {
          if (selectedDates.length === 0) {
            onChange([])
            dates.current = []
          }

          setApplyDate(() =&gt; {
            return () =&gt; {
              dates.current = selectedDates
              onChange(selectedDates)
              flatpickrInstance.close()
            }
          })
        },
        onClose: () =&gt; {
          flatpickrInstance.setDate(dates.current)
        },
      })

      setFlatpickrInstance(flatpickrInstance)
    }

    return () =&gt; flatpickrInstance?.destroy()
  }, [])

  return (
    &lt;div&gt;
      &lt;input ref={datePickerRef} type="text" placeholder="Select date..." /&gt;
      {flatpickrInstance &amp;&amp;
        createPortal(
          &lt;div className="flex justify-center gap-3 py-2"&gt;
            &lt;Button
              text="Clear"
              bgColor="#F8F8F8"
              textColor="#292A2E"
              onClick={() =&gt; {
                flatpickrInstance.clear(true)
                flatpickrInstance.close()
              }}
            /&gt;
            &lt;Button
              text="Apply"
              bgColor="#569ff7"
              textColor="#FFF"
              onClick={applyDate}
            /&gt;
          &lt;/div&gt;,
          flatpickrInstance.calendarContainer
        )}
    &lt;/div&gt;
  )
}

export default DatePicker

interface DatePickerProps {
  onChange: (date: Date[]) =&gt; void
}
</code></pre>
<p>And this is how the date picker now looks with the custom buttons:
<img src="https://www.freecodecamp.org/news/content/images/2024/01/Screenshot-2024-01-16-085906.png" alt="Screenshot-2024-01-16-085906" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The date picker is now fully functional and can work for all <code>mode</code> options. There are tons of potential customizations you could possibly do using this technique. Hopefully, this article has done a good job of showing how flatpickr customization can be achieved.</p>
<h3 id="heading-enjoyed-this-article">❤️Enjoyed this article?</h3>
<p><strong>See more of my content!</strong> You can find more articles on my <a target="_blank" href="https://blog.eedris.dev">blog</a>.</p>
<p><strong>Want to connect?</strong> Link up with me on <a target="_blank" href="https://twitter.com/eedrxs">Twitter</a> or <a target="_blank" href="https://linkedin.com/in/eedris">LinkedIn</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[ 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>
        
    </channel>
</rss>
