<?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[ Oluwatobi Sofela - 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[ Oluwatobi Sofela - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 16:29:44 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/oluwatobiss/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ The React Handbook for Beginners – JSX, Hooks, and Rendering Explained ]]>
                </title>
                <description>
                    <![CDATA[ React is one of the most powerful and widely used libraries for building user interfaces with JavaScript. From small components to large-scale front-end and full-stack applications, React gives you the flexibility to create interactive, efficient, an... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-handbook-for-beginners-learn-jsx-hooks-rendering/</link>
                <guid isPermaLink="false">68f95319417d2ee394355b66</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Programming Blogs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Wed, 22 Oct 2025 21:56:41 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1761170169453/445fd0f5-54f9-4be5-bacf-2e6c6acd1f21.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React is one of the most powerful and widely used libraries for building user interfaces with JavaScript. From small components to large-scale front-end and full-stack applications, React gives you the flexibility to create interactive, efficient, and modern features.</p>
<p>But learning React can feel overwhelming. With so many new terms, patterns, and frameworks like Next.js in the mix, it’s easy to feel lost.</p>
<p>That’s why this handbook focuses on React itself without unnecessary distractions. Once you’ve mastered React at its core, you’ll have the confidence to use it with or without frameworks to build anything you can imagine.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-you-should-already-know">What You Should Already Know</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-exactly-is-react">What Exactly Is React?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-why-the-react-name">Why the “React” name?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-is-react-a-framework">Is React a framework?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-is-react-only-for-web-development">Is React only for web development?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-whats-the-primary-goal-of-react">What’s the primary goal of React?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-add-a-react-component-to-a-website">How to Add a React Component to a Website</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-create-a-new-project-directory">Create a new project directory</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-create-a-dom-container">Create a DOM container</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-import-react-babel-and-your-component">Import React, Babel, and your component</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-create-your-component">Create your component</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-configure-a-local-server">Configure a local server</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-jsx">What Is JSX?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-can-react-work-without-jsx">Can React work without JSX?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-1-create-a-react-element-with-jsx">Example 1: Create a React element with JSX</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-2-create-a-react-element-with-regular-javascript">Example 2: Create a React element with regular JavaScript</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-reactcreateelement">What Is React.createElement()?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-jsx">How to Use JSX</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-use-jsx-like-any-javascript-expression">Use JSX like any JavaScript expression</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrap-multi-line-jsx-in-parentheses">Wrap multi-line JSX in parentheses</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrap-expressions-in-curly-braces">Wrap expressions in curly braces</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-camelcase-to-name-attributes">Use camelCase to name attributes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-close-empty-jsx-tags-properly">Close empty JSX tags properly</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-a-react-component-can-return-only-a-single-element">A React component can return only a single element</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-time-to-practice-with-jsx">Time to Practice with JSX 🤸‍♂️🏋️‍♀️🏊‍♀️</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-the-solution">The solution</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-react-component">What Is a React Component?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-syntax-of-a-react-component">Syntax of a React component</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-of-a-react-component">Example of a React component</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-react-components-best-practices">React components best practices</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-render-lists-of-elements-from-an-array">How to Render Lists of Elements from an Array</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-each-react-element-in-an-array-needs-a-unique-key">Each React element in an array needs a unique key</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-add-unique-keys-to-each-react-element-in-an-array">How to add unique keys to each React element in an array</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-essential-things-to-know-about-assigning-keys">Essential things to know about assigning keys</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-handle-events-in-react">How to Handle Events in React</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-types-of-event-handlers">Types of event handlers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-inline-event-handler">Example: Inline event handler</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-referenced-event-handler">Example: Referenced event handler</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-react-state">What Is React State?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-syntax-of-react-state">Syntax of React state</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-of-react-state">Example of React state</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-react-trigger-vs-render-vs-commit-vs-paint">React trigger vs render vs commit vs paint</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-does-it-mean-to-trigger-a-render-in-react">What does it mean to trigger a render in React?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-does-it-mean-to-render-react-components">What does it mean to render React components?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-does-it-mean-to-commit-a-react-ui-to-the-browsers-dom">What does it mean to commit a React UI to the browser’s DOM?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-does-it-mean-to-paint-the-dom-nodes-on-the-screen">What does it mean to paint the DOM nodes on the screen?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-react-ref-hook">What Is the React Ref Hook?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-syntax-of-the-react-ref-hook">Syntax of the React ref Hook</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-of-the-react-ref-hook">Example of the React ref Hook</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-react-ref-hook-best-ractices">React ref Hook best practices</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-variables-vs-refs-vs-states-in-react">Variables vs Refs vs States in React</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-do-variables-work-in-react">How do variables work in React?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-do-refs-work-in-react">How do refs work in React?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-do-states-work-in-react">How do states work in React?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-tips-on-using-variables-refs-and-states-in-react">Tips on using variables, refs, and states in React</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-useeffect-hook">What Is the useEffect Hook?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-syntax-of-the-useeffect-hook">Syntax of the useEffect Hook</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-of-the-useeffect-hook">Example of the useEffect Hook</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-useeffect-hooks-best-practices">useEffect Hook’s best practices</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-style-react-components">How to Style React Components</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-use-css-style-sheets-to-style-react-elements">How to use CSS style sheets to style React elements</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-the-inline-style-attribute-to-style-react-elements">How to use the inline style attribute to style React elements</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-css-modules-to-style-react-elements">How to use CSS Modules to style React elements</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-a-css-in-js-library-to-style-react-elements">How to use a CSS-in-JS library to style React elements</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-overview">Overview</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-dive-deeper-into-react">Dive deeper into React</a></li>
</ul>
</li>
</ol>
<h2 id="heading-what-you-should-already-know">What You Should Already Know</h2>
<p>You will get the most value out of this handbook if you are familiar with:</p>
<ul>
<li><p>JavaScript fundamentals (variables, functions, arrays, objects)</p>
</li>
<li><p>Basic CSS for styling</p>
</li>
<li><p>HTML basics for structure</p>
</li>
</ul>
<p>If you’ve ever written a small JavaScript file or built a simple “Hello World” website, you are all set!</p>
<p>Let’s get started with the basics.</p>
<h2 id="heading-what-exactly-is-react">What Exactly Is React?</h2>
<p>React is a component-based JavaScript library for efficiently building user interfaces (UI).</p>
<p>No matter how massive or miniature your project may be, React is well-suited to help you develop any web application efficiently.</p>
<p>Developers primarily use React to build independent, reusable components that can be combined with other isolated user interfaces to create highly scalable applications. For instance, the image below illustrates the individual components of YouTube’s video player page.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760577491945/1b0f8c61-b42e-4e3c-afdc-5804fdfa0d42.webp" alt="An Illustration of React Components. The YouTube video player page is illustrated as a combination of independent components." class="image--center mx-auto" width="3403" height="1936" loading="lazy"></p>
<p>In other words, React helps you build complex UIs from small, isolated components that can easily be reused in multiple applications. Each independent component tells React the exact element you want to display on screen.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760577104799/4592a7d2-e75b-4ae6-b1f4-65cfd8e94033.webp" alt="React explained: The super flexible JavaScript library for modern frontend and full-stack app development" class="image--center mx-auto" width="1920" height="1920" loading="lazy"></p>
<p>The image above illustrates React as a highly adaptable library that uses JavaScript functions to build user interfaces for both mobile and web-based applications. Let’s discuss the points highlighted in the image.</p>
<h3 id="heading-why-the-react-name">Why the “React” name?</h3>
<p>The name stems from the idea that React renders your UI and reacts to events in the user interface it has rendered on screen.</p>
<h3 id="heading-is-react-a-framework">Is React a framework?</h3>
<p>No, React is a <a target="_blank" href="https://codesweetly.com/framework-vs-library/">library—not a framework</a>. React serves only as an add-on feature to your application. It’s not designed to be used as an app’s primary support system.</p>
<h3 id="heading-is-react-only-for-web-development">Is React only for web development?</h3>
<p>No, you don’t just use React on the web. For instance, ReactDOM helps build web applications, and React Native helps build mobile applications.</p>
<h3 id="heading-can-react-be-used-for-full-stack-applications">Can React be used for full-stack applications?</h3>
<p>Absolutely. React is super flexible. You can use it in simple HTML projects, integrate it into existing code, or build complex full-stack applications. Its adaptability makes it suitable for a wide variety of development scenarios.</p>
<h3 id="heading-whats-the-primary-goal-of-react">What’s the primary goal of React?</h3>
<p>React’s primary goal is for you to use JavaScript functions to return and manage the UI (HTML element) you want to render (display) on the screen. For instance, consider the following:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">DonationUserInterface</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>&gt;</span>☕ Buy me a coffee<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>;
}
</code></pre>
<p>The JavaScript function above is a React component that returns the UI (HTML button element) we want to display on screen and manage with React. In fact, let’s implement the <code>DonationUserInterface</code> component on a live website using only HTML and JavaScript – no frameworks.</p>
<h2 id="heading-how-to-add-a-react-component-to-a-website">How to Add a React Component to a Website</h2>
<p>Follow the steps below to add a donation UI component to a live HTML website.</p>
<h3 id="heading-create-a-new-project-directory">Create a new project directory</h3>
<pre><code class="lang-bash">mkdir codesweetly-donation-ui-001
</code></pre>
<p><strong>Note:</strong> You can use any name you prefer. In this guide, we’ll use <code>codesweetly-donation-ui-001</code> for demonstration.</p>
<p>Afterward, navigate to your project directory using the command line.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> path/to/codesweetly-donation-ui-001
</code></pre>
<h3 id="heading-create-a-dom-container">Create a DOM container</h3>
<p>To add a React component to a webpage, you first need to specify the section of the page where you want to insert the UI. So, create an HTML page:</p>
<pre><code class="lang-bash">touch index.html
</code></pre>
<p>Afterward, open the new file and add the following code:</p>
<pre><code class="lang-xml"><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-US"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>CodeSweetly Donation UI<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-comment">&lt;!-- A div container (the DOM node) created for React to manage --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"donation-ui"</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 snippet above created a DOM node (<code>&lt;div&gt;</code> element), inside which we want React to display and manage a donation user interface. In other words, the <code>&lt;div&gt;</code> represents the website’s section you want React to manage.</p>
<p>Some notes:</p>
<ul>
<li><p>The <code>div</code>’s <code>id</code> attribute is the reference we’ll later use in a JavaScript file to find the container and tell React to insert a donation UI.</p>
</li>
<li><p>Although most developers use a <code>&lt;div&gt;</code> tag as the DOM container, you can use other HTML elements like the <code>&lt;main&gt;</code> tag.</p>
</li>
<li><p>You can have multiple DOM containers anywhere inside the <code>&lt;body&gt;</code> element.</p>
</li>
<li><p>A DOM container is usually left empty, as React will overwrite its content.</p>
</li>
</ul>
<h3 id="heading-import-react-babel-and-your-component">Import React, Babel, and your component</h3>
<p>Use script tags to load React, Babel, and your component into your project’s HTML page.</p>
<pre><code class="lang-xml"><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-US"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>CodeSweetly Donation UI<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Load the React Library --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/react@18/umd/react.development.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Load the ReactDOM API --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/react-dom@18/umd/react-dom.development.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Load the Babel Compiler --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/@babel/standalone/babel.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">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">"donation-ui"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Load your React component --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/babel"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"DonationUserInterface.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>The snippet above uses the first three script tags to load React, ReactDOM, and Babel from unpkg.com.</p>
<p>At the same time, we use the fourth script tag to import our donation component (which we will create in the following section).</p>
<p>Some notes:</p>
<ul>
<li><p>The <code>react</code> package is a library containing React’s core functionality for creating React components.</p>
</li>
<li><p>The ReactDOM API provides the required methods to use React with the DOM.</p>
</li>
<li><p>Babel is a compiler that transforms React code into plain JavaScript, as browsers don’t understand React syntax by default.</p>
</li>
<li><p>The <code>type="text/babel"</code> attribute tells Babel to automatically execute and convert the <code>DonationUserInterface.js</code> script from React code into plain JavaScript.</p>
</li>
<li><p>The setup above is recommended for learning React only. Don’t use it for public projects (production environment). You can learn how to set up React for production in my <a target="_blank" href="https://www.amazon.com/dp/B0FRC4R8T3?tag=codesweetly00-20">Code React Sweetly book</a>.</p>
</li>
<li><p>The scripts will not work if your internet or <code>unpkg.com</code>’s server is down. So, if nothing renders on-screen, enter each script’s <code>src</code> URL in your browser to confirm if the server responds successfully.</p>
</li>
</ul>
<h3 id="heading-create-your-component">Create your component</h3>
<p>Create a <code>DonationUserInterface.js</code> JavaScript file inside the same folder in which your HTML file is located.</p>
<pre><code class="lang-bash">touch DonationUserInterface.js
</code></pre>
<p>Then, paste the following code inside the JavaScript file you’ve just created:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">DonationUserInterface</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [donate, setDonate] = React.useState(<span class="hljs-literal">false</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createUserInterface</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">if</span> (donate) {
      <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://www.buymeacoffee.com/codesweetly"</span>&gt;</span>Support page<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>.
          Thank you so much! 🎉
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</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">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setDonate(true)}&gt;☕ Buy me a coffee<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>;
  }
  <span class="hljs-keyword">return</span> createUserInterface();
}

<span class="hljs-keyword">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"donation-ui"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">DonationUserInterface</span> /&gt;</span></span>);
</code></pre>
<p>The snippet above does the following:</p>
<ol>
<li><p>Defines a component named <code>DonationUserInterface</code>.</p>
</li>
<li><p>Initializes the component’s state (built-in object) with the Boolean value <code>false</code>.</p>
</li>
<li><p>Programs the component to return a paragraph element if the state’s <code>donate</code> variable is <code>true</code>. Otherwise, it should return a button element.</p>
</li>
<li><p>Creates a <code>ReactDOMRoot</code> object instance for the <code>donation-ui</code> HTML element you want React to manage. Afterwards, it assigns the newly created instance to the <code>root</code> variable.</p>
</li>
<li><p>Uses the object instance’s <code>render()</code> method to display the <code>DonationUserInterface</code> component inside the root <code>donation-ui</code>.</p>
</li>
</ol>
<h3 id="heading-configure-a-local-server">Configure a local server</h3>
<p>HTML files containing <a target="_blank" href="https://codesweetly.com/javascript-modules-tutorial/">ES modules</a> work only through <code>http://</code> and <code>https://</code> URLs, not locally via a <code>file://</code> URL.</p>
<p>Since we previously used the <code>type="text/babel"</code> attribute to convert the <code>DonationUserInterface.js</code> JavaScript file to an ES module, we need a local server, like “Live Server” or “Servor,” to load the HTML document via an <code>http://</code> scheme. Let’s install Servor so we can use it for this project.</p>
<h4 id="heading-install-the-servor-local-server">Install the Servor local server</h4>
<pre><code class="lang-bash">npm install servor@4.0.2 --save-dev
</code></pre>
<h4 id="heading-run-your-app">Run your app</h4>
<p>After installing Servor, use it to start your app from your terminal:</p>
<pre><code class="lang-bash">npx servor --browse --reload
</code></pre>
<p>Some notes:</p>
<ul>
<li><p>Close the server using <kbd>Ctrl</kbd> + <kbd>C</kbd> on Windows or <kbd>Cmd</kbd> + <kbd>C</kbd> on Mac.</p>
</li>
<li><p><code>--browse</code>: Opens the browser once the server starts.</p>
</li>
<li><p><code>--reload</code>: Reloads the browser whenever you update the project’s files.</p>
</li>
<li><p>You can also add the <code>servor</code> command to the <code>"scripts"</code> field of your project’s <code>package.json</code> file:</p>
</li>
</ul>
<pre><code class="lang-json">{
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"start"</span>: <span class="hljs-string">"servor --browse --reload"</span>
  },
  <span class="hljs-attr">"devDependencies"</span>: {
    <span class="hljs-attr">"servor"</span>: <span class="hljs-string">"^4.0.2"</span>
  }
}
</code></pre>
<p>By doing so, you can run your app from your terminal like this:</p>
<pre><code class="lang-bash">npm run start
</code></pre>
<p>And that’s it! You’ve successfully added a React component to a live website using a JavaScript function to render a donation UI on screen! 🎉</p>
<p>Are you asking why we’re writing HTML inside JavaScript? Well, that HTML-like code is called JSX. Let’s learn about it.</p>
<h2 id="heading-what-is-jsx">What Is JSX?</h2>
<p>JSX is a JavaScript syntax extension that allows you to build React elements with HTML-like syntax directly inside your JavaScript code.</p>
<p><strong>Tips:</strong></p>
<ul>
<li><p>JSX is sometimes called JavaScript XML or JavaScript Syntax eXtension.</p>
</li>
<li><p>While JSX looks a lot like HTML, it’s not HTML. Instead, it enables you to use HTML-like syntax along with all the strengths of JavaScript.</p>
</li>
</ul>
<h3 id="heading-can-react-work-without-jsx">Can React work without JSX?</h3>
<p>Yes. React can work independently of JSX. But JSX makes it easier to create user interfaces (UI).</p>
<p>In other words, whatever you can do with JSX, you can do the same with plain JavaScript. For instance, consider the two examples below. The first includes JSX syntax, while the second is regular JavaScript syntax.</p>
<h4 id="heading-example-1-create-a-react-element-with-jsx">Example 1: Create a React element with JSX</h4>
<p><code>MyBio.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyBio</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My name is Oluwatobi.<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}
<span class="hljs-keyword">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">MyBio</span> /&gt;</span></span>);
</code></pre>
<p><code>index.html</code></p>
<pre><code class="lang-xml"><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-US"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>MyBio App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/react@18/umd/react.development.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/react-dom@18/umd/react-dom.development.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/@babel/standalone/babel.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">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">"root"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/babel"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"MyBio.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In the React snippet above, <code>&lt;h1&gt;My name is Oluwatobi.&lt;/h1&gt;</code> and <code>&lt;MyBio /&gt;</code> are JSX.</p>
<p><strong>Tip:</strong> React supports the <code>.jsx</code> file extension for files with JSX code. So, if you prefer to differentiate your JSX files from JavaScript, you can rename <code>MyBio.js</code> to <code>MyBio.jsx</code>. Just note that choosing between using <code>.js</code> vs <code>.jsx</code> for files with JSX is entirely up to you. (Your JSX code is simply a syntactic sugar for the <code>React.createElement()</code> JavaScript call.)</p>
<h4 id="heading-example-2-create-a-react-element-with-regular-javascript">Example 2: Create a React element with regular JavaScript</h4>
<p><code>MyBio.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyBio</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> React.createElement(<span class="hljs-string">"h1"</span>, <span class="hljs-literal">null</span>, <span class="hljs-string">"My name is Oluwatobi."</span>);
}
<span class="hljs-keyword">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(React.createElement(MyBio));
</code></pre>
<p><code>index.html</code></p>
<pre><code class="lang-xml"><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-US"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>MyBio App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/react@18/umd/react.development.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/react-dom@18/umd/react-dom.development.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/@babel/standalone/babel.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">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">"root"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/babel"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"MyBio.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Everything in the React snippet above is plain JavaScript code.</p>
<h2 id="heading-what-is-reactcreateelement">What Is React.createElement()?</h2>
<p><code>React.createElement()</code> is the JavaScript alternative to JSX. It is a method for creating React elements in regular JavaScript.</p>
<p>Browsers can’t read the JSX syntax. This is why we typically use tools like Babel, TypeScript, and Parcel to compile JSX to a <code>React.createElement(component, props, ...children)</code> JavaScript call.</p>
<p>For instance, <code>&lt;button className="support-btn"&gt;Buy me a coffee&lt;/button&gt;</code> will transform to <code>React.createElement("button", { className: "support-btn" }, "Buy me a coffee ")</code> at runtime.</p>
<p>Under the hood, the <code>React.createElement()</code> method creates a JavaScript object conventionally called “React element.”</p>
<p><strong>Tip:</strong> A React element is a JavaScript object that defines the user interface (UI) you want to render on screen.</p>
<p>A simplified version of a React element looks like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myBioReactElement = {
  <span class="hljs-attr">type</span>: <span class="hljs-string">"h1"</span>,
  <span class="hljs-attr">props</span>: {
    <span class="hljs-attr">className</span>: <span class="hljs-literal">null</span>,
    <span class="hljs-attr">children</span>: <span class="hljs-string">"My name is Oluwatobi."</span>,
  },
};
</code></pre>
<p><code>React.createElement()</code> is best for projects that want to avoid compiling tools like Babel. Whereas JSX is a syntactic sugar that makes React code easier to read. So, you are free to choose the syntax that works best for you (but most React projects use JSX for its simplicity).</p>
<h2 id="heading-how-to-use-jsx">How to Use JSX</h2>
<p>The following tips will help you get up and running with JSX so you can use it in your React projects.</p>
<h3 id="heading-use-jsx-like-any-javascript-expression">Use JSX like any JavaScript expression</h3>
<p>You can use JSX like any other JavaScript expression because, at <a target="_blank" href="https://codesweetly.com/web-tech-terms-e/#execution-time">execution time</a>, JSX transpiles into regular JavaScript.</p>
<p>In other words, you can store JSX expressions in variables, use them in <code>if</code> statements, or make them the return value of functions.</p>
<p><strong>Example:</strong></p>
<p><code>DisplayMyName.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> firstName = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">const</span> myFirstName = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My first name is Oluwatobi.<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
<span class="hljs-keyword">const</span> mylastName = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My last name is Sofela.<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">DisplayMyName</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (firstName) {
    <span class="hljs-keyword">return</span> myFirstName;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> mylastName;
  }
}
<span class="hljs-keyword">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">DisplayMyName</span> /&gt;</span></span>);
</code></pre>
<p><code>index.html</code></p>
<pre><code class="lang-xml"><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-US"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>DisplayMyName App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/react@18/umd/react.development.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/react-dom@18/umd/react-dom.development.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/@babel/standalone/babel.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">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">"root"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/babel"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"DisplayMyName.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>The React snippet above stores JSX code in variables. We also made it the return value of a function’s <code>if...else</code> statement.</p>
<h3 id="heading-wrap-multi-line-jsx-in-parentheses">Wrap multi-line JSX in parentheses</h3>
<p>Wrapping your JSX code in parentheses is best when it spans across multiple lines. Doing so will make your code readable and avoid the <a target="_blank" href="https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi">pitfalls of automatic semicolon insertion</a>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myName = (
  <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>My name is Oluwatobi.<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
);
</code></pre>
<p>The snippet above wraps the <code>div</code> in parentheses because it spans multiple lines.</p>
<h3 id="heading-wrap-expressions-in-curly-braces">Wrap expressions in curly braces</h3>
<p>Suppose you wish to write JavaScript expressions in your JSX code. In that case, wrap the expression in curly braces like so:</p>
<p><code>ExpressionInJSX.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ExpressionInJSX</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">h2</span>&gt;</span>JSX makes it {10 * 3} times faster to build React UIs.<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span></span>;
}
<span class="hljs-keyword">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ExpressionInJSX</span> /&gt;</span></span>);
</code></pre>
<p><code>index.html</code></p>
<pre><code class="lang-xml"><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-US"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>ExpressionInJSX App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/react@18/umd/react.development.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/react-dom@18/umd/react-dom.development.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/@babel/standalone/babel.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">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">"root"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/babel"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"ExpressionInJSX.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><strong>Tips:</strong></p>
<ul>
<li><p>React reads curly braces (<code>{...}</code>) in JSX code as a JavaScript expression.</p>
</li>
<li><p>Using curly braces to embed a JavaScript expression works only if you use it in either of two ways:</p>
<ol>
<li><p>Directly between the opening and closing JSX tags:</p>
<pre><code class="lang-xml"> <span class="hljs-tag">&lt;<span class="hljs-name">openingTag</span>&gt;</span>I have a {javaScriptExpression} content.<span class="hljs-tag">&lt;/<span class="hljs-name">closingTag</span>&gt;</span>
</code></pre>
</li>
<li><p>As the value of a JSX element’s attribute:</p>
<pre><code class="lang-xml"> <span class="hljs-tag">&lt;<span class="hljs-name">openingTag</span> <span class="hljs-attr">attribute</span>=<span class="hljs-string">{javaScriptExpression}</span>&gt;</span>I have a content<span class="hljs-tag">&lt;/<span class="hljs-name">closingTag</span>&gt;</span>
</code></pre>
</li>
</ol>
</li>
</ul>
<h3 id="heading-use-camelcase-to-name-attributes">Use camelCase to name attributes</h3>
<p>React uses <a target="_blank" href="https://codesweetly.com/naming-convention-explained/#what-is-camelcase">camelCase</a> for JSX attribute keys rather than the lowercase HTML attribute naming convention. This is because, under the hood, JSX compiles into plain JavaScript and, therefore, uses the JavaScript Web APIs.</p>
<p>In other words, instead of writing <code>readonly</code>, use <code>readOnly</code>. Likewise, instead of using <code>maxlength</code>, write <code>maxLength</code>. By doing so, React will gain access to JavaScript’s <code>readOnly</code> and <code>maxLength</code> Web APIs.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myName = (
  <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> <span class="hljs-attr">className</span>=<span class="hljs-string">"about-me"</span>&gt;</span>My name is Oluwatobi.<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
);
</code></pre>
<h3 id="heading-close-empty-jsx-tags-properly">Close empty JSX tags properly</h3>
<p>React requires closing all JSX elements explicitly with <code>/&gt;</code>, including empty tags. For instance, you’ll need to write an HTML <code>&lt;img&gt;</code> element as <code>&lt;img /&gt;</code>.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> emptyJSXElement = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Click me"</span> /&gt;</span></span>;
</code></pre>
<h3 id="heading-a-react-component-can-return-only-a-single-element">A React component can return only a single element</h3>
<p>Creating two or more JSX elements from a component requires wrapping them in a single parent element. Otherwise, React will throw an error. This is because React components return only a single element.</p>
<p><strong>Example:</strong></p>
<p><code>TwoInnerUIs.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TwoInnerUIs</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My name is Oluwatobi.<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Buy me a coffee<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">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">TwoInnerUIs</span> /&gt;</span></span>);
</code></pre>
<p><code>index.html</code></p>
<pre><code class="lang-xml"><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-US"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>TwoInnerUIs App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/react@18/umd/react.development.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/react-dom@18/umd/react-dom.development.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/@babel/standalone/babel.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">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">"root"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/babel"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"TwoInnerUIs.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In the expression above, the <code>&lt;div&gt;</code> is a parent element containing two (2) inner tags.</p>
<p><strong>Tip:</strong> React allows using a <a target="_blank" href="https://react.dev/reference/react/Fragment">fragment</a> (empty tag) to group elements. Here’s an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TwoInnerUIs</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My name is Oluwatobi.<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Buy me a coffee<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}
<span class="hljs-keyword">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">TwoInnerUIs</span> /&gt;</span></span>);
</code></pre>
<p>Fragments are a great way to return multiple elements without creating unnecessary tags in the HTML DOM.</p>
<h2 id="heading-time-to-practice-with-jsx">Time to Practice with JSX 🤸‍♂️🏋️‍♀️🏊‍♀️</h2>
<p>Here is your moment to practice the JSX concepts you’ve learned.</p>
<p>In this exercise, you will convert the regular JavaScript code below to its JSX equivalent:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SupportCodeSweetly</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> React.createElement(
    <span class="hljs-string">"div"</span>,
    { <span class="hljs-attr">className</span>: <span class="hljs-string">"support-ui"</span> },
    React.createElement(
      <span class="hljs-string">"a"</span>,
      {
        <span class="hljs-attr">id</span>: <span class="hljs-string">"support-link"</span>,
        <span class="hljs-attr">className</span>: <span class="hljs-string">"support-link"</span>,
        <span class="hljs-attr">target</span>: <span class="hljs-string">"_blank"</span>,
        <span class="hljs-attr">href</span>: <span class="hljs-string">"https://www.buymeacoffee.com/codesweetly"</span>,
      },
      <span class="hljs-string">"Buy me a coffee"</span>
    ),
    <span class="hljs-string">". Thank you!"</span>
  );
}

<span class="hljs-keyword">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(React.createElement(SupportCodeSweetly));
</code></pre>
<p>Take a moment to try it yourself before looking at the solution below. Even if you have to try a couple times, go back and read the above tips, or google a few things, it’ll help you learn the concepts better.</p>
<p>Ok, now that you’ve tried…</p>
<h3 id="heading-the-solution">The solution:</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">SupportCodeSweetly</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">"support-ui"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">a</span>
        <span class="hljs-attr">id</span>=<span class="hljs-string">"support-link"</span>
        <span class="hljs-attr">className</span>=<span class="hljs-string">"support-link"</span>
        <span class="hljs-attr">target</span>=<span class="hljs-string">"_blank"</span>
        <span class="hljs-attr">href</span>=<span class="hljs-string">"https://www.buymeacoffee.com/codesweetly"</span>
      &gt;</span>
        Buy me a coffee
      <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
      . Thank you!
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">SupportCodeSweetly</span> /&gt;</span></span>);
</code></pre>
<p>The <code>SupportCodeSweetly</code> component returns the UI we want to display on-screen and manage with React. But what exactly is a React component?</p>
<h2 id="heading-what-is-a-react-component">What Is a React Component?</h2>
<p>A component in React is a class or function that accepts a single argument called <code>props</code> and returns an element (UI).</p>
<h3 id="heading-syntax-of-a-react-component">Syntax of a React component</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760626118056/8fb5818f-b39a-42c7-9399-1acc476604ee.webp" alt="React component syntax" class="image--center mx-auto" width="1920" height="1920" loading="lazy"></p>
<p>The above image illustrates the constituent parts of a React component:</p>
<ol>
<li><p>A JavaScript function with a Pascal case naming convention.</p>
</li>
<li><p>A props parameter, which is the only argument React components accept. (Tip: props is short for properties.)</p>
</li>
<li><p>The component’s body, where you place a sequence of statements like variables, hooks, and conditionals.</p>
</li>
<li><p>A return statement, which is used to output the user interface (UI) you want React to display on-screen. It can be any valid HTML element.</p>
</li>
<li><p>An invocator that executes the component to retrieve its user interface. The invocator can also pass arguments (props) to the component.</p>
</li>
</ol>
<h3 id="heading-example-of-a-react-component">Example of a React component</h3>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyBio</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>My name is {props.firstName}.<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/jlj9lg?file=%2Fsrc%2Findex.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The code in the snippet above is a function component that accepts a single argument (props) and returns a React element.</p>
<h3 id="heading-react-components-best-practices">React components best practices</h3>
<p>When you’re working with components in React, there are a few best practices you should follow:</p>
<ul>
<li><p>Capitalize the first letter of your component’s name.</p>
</li>
<li><p>Don’t use bracket notation expressions in React component tags.</p>
</li>
<li><p>React components work best as pure functions.</p>
</li>
<li><p>Create components at the top level of your file.</p>
</li>
<li><p>Split long components into smaller chunks.</p>
</li>
</ul>
<p>As it’s common practice to use components to render a list of elements, let’s now discuss how to implement this optimally.</p>
<h2 id="heading-how-to-render-lists-of-elements-from-an-array">How to Render Lists of Elements from an Array</h2>
<p>Suppose you want to create a list of React elements from an array of data. You can use the JavaScript <a target="_blank" href="https://codesweetly.com/javascript-map-method/"><code>map()</code></a> method.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;

<span class="hljs-comment">// Define the bestColors array:</span>
<span class="hljs-keyword">const</span> bestColors = [<span class="hljs-string">"Blue"</span>, <span class="hljs-string">"White"</span>, <span class="hljs-string">"Pink"</span>];

<span class="hljs-comment">// Use the bestColors array to create a list of React elements:</span>
<span class="hljs-keyword">const</span> bestColorsLiElements = bestColors.map(<span class="hljs-function">(<span class="hljs-params">color</span>) =&gt;</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>{color}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>);

<span class="hljs-comment">// Render the array of &lt;li&gt; elements to the root DOM:</span>
<span class="hljs-keyword">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>{bestColorsLiElements}<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>);
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/dcwwqr?file=%2Fsrc%2Findex.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above used <code>map()</code> to create a new list of React elements by converting each of <code>bestColors</code> items to <code>&lt;li&gt;</code> elements.</p>
<p>Notice that we rendered the list of elements directly in the <code>root.render()</code> method. Typically, you would use a component to do such rendering. So, let’s do some refactoring by moving the <code>bestColorsLiElements</code> variable and the <code>&lt;ul&gt;</code> element into a component:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BestColor</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Define the bestColors array:</span>
  <span class="hljs-keyword">const</span> bestColors = [<span class="hljs-string">"Blue"</span>, <span class="hljs-string">"White"</span>, <span class="hljs-string">"Pink"</span>];
  <span class="hljs-comment">// Use the bestColors array to create a list of React elements:</span>
  <span class="hljs-keyword">const</span> bestColorsLiElements = bestColors.map(<span class="hljs-function">(<span class="hljs-params">color</span>) =&gt;</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>{color}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>);
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>{bestColorsLiElements}<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>;
}

<span class="hljs-comment">// Render the array of &lt;li&gt; elements to the root DOM:</span>
<span class="hljs-keyword">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">BestColor</span> /&gt;</span></span>);
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/pj62c3?file=%2Fsrc%2Findex.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>Although the snippet above displays the right content on the screen, it’s not efficient. So, React throws a console error. Let’s discuss the issue.</p>
<h3 id="heading-each-react-element-in-an-array-needs-a-unique-key">Each React element in an array needs a unique key</h3>
<p>If you check your console, you will see a warning message that says: <code>Each child in a list should have a unique "key" prop.</code></p>
<p>The message means that whenever you create an array of elements, React needs you to specify a unique identity for each item in the list.</p>
<p>The unique identity keys help React identify changes to the array.</p>
<p>Let’s refactor the previous snippet so that each element in the <code>bestColorsLiElements</code> has a unique <code>key</code> prop.</p>
<h3 id="heading-how-to-add-unique-keys-to-each-react-element-in-an-array">How to add unique keys to each React element in an array</h3>
<p>There are two common ways to assign unique keys to each element of an array. The first is the unrecommended way. While the second is the best technique, it is worth noting.</p>
<h4 id="heading-not-recommended-way-to-assign-keys-to-an-array-of-react-elements">Not recommended way to assign keys to an array of React elements</h4>
<p>One way to add unique keys is to use each item’s index as its <code>key</code> prop.</p>
<p><strong>Tip:</strong> By default, if you don’t provide a <code>key</code> prop, React uses each element’s index position in the array to identify them (<code>key=0</code>, <code>key=1</code>, and so on).</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BestColor</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> bestColors = [<span class="hljs-string">"Blue"</span>, <span class="hljs-string">"White"</span>, <span class="hljs-string">"Pink"</span>];
  <span class="hljs-comment">// Use each item's index as its key prop:</span>
  <span class="hljs-keyword">const</span> bestColorsLiElements = bestColors.map(<span class="hljs-function">(<span class="hljs-params">color, index</span>) =&gt;</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{index}</span>&gt;</span>{color}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
  ));
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>{bestColorsLiElements}<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>;
}

<span class="hljs-keyword">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">BestColor</span> /&gt;</span></span>);
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/yxp4sz?file=%2Fsrc%2Findex.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above specifies a <code>key</code> prop on each <code>&lt;li&gt;</code> element. It then uses each item’s <code>index</code> as the prop’s value.</p>
<p>But note that it’s best to avoid using indexes as a React element’s <code>key</code> prop. You should use it only as a last resort when you don’t have stable IDs.</p>
<p>Whenever you use an index as the <code>key</code> prop, ensure the order of items in the array never changes. Otherwise, you may have severe issues with performance and component state.</p>
<h4 id="heading-best-way-to-assign-keys-to-an-array-of-react-elements">Best way to assign keys to an array of React elements</h4>
<p>The best way to add unique keys to each React element in an array is to use stable IDs from either of the following sources:</p>
<ul>
<li><p><strong>Database:</strong> Use the database-generated IDs as the <code>key</code> props if your data comes from a database, as they are unique by default.</p>
</li>
<li><p><code>crypto.randomUUID()</code> <strong>incrementing counter:</strong> Use the <code>randomUUID()</code> method to generate Universally Unique Identifiers if you are creating and storing your data locally. (Note: This method is a web API. So, it’s available only in supporting browsers’ HTTPS contexts.)</p>
</li>
<li><p><code>uuid</code>: An NPM package for generating Universally Unique Identifiers if you are creating and persisting your data locally. This is a good alternative to the <code>randomUUID()</code> method for cross-platform compatibility.</p>
</li>
</ul>
<p><strong>Example:</strong></p>
<p><code>index.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createRoot } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;
<span class="hljs-keyword">import</span> { bestColors } <span class="hljs-keyword">from</span> <span class="hljs-string">"./bestColors.js"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BestColor</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Use each item's id as its key prop:</span>
  <span class="hljs-keyword">const</span> bestColorsLiElements = bestColors.map(<span class="hljs-function">(<span class="hljs-params">color</span>) =&gt;</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{color.id}</span>&gt;</span>{color.name}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
  ));
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>{bestColorsLiElements}<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>;
}

<span class="hljs-keyword">const</span> root = createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">BestColor</span> /&gt;</span></span>);
</code></pre>
<p><code>bestColors.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> bestColors = [
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"Blue"</span> },
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"White"</span> },
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"Pink"</span> },
];
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/n56z6x?file=%2Fsrc%2Findex.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above specifies a <code>key</code> prop on each <code>&lt;li&gt;</code> element. It then uses each item’s <code>id</code> as the prop’s value.</p>
<p><strong>Note:</strong> Each <code>key</code> prop should be unique among its siblings – not globally. It’s okay to use the same <code>key</code> for an element in a different array.</p>
<h3 id="heading-essential-things-to-know-about-assigning-keys">Essential things to know about assigning keys</h3>
<p>Here are essential facts to remember whenever you assign keys to an array of React elements.</p>
<h4 id="heading-1-set-each-array-elements-key-while-creating-the-array">1. Set each array element’s key while creating the array</h4>
<p>The right place to specify each array element’s unique key is directly inside the <code>map()</code> method <em>while creating the list of elements</em>.</p>
<p>In other words, say you extract your template element into a separate component. Set the <code>key</code> prop on the component’s invocation tag—not on the extracted template element.</p>
<p><strong>Example 1: Incorrect placement of the key prop</strong></p>
<p><code>index.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createRoot } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;
<span class="hljs-keyword">import</span> { bestColors } <span class="hljs-keyword">from</span> <span class="hljs-string">"./bestColors.js"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ColorListElement</span>(<span class="hljs-params">{ color }</span>) </span>{
  <span class="hljs-comment">// WRONG: Don't place the key outside the map() method.</span>
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{color.id}</span>&gt;</span>{color.name}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BestColor</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> bestColorsLiElements = bestColors.map(<span class="hljs-function">(<span class="hljs-params">color</span>) =&gt;</span> (
    <span class="hljs-comment">// The key attribute above should have been set here.</span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ColorListElement</span> <span class="hljs-attr">color</span>=<span class="hljs-string">{color}</span> /&gt;</span></span>
  ));
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>{bestColorsLiElements}<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>;
}

<span class="hljs-keyword">const</span> root = createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">BestColor</span> /&gt;</span></span>);
</code></pre>
<p><code>bestColors.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> bestColors = [
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"Blue"</span> },
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"White"</span> },
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"Pink"</span> },
];
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/frcspn?file=%2Fsrc%2Findex.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above incorrectly sets each item’s key outside the <code>map()</code> method. You should avoid such a mistake!</p>
<p>Always set the <code>key</code> prop <em>while creating the array of elements</em>. So, the snippet above should have set the <code>key</code> on the component invocation tag – in the <code>map()</code> method.</p>
<p><strong>Example 2: Correct placement of the key prop</strong></p>
<p><code>index.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createRoot } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;
<span class="hljs-keyword">import</span> { bestColors } <span class="hljs-keyword">from</span> <span class="hljs-string">"./bestColors.js"</span>;

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

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BestColor</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> bestColorsLiElements = bestColors.map(<span class="hljs-function">(<span class="hljs-params">color</span>) =&gt;</span> (
    <span class="hljs-comment">// CORRECT: Always define the key directly inside the map() method.</span>
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ColorListElement</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{color.id}</span> <span class="hljs-attr">color</span>=<span class="hljs-string">{color}</span> /&gt;</span></span>
  ));
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>{bestColorsLiElements}<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>;
}

<span class="hljs-keyword">const</span> root = createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">BestColor</span> /&gt;</span></span>);
</code></pre>
<p><code>bestColors.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> bestColors = [
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"Blue"</span> },
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"White"</span> },
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"Pink"</span> },
];
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/n9m7w2?file=%2Fsrc%2Findex.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above correctly sets each item’s key inside the <code>map()</code> method. This allows React to access the <code>key</code> value for each element in the array returned by the <code>map()</code> method.</p>
<p><strong>Tip:</strong> React’s reconciliation (diffing) algorithm is programmed to access the <code>key</code> of each top-level item of the array. It never looks for the <code>key</code> in the child or descendant elements.</p>
<h4 id="heading-2-react-does-not-pass-keys-to-components">2. React does not pass keys to components</h4>
<p>React neither transfers the <code>key</code> prop to components nor includes it as an attribute of a rendered element.</p>
<p>React uses keys solely to know the state of array items. They help React identify changes to the array.</p>
<p>So if you need to use a specific key’s value in your component or on your DOM element, you should explicitly pass it as the value of a different attribute.</p>
<p><strong>Example:</strong></p>
<p><code>index.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createRoot } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;
<span class="hljs-keyword">import</span> { bestColors } <span class="hljs-keyword">from</span> <span class="hljs-string">"./bestColors.js"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ColorListElement</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>
      {props.color.name} (ID: {props.id})
    <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
  );
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BestColor</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Use `color.id` as the `key` and `id` props' value.</span>
  <span class="hljs-keyword">const</span> bestColorsLiElements = bestColors.map(<span class="hljs-function">(<span class="hljs-params">color</span>) =&gt;</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ColorListElement</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{color.id}</span> <span class="hljs-attr">id</span>=<span class="hljs-string">{color.id}</span> <span class="hljs-attr">color</span>=<span class="hljs-string">{color}</span> /&gt;</span></span>
  ));
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>{bestColorsLiElements}<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>;
}

<span class="hljs-keyword">const</span> root = createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">BestColor</span> /&gt;</span></span>);
</code></pre>
<p><code>bestColors.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> bestColors = [
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"Blue"</span> },
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"White"</span> },
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"Pink"</span> },
];
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/v7yflr?file=%2Fsrc%2Findex.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above initializes each list item’s <code>id</code> attribute with the same value as the <code>key</code> prop. By so doing, the <code>ColorListElement</code> component can access <code>props.id</code> but not <code>props.key</code>.</p>
<h4 id="heading-3-always-generate-the-keys-outside-your-components">3. Always generate the keys outside your components</h4>
<p>Never generate keys on the fly (while <a target="_blank" href="https://codesweetly.com/web-tech-terms-r/#react-render">rendering</a> your components). Instead, create them in your data outside your components. Otherwise, React will recreate the elements on every rendering cycle because the <code>key</code>’s value will always be different.</p>
<p><strong>Example 1: Incorrect place to generate the key prop</strong></p>
<p><code>index.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createRoot } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;
<span class="hljs-keyword">import</span> { bestColors } <span class="hljs-keyword">from</span> <span class="hljs-string">"./bestColors.js"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BestColor</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// WRONG: Never generate keys on the fly.</span>
  <span class="hljs-keyword">const</span> bestColorsLiElements = bestColors.map(<span class="hljs-function">(<span class="hljs-params">color</span>) =&gt;</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{crypto.randomUUID()}</span>&gt;</span>{color}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
  ));
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>{bestColorsLiElements}<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>;
}

<span class="hljs-keyword">const</span> root = createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">BestColor</span> /&gt;</span></span>);
</code></pre>
<p><code>bestColors.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// The keys' values should have been set here (outside the component while creating your data).</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> bestColors = [<span class="hljs-string">"Blue"</span>, <span class="hljs-string">"White"</span>, <span class="hljs-string">"Pink"</span>];
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/lhwknv?file=%2Fsrc%2Findex.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above incorrectly generated each element’s key while rendering the <code>BestColor</code> component. You should avoid such a mistake to prevent subtle bugs caused by recreating the elements on every render.</p>
<p>Always create each <code>key</code>’s value in your data outside the component.</p>
<p><strong>Example 2: Correct place to generate the key prop</strong></p>
<p><code>index.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createRoot } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;
<span class="hljs-keyword">import</span> { bestColors } <span class="hljs-keyword">from</span> <span class="hljs-string">"./bestColors.js"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BestColor</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> bestColorsLiElements = bestColors.map(<span class="hljs-function">(<span class="hljs-params">color</span>) =&gt;</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{color.id}</span>&gt;</span>{color.name}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
  ));
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>{bestColorsLiElements}<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>;
}

<span class="hljs-keyword">const</span> root = createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">BestColor</span> /&gt;</span></span>);
</code></pre>
<p><code>bestColors.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// CORRECT: Always generate the key in your data outside the component.</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> bestColors = [
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"Blue"</span> },
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"White"</span> },
  { <span class="hljs-attr">id</span>: crypto.randomUUID(), <span class="hljs-attr">name</span>: <span class="hljs-string">"Pink"</span> },
];
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/n56z6x?file=%2Fsrc%2Findex.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above correctly generated each element’s key in the array data outside the component.</p>
<h2 id="heading-how-to-handle-events-in-react">How to Handle Events in React</h2>
<p>Event handling in React involves configuring your JSX elements to respond to user interactions on them (such as mouse clicks, form submission, and element focus).</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">jsxTag</span> <span class="hljs-attr">onEvent</span>=<span class="hljs-string">{handleEvent}</span>&gt;</span>UI Content<span class="hljs-tag">&lt;/<span class="hljs-name">jsxTag</span>&gt;</span>
</code></pre>
<p>Here’s what’s going on:</p>
<ul>
<li><p><code>jsxTag</code>: React elements like <code>&lt;div&gt;</code>, <code>&lt;button&gt;</code>, and <code>&lt;input&gt;</code>.</p>
</li>
<li><p><code>onEvent</code>: The event listener you want to add to the React element. Some examples are <code>onClick</code>, <code>onBlur</code>, and <code>onHover</code>.</p>
</li>
<li><p><code>handleEvent</code>: The event handler function you want to use to handle (respond to) the specified <code>onEvent</code> type.</p>
</li>
</ul>
<p><strong>Tip:</strong> Although you can name the event handler anything you prefer, the typical naming convention is to prefix the event’s name with “handle”. For instance, if the event’s name is <code>focus</code>, the handler’s name will be <code>handleFocus</code>.</p>
<h3 id="heading-types-of-event-handlers">Types of event handlers</h3>
<p>There are two typical ways to define the event handler function in React:</p>
<ul>
<li><p><strong>Inline event handler:</strong> A function defined directly on a JSX element’s opening tag as the value of the event listener prop (<code>onEvent</code>).</p>
</li>
<li><p><strong>Referenced event handler:</strong> A function defined as a separate (independent) logic and linked to an event listener attribute (<code>onEvent</code>) by name referencing.</p>
</li>
</ul>
<h4 id="heading-example-inline-event-handler">Example: Inline event handler</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> alert("You clicked the heading!")}&gt;
      Oluwatobi is my name.
    <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
  );
}
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/7tx7l5?file=%2Fsrc%2Fcomponents%2FApp.js"><strong>Try it on CodeSandbox</strong></a></p>
<h4 id="heading-example-referenced-event-handler">Example: Referenced event handler</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span>&gt;</span>Oluwatobi is my name.<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}

<span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">() =&gt;</span> alert(<span class="hljs-string">"You clicked the heading!"</span>);
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/msfszz?file=%2Fsrc%2Fcomponents%2FApp.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>React components have a unique memory that allows them to remember things between renderings. This memory is called “state.”</p>
<h2 id="heading-what-is-react-state">What Is React State?</h2>
<p>React state is a <em>component’s memory</em> for storing data that React should remember during a component’s re-rendering and whose update should trigger a new render.</p>
<h3 id="heading-syntax-of-react-state">Syntax of React state:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [state, setState] = useState(initialState);

  <span class="hljs-comment">// ...</span>
}
</code></pre>
<ul>
<li><p><code>state</code>: The variable containing the component’s state value.</p>
</li>
<li><p><code>setState</code>: A function for updating the state value.</p>
</li>
<li><p><code>useState</code>: The state Hook for initializing and retrieving the component’s state.</p>
</li>
</ul>
<h3 id="heading-example-of-react-state">Example of React state:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AboutCompany</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [age, setAge] = useState(<span class="hljs-number">5</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateAge</span>(<span class="hljs-params"></span>) </span>{
    setAge(age + <span class="hljs-number">1</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">h3</span>&gt;</span>CodeSweetly is {age} years old!<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{updateAge}</span>&gt;</span>
        Click to update age
      <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> AboutCompany;
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/9mlsl7?file=%2Fsrc%2FAboutCompany.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>When a user clicks the button UI, the <code>onClick</code> event triggers the <code>updateAge</code> event handler, which uses the <code>setAge</code> setter function to update the component’s <code>age</code> state.</p>
<p><strong>Tip:</strong> React will trigger a re-render of your component every time you use <code>useState</code>’s setter function to update your state. But what exactly do the terms “trigger” and “render” mean?</p>
<h3 id="heading-react-trigger-vs-render-vs-commit-vs-paint">React Trigger vs Render vs Commit vs Paint</h3>
<p>Triggering, rendering, committing, and painting are the steps involved in displaying React UIs on screen. Here are the differences between the four steps:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760637870319/ed8ae7a7-67c1-468a-ba5f-dbbafed8deb0.webp" alt="React Component's Lifecyle" class="image--center mx-auto" width="1920" height="1920" loading="lazy"></p>
<p>The above slide illustrates the four phases in the lifecycle of a component’s UI:</p>
<ul>
<li><p><strong>Trigger:</strong> Specifies the component whose UI you want to display on the screen.</p>
</li>
<li><p><strong>Render:</strong> Calls the component you’ve triggered.</p>
</li>
<li><p><strong>Commit:</strong> Updates the DOM with the UI of the rendered component.</p>
</li>
<li><p><strong>Paint:</strong> Converts the DOM code you’ve committed into user-friendly elements that users can interact with in their browsers.</p>
</li>
</ul>
<p>Let’s discuss these differences in detail.</p>
<h3 id="heading-what-does-it-mean-to-trigger-a-render-in-react">What does it mean to trigger a render in React?</h3>
<p>The trigger event is the first step in displaying a React user interface (UI) on screen. It specifies the component whose UI you want to display on the screen. This event happens on two occasions:</p>
<ol>
<li>When the app starts running. The React application uses the <code>createRoot</code> method to specify the component whose UI you want to render to a DOM node.</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;
<span class="hljs-keyword">import</span> DonationUI <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/DonationUI.js"</span>;

<span class="hljs-comment">// When the app starts running, you need to use createRoot and its render method to trigger an initial rendering of the app's root component.</span>
<span class="hljs-keyword">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">DonationUI</span> /&gt;</span></span>);
</code></pre>
<p>The snippet above does the following:</p>
<ul>
<li><p>Uses the <code>ReactDOM.createRoot()</code> method to create a <code>ReactDOMRoot</code> object instance for the <code>root</code> element argument.</p>
</li>
<li><p>Use the object instance’s <code>render()</code> method to trigger an initial rendering of the <code>DonationUI</code> component.</p>
</li>
</ul>
<p>In other words, the <code>createRoot().render()</code> method specifies <code>DonationUI</code> as the component whose UI React should display in the <code>root</code> HTML element.</p>
<ol start="2">
<li>The second reason a trigger event can happen is when a component’s (or its ancestors’) state gets updated with a set function.</li>
</ol>
<p><code>DonationUI.js</code></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">DonationUI</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [donate, setDonate] = React.useState(<span class="hljs-literal">false</span>);
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createUserInterface</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">if</span> (donate) {
      <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://www.buymeacoffee.com/codesweetly"</span>&gt;</span>Support page<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>.
          Thank you so much!
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
      );
    }
    <span class="hljs-comment">// The setDonate function will trigger a re-rendering of the DonationUI component.</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">{()</span> =&gt;</span> setDonate(true)}&gt;Buy me a coffee<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>;
  }
  <span class="hljs-keyword">return</span> createUserInterface();
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> DonationUI;
</code></pre>
<p>The snippet above does the following:</p>
<ol>
<li><p>Defines a component named <code>DonationUI</code>.</p>
</li>
<li><p>Initializes the component’s state with the Boolean value <code>false</code>.</p>
</li>
<li><p>Programs the component to return a paragraph element if the state’s <code>donate</code> variable is <code>true</code>. Otherwise, it should return a button element.</p>
</li>
</ol>
<p>When users click the button element, the <code>setDonate</code> setter function will trigger a re-rendering of the <code>DonationUI</code> component. Below are the entry script and the HTML code so you can try it yourself locally.</p>
<p><code>index.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;
<span class="hljs-keyword">import</span> DonationUI <span class="hljs-keyword">from</span> <span class="hljs-string">"./components/DonationUI"</span>;

<span class="hljs-keyword">const</span> root = ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>));
root.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">DonationUI</span> /&gt;</span></span>);
</code></pre>
<p><code>index.html</code></p>
<pre><code class="lang-xml"><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-US"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>CodeSweetly DonationUI<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">main</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"root"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"index.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/95nvmr?file=%2Fsrc%2Fcomponents%2FDonationUI.js"><strong>Try it on CodeSandbox</strong></a></p>
<h3 id="heading-what-does-it-mean-to-render-react-components">What does it mean to render React components?</h3>
<p>The rendering step is when React <a target="_blank" href="https://codesweetly.com/invoke-vs-call/">invokes (calls)</a> the component you’ve triggered with either the <code>createRoot</code> method or a set function. Rendering causes React to invoke a component to produce the UI you want to display on the screen. The component React will render depends on the moment the trigger event occurred:</p>
<ul>
<li><p><strong>For an initial trigger (at the start of the app),</strong> React will invoke the app’s root component.</p>
</li>
<li><p><strong>For update triggers (whenever a component’s state gets updated),</strong> React will call the function component whose state update initiated the trigger event.</p>
</li>
</ul>
<p><strong>Tip:</strong> Rendering a component means “calling a component” to retrieve its user interface (UI).</p>
<h3 id="heading-what-does-it-mean-to-commit-a-react-ui-to-the-browsers-dom">What does it mean to commit a React UI to the browser’s DOM?</h3>
<p>The committing stage is when React updates the DOM with the UI of the rendered component.</p>
<p>There are some important things to note about this process:</p>
<ul>
<li><p><strong>For an initial render (at the start of the app),</strong> React will initialize the root DOM with the root component’s UI. It will use the <code>appendChild()</code> JavaScript API to append the DOM nodes (UI) retrieved from the component into the app’s root HTML element.</p>
</li>
<li><p><strong>For subsequent re-rendering (after the initial commit),</strong> React will only update the DOM nodes if there’s a difference between the previous rendering output and the latest one. No changes will occur if the component’s latest output is the same as the previously committed one.</p>
</li>
</ul>
<h3 id="heading-what-does-it-mean-to-paint-the-dom-nodes-on-the-screen">What does it mean to paint the DOM nodes on the screen?</h3>
<p>The painting (browser rendering) stage is when the browser repaints the screen to convert the DOM code to user-friendly elements. This is a browser-level process that begins once React has finished updating (committing) the DOM nodes.</p>
<p>Sometimes, components need to store information that shouldn’t trigger a render when updated. In these situations, you can use a ref.</p>
<h2 id="heading-what-is-the-react-ref-hook">What Is the React Ref Hook?</h2>
<p>The React Ref Hook lets you store values that don’t trigger re-renders when changed.</p>
<h3 id="heading-syntax-of-the-react-ref-hook">Syntax of the React ref Hook</h3>
<p>The <code>useRef</code> Hook accepts only one optional argument. Here is the syntax:</p>
<pre><code class="lang-javascript">useRef(initialValue);
</code></pre>
<ul>
<li><p><code>initialValue</code>: The value to store in the component’s ref memory. Any JavaScript data type is allowed.</p>
</li>
<li><p><code>useRef()</code>: Returns an object (<code>{ current: initialValue }</code>).</p>
</li>
</ul>
<h3 id="heading-example-of-the-react-ref-hook">Example of the React ref Hook:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useRef } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> myNameRef = useRef(<span class="hljs-string">"Oluwatobi"</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(myNameRef.current); <span class="hljs-comment">// Outputs: "Oluwatobi"</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">{handleClick}</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>;
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/mgsxyq?file=%2Fsrc%2FApp.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above used the <code>useRef</code> Hook to store a value (<code>"Oluwatobi"</code>) whose update shouldn’t trigger re-renders.</p>
<h3 id="heading-react-ref-hook-best-practices">React ref Hook best practices</h3>
<p>When you’re working with React’s ref hook, there are some best practices you should follow:</p>
<ul>
<li><p>Use dot syntax to access and update a ref object’s value instead of square bracket notation.</p>
</li>
<li><p>Avoid accessing or updating the <code>current</code> property during rendering to maintain the purity of your components.</p>
</li>
<li><p>Don’t use a function instance as your <code>initialValue</code>. Pass the function itself, not its output.</p>
</li>
<li><p>You can use the React ref Hook to manage your HTML DOM nodes.</p>
</li>
</ul>
<p>But what’s the difference between refs, states, and variables, I hear you ask? Let’s find out below.</p>
<h2 id="heading-variables-vs-refs-vs-states-in-react">Variables vs Refs vs States in React</h2>
<p>In React, variables, refs, and states allow you to store and mutate data. But they work in different ways. Here are the main distinctions between them:</p>
<ol>
<li><p>Does its value persist during re-rendering?</p>
<ul>
<li><p>React Ref: Yes</p>
</li>
<li><p>React State: Yes</p>
</li>
<li><p>JavaScript Variable: No</p>
</li>
</ul>
</li>
<li><p>Would updating its value trigger a re-rendering of the component?</p>
<ul>
<li><p>React Ref: No</p>
</li>
<li><p>React State: Yes</p>
</li>
<li><p>JavaScript Variable: No</p>
</li>
</ul>
</li>
<li><p>Is it plain JavaScript?</p>
<ul>
<li><p>React Ref: Yes</p>
</li>
<li><p>React State: No</p>
</li>
<li><p>JavaScript Variable: Yes</p>
</li>
</ul>
</li>
<li><p>Can you declare it outside a component?</p>
<ul>
<li><p>React Ref: No</p>
</li>
<li><p>React State: No</p>
</li>
<li><p>JavaScript Variable: Yes</p>
</li>
</ul>
</li>
<li><p>Is it usable in conditional statements, loops, or nested functions?</p>
<ul>
<li><p>React Ref: No</p>
</li>
<li><p>React State: No</p>
</li>
<li><p>JavaScript Variable: Yes</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-how-do-variables-work-in-react">How do variables work in React?</h3>
<p>A <a target="_blank" href="https://codesweetly.com/javascript-variable/">variable</a>’s value does not persist during re-rendering. Its value resets at the beginning of a new rendering.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> myVar = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">const</span> [myState, setMyState] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateVar</span>(<span class="hljs-params"></span>) </span>{
    myVar = myVar + <span class="hljs-number">1</span>;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"myVar ="</span>, myVar);
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateState</span>(<span class="hljs-params"></span>) </span>{
    setMyState(myState + <span class="hljs-number">1</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">h2</span>&gt;</span>Variable: {myVar}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>State: {myState}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{updateVar}</span>&gt;</span>Update Variable<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{updateState}</span>&gt;</span>Update State<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><a target="_blank" href="https://codesweetly.com/variables-vs-refs-vs-states-in-react/try-it-sdk-vitejs-vite-u6yjihmv"><strong>Try Editing It</strong></a></p>
<p>The snippet above will:</p>
<ul>
<li><p>Increment the variable’s value when you click the “Update Variable” button. This modification doesn’t trigger a re-rendering of the component because React doesn’t track a variable’s changes.</p>
</li>
<li><p>Increment the state’s value when you click the “Update State” button. This modification triggers a re-rendering of the component because React requests a re-render whenever you modify the state.</p>
</li>
<li><p>Reset the variable’s value to zero (0) during each re-rendering of the App component. Therefore, the rendered variable’s value will always be zero (0).</p>
</li>
</ul>
<h3 id="heading-how-do-refs-work-in-react">How do refs work in React?</h3>
<p>A ref’s value persists during re-rendering, but modifying it doesn’t cause React to re-render the component. In other words, a ref is a plain <a target="_blank" href="https://codesweetly.com/javascript-properties-object/">JavaScript object</a> whose value React remembers while re-rendering your component. But React doesn’t track changes to the ref’s value. So, its modifications don’t trigger a new rendering.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState, useRef } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> myRef = useRef(<span class="hljs-number">0</span>);
  <span class="hljs-keyword">const</span> [myState, setMyState] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateRef</span>(<span class="hljs-params"></span>) </span>{
    myRef.current = myRef.current + <span class="hljs-number">1</span>;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"myRef ="</span>, myRef);
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateState</span>(<span class="hljs-params"></span>) </span>{
    setMyState(myState + <span class="hljs-number">1</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">h2</span>&gt;</span>Ref: {myRef.current}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>State: {myState}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{updateRef}</span>&gt;</span>Update Ref<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{updateState}</span>&gt;</span>Update State<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><a target="_blank" href="https://codesweetly.com/variables-vs-refs-vs-states-in-react/try-it-sdk-vitejs-vite-xyjh2fev"><strong>Try Editing It</strong></a></p>
<p>The snippet above will:</p>
<ul>
<li><p>Increment the ref’s value when you click the “Update Ref” button. This modification doesn’t trigger a re-rendering of the component because React doesn’t monitor the ref’s changes.</p>
</li>
<li><p>Increment the state’s value when you click the “Update State” button. This modification triggers a re-rendering of the component because React requests a re-render whenever you modify the state.</p>
</li>
<li><p>Retains the ref and state’s value during each re-rendering of the App component.</p>
</li>
</ul>
<h3 id="heading-how-do-states-work-in-react">How do states work in React?</h3>
<p>A state’s value persists during re-rendering. Modifying it also causes React to re-render the component.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState, useRef } <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">let</span> myVar = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">const</span> myRef = useRef(<span class="hljs-number">0</span>);
  <span class="hljs-keyword">const</span> [myState, setMyState] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateVarAndRef</span>(<span class="hljs-params"></span>) </span>{
    myVar = myVar + <span class="hljs-number">1</span>;
    myRef.current = myRef.current + <span class="hljs-number">1</span>;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"myVar ="</span>, myVar);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"myRef ="</span>, myRef);
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateState</span>(<span class="hljs-params"></span>) </span>{
    setMyState(myState + <span class="hljs-number">1</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">h2</span>&gt;</span>Variable: {myVar}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Ref: {myRef.current}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>State: {myState}<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{updateVarAndRef}</span>&gt;</span>Update Variable and Ref<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{updateState}</span>&gt;</span>Update State<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><a target="_blank" href="https://codesweetly.com/variables-vs-refs-vs-states-in-react/try-it-sdk-vitejs-vite-gklkzfps"><strong>Try Editing It</strong></a></p>
<p>The snippet above will:</p>
<ul>
<li><p>Increment the variable and ref’s value when you click the “Update Variable and Ref” button. This modification doesn’t trigger a re-rendering of the component because React doesn’t monitor changes to the variable or ref.</p>
</li>
<li><p>Increment the state’s value when you click the “Update State” button. This modification triggers a re-rendering of the component because React requests a re-render whenever you modify the state.</p>
</li>
<li><p>Resets the variable’s value during each re-rendering of the App component, while retaining the ref and state’s data.</p>
</li>
</ul>
<h3 id="heading-tips-on-using-variables-refs-and-states-in-react">Tips on using variables, refs, and states in React</h3>
<ul>
<li><p>Use variables for values that should reset on every rendering of the component.</p>
</li>
<li><p>Use the Ref Hook to store values that users do not need to see on screen, as changes to the ref will not trigger a re-rendering of the component.</p>
</li>
<li><p>React state is ideal for storing values that you want to display on the screen, as state changes trigger a re-rendering of the component.</p>
</li>
</ul>
<p>React components sometimes need to fetch data or change the DOM during different lifecycle phases: trigger, render, commit, and paint. The Effect Hook can help with these tasks.</p>
<h2 id="heading-what-is-the-useeffect-hook">What Is the useEffect Hook?</h2>
<p>The <code>useEffect</code> hook lets function components perform side effects outside React.</p>
<h3 id="heading-syntax-of-the-useeffect-hook">Syntax of the useEffect Hook</h3>
<p>The <code>useEffect</code> hook accepts two arguments. Here’s the syntax:</p>
<pre><code class="lang-javascript">useEffect(callback, array);
</code></pre>
<ul>
<li><p><code>callback</code>: The required setup function for the useEffect hook.</p>
</li>
<li><p><code>array</code>: (Optional) The reactive dependencies list that indicates when React runs the callback.</p>
</li>
</ul>
<p><strong>Tip:</strong> React runs the setup function after the component mounts or when dependencies change.</p>
<h3 id="heading-example-of-the-useeffect-hook">Example of the useEffect Hook:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useState, useEffect } <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">AboutCompany</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [age, setAge] = useState(<span class="hljs-number">5</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">document</span>.title = <span class="hljs-string">`🥳🎁🎉 It's CodeSweetly's birthday! 🎉🎁🥳`</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">h3</span>&gt;</span>CodeSweetly is {age} years old!<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setAge(age + 1)}&gt;
        Click to update age
      <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> AboutCompany;
</code></pre>
<p>The <code>useEffect</code> code updates the browser’s title after the UI finishes rendering.</p>
<h3 id="heading-useeffect-hooks-best-practices">useEffect Hook’s best practices</h3>
<p>As always, there are some best practices to use this hook most effectively:</p>
<ul>
<li><p>Use <code>useEffect</code> to connect with things outside your React app, such as APIs or timers. If your code has no side effects, you likely don’t need it.</p>
</li>
<li><p>Avoid adding values to the dependency array unless your effect uses them. Include only the state and props needed to prevent unnecessary re-runs.</p>
</li>
<li><p>Declare static objects and functions outside components. Place dynamic ones inside your Effect Hook.</p>
</li>
<li><p>When depending on object props, list each primitive value used in your effect instead of the entire object.</p>
</li>
<li><p>Use <code>StrictMode</code> to help catch common useEffect hook issues during development.</p>
</li>
</ul>
<p>With the basics of React covered, let’s discuss styling.</p>
<h2 id="heading-how-to-style-react-components">How to Style React Components</h2>
<p>The four primary ways to style React elements are:</p>
<ul>
<li><p>CSS style sheets</p>
</li>
<li><p>Inline style attributes</p>
</li>
<li><p>CSS Modules</p>
</li>
<li><p>CSS-in-JS Libraries</p>
</li>
</ul>
<p>Let’s discuss the four styling techniques.</p>
<h3 id="heading-how-to-use-css-style-sheets-to-style-react-elements">How to use CSS style sheets to style React elements</h3>
<p>Below are the steps to style JSX elements with regular CSS style sheets.</p>
<h4 id="heading-1-create-a-css-stylesheet">1. Create a CSS stylesheet</h4>
<p>First, create a CSS stylesheet in your React projects.</p>
<pre><code class="lang-console">touch styles.css
</code></pre>
<p><strong>Tip:</strong> You can create the stylesheet anywhere in your project directory.</p>
<h4 id="heading-2-define-your-ruleset">2. Define your ruleset</h4>
<p>Open the newly created CSS file and declare your styles.</p>
<p><strong>Example:</strong></p>
<p><code>styles.css</code></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.text</span> {
  <span class="hljs-attribute">color</span>: seagreen;
  <span class="hljs-attribute">font-weight</span>: bold;
}
</code></pre>
<p>The CSS snippet above instructs browsers to apply a <code>seagreen</code> color and <code>bold</code> font weight on elements with a <code>text</code> class name.</p>
<h4 id="heading-3-apply-the-stylesheets-ruleset-to-your-element">3. Apply the stylesheet’s ruleset to your element</h4>
<p>Import your stylesheet into the component file containing the element you wish to style. Then, apply the stylesheet’s ruleset to it.</p>
<p><strong>Example:</strong></p>
<p><code>App.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Import your stylesheet (the path to your stylesheet may be different).</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">"../styles.css"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text"</span>&gt;</span>Oluwatobi is my name.<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><a target="_blank" href="https://codesandbox.io/p/sandbox/mq5xzp?file=%2Fsrc%2FApp.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above instructs React to apply the <code>"text"</code> ruleset on the element with a <code>className="text"</code> attribute.</p>
<h3 id="heading-how-to-use-the-inline-style-attribute-to-style-react-elements">How to use the inline <code>style</code> attribute to style React elements</h3>
<p>React allows you to apply inline styles to JSX elements in the same way as inline CSS works in HTML. But there are some differences to keep in mind.</p>
<p>First, HTML applies inline styles as a string value:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"color:seagreen; font-weight:bold;"</span>&gt;</span>Oluwatobi is my name.<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>But in React, you must define inline styles as objects, not strings:</p>
<pre><code class="lang-javascript">&lt;div style={{ <span class="hljs-attr">color</span>: <span class="hljs-string">"seagreen"</span>, <span class="hljs-attr">fontWeight</span>: <span class="hljs-string">"bold"</span> }}&gt;
  Oluwatobi is my name.
&lt;/div&gt;
</code></pre>
<p>The snippet above uses two sets of curly braces because in JSX (as I mentioned above), you wrap <a target="_blank" href="https://codesweetly.com/javascript-statement/#what-is-a-javascript-expression-statement">JavaScript expressions</a> inside curly braces: for instance, <code>&lt;div&gt;{myNameVariable}&lt;/div&gt;</code>.</p>
<p>So, suppose the expression is a JavaScript object literal. In that case, you will need two sets of curly braces: for instance, <code>&lt;div&gt;{{ name: "Oluwatobi" }}&lt;/div&gt;</code>.</p>
<p>Therefore, in <code>style={{ color: seagreen, fontWeight: bold }}</code>, the first set of curly braces (<code>{...}</code>) tells React that you want to write a JavaScript expression. The second set of curly braces (<code>{ color: seagreen, fontWeight: bold }</code>) is the JavaScript expression (an object) you are assigning as the <code>style</code> attribute’s value.</p>
<p><strong>Example:</strong></p>
<p><code>App.js</code></p>
<pre><code class="lang-javascript"><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">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> "<span class="hljs-attr">seagreen</span>", <span class="hljs-attr">fontWeight:</span> "<span class="hljs-attr">bold</span>" }}&gt;</span>
      Oluwatobi is my name.
    <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><a target="_blank" href="https://codesandbox.io/p/sandbox/84cmjf?file=%2Fsrc%2FApp.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The React snippet above instructs the computer to apply an inline style to the <code>div</code> element.</p>
<p>You can see that we wrote <code>fontWeight</code> in <a target="_blank" href="https://codesweetly.com/naming-convention-explained/#what-is-camelcase">camelCase</a>. This is because, under the hood, JSX compiles into plain JavaScript. So it uses the JavaScript Web APIs attribute naming convention.</p>
<p>To make your code easier to read, consider storing your inline style object in a separate variable like so:</p>
<p><code>App.js</code></p>
<pre><code class="lang-javascript"><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">// Store your inline style object in a variable:</span>
  <span class="hljs-keyword">const</span> textStyles = { <span class="hljs-attr">color</span>: <span class="hljs-string">"seagreen"</span>, <span class="hljs-attr">fontWeight</span>: <span class="hljs-string">"bold"</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">style</span>=<span class="hljs-string">{textStyles}</span>&gt;</span>Oluwatobi is my name.<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><a target="_blank" href="https://codesandbox.io/p/sandbox/2llmwy?file=%2Fsrc%2FApp.js"><strong>Try it on CodeSandbox</strong></a></p>
<p><strong>Tip:</strong> The Tailwind CSS framework is an inline styling tool that provides utility classes you can apply directly to an element. It offers additional features that are often lacking in regular inline styling. For example, Tailwind allows you to configure media queries and event states (such as <code>hover</code>, <code>focus</code>, and <code>active</code>) in inline styles.</p>
<h3 id="heading-how-to-use-css-modules-to-style-react-elements">How to use CSS modules to style React elements</h3>
<p>As defined on the official <a target="_blank" href="https://github.com/css-modules/css-modules">documentation</a>, a CSS Module is a CSS file in which all class names and animation names are scoped locally by default.</p>
<p>CSS Modules share many similarities with a regular CSS style sheet. But there are some essential differences.</p>
<h4 id="heading-1-filename-convention">1. Filename convention</h4>
<p>The syntax for naming a regular CSS stylesheet is <code>[name].css</code>: for instance, <code>codesweetly-styles.css</code>.</p>
<p>But a CSS module’s file naming convention is <code>[name].module.css</code>: for instance, <code>codesweetly-styles.module.css</code>.</p>
<h4 id="heading-2-styles-scope">2. Styles scope</h4>
<p>Importing a CSS style sheet into your script file makes its rulesets available <em>globally</em> to all components (and child components) of that script.</p>
<p>But importing a CSS module into your script file only makes its rulesets available <em>locally</em> to the component that invokes the module’s rule. Also, that component must be in the script that imports the CSS module.</p>
<p><strong>Example:</strong></p>
<p>Create a regular CSS stylesheet in your React project and add some rules to it:</p>
<p><code>styles.css</code></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.imageInfo</span> {
  <span class="hljs-attribute">text-align</span>: center;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#442109</span>;
}
</code></pre>
<p>Also, create a CSS module in the same project and add some rules to it:</p>
<p><code>styles.module.css</code></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.imageInfo</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">8px</span> ridge <span class="hljs-number">#71380f</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#ffe5b4</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span> <span class="hljs-number">0</span> <span class="hljs-number">7px</span>;
}
</code></pre>
<p>Import both the CSS stylesheet and CSS module you’ve just created into your script file:</p>
<p><code>App.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">"../styles.css"</span>;
<span class="hljs-keyword">import</span> codesweetlyStyles <span class="hljs-keyword">from</span> <span class="hljs-string">"../styles.module.css"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"imageInfo"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Random Image<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://picsum.photos/400/400"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Random Image"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Get a new image each time you refresh your browser.<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><a target="_blank" href="https://codesandbox.io/p/sandbox/3t3nwt?file=%2Fsrc%2FApp.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>Go ahead and run your app and check its output in your browser.</p>
<p>After running your app, you will notice that React only applied the CSS stylesheet’s ruleset, not the CSS module’s own.</p>
<p>React did so because the stylesheet’s ruleset is globally available to all elements (and child components) of the page where you imported the sheet.</p>
<p>But the ruleset in the module is locally available only to the component that explicitly invokes the rule.</p>
<p>So, to use your CSS module’s style in your component, you must explicitly execute it like so:</p>
<p><code>App.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">"../styles.css"</span>;
<span class="hljs-keyword">import</span> codesweetlyStyles <span class="hljs-keyword">from</span> <span class="hljs-string">"../styles.module.css"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{</span>`<span class="hljs-attr">imageInfo</span> ${<span class="hljs-attr">codesweetlyStyles.imageInfo</span>}`}&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Random Image<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://picsum.photos/400/400"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Random Image"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Get a new image each time you refresh your browser.<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><a target="_blank" href="https://codesandbox.io/p/sandbox/45lkpf?file=%2Fsrc%2FApp.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above uses the <code>codesweetlyStyles.imageInfo</code> code to instruct React to apply the CSS module’s <code>imageInfo</code> ruleset to the <code>div</code> element.</p>
<h4 id="heading-3-composition">3. Composition</h4>
<p>To compose styles together while using a regular CSS style sheet, you must apply multiple classes to your element.</p>
<p><strong>Example: Compose rulesets with regular CSS style sheets</strong></p>
<p><code>styles.css</code></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">4px</span> solid blueviolet;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">30px</span> <span class="hljs-number">15px</span>;
}

<span class="hljs-selector-class">.text</span> {
  <span class="hljs-attribute">color</span>: seagreen;
  <span class="hljs-attribute">font-weight</span>: bold;
}
</code></pre>
<p><code>App.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> <span class="hljs-string">"../styles.css"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"container text"</span>&gt;</span>Oluwatobi is my name.<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><a target="_blank" href="https://codesandbox.io/p/sandbox/w6h74d?file=%2Fsrc%2FApp.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>Using multiple classes on an element to implement style composition is not the best practice because CSS will use the order of style definitions in the stylesheet to determine the order of precedence based on the CSS cascading rules.</p>
<p>But CSS modules provide a <code>composes</code> declaration that offers greater flexibility in composing your styles to suit your project’s needs.</p>
<p><strong>Example: Compose rulesets with CSS modules</strong></p>
<p><code>styles.module.css</code></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">4px</span> solid blueviolet;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">30px</span> <span class="hljs-number">15px</span>;
}

<span class="hljs-selector-class">.text</span> {
  <span class="hljs-attribute">composes</span>: container;
  <span class="hljs-attribute">color</span>: seagreen;
  <span class="hljs-attribute">font-weight</span>: bold;
}
</code></pre>
<p><code>App.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> styles <span class="hljs-keyword">from</span> <span class="hljs-string">"../styles.module.css"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{styles.text}</span>&gt;</span>Oluwatobi is my name.<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><a target="_blank" href="https://codesandbox.io/p/sandbox/j6yl9z?file=%2Fsrc%2FApp.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>Although you can define multiple <code>composes</code> declarations in a ruleset, they must precede other rules.</p>
<p><strong>Example: All</strong> <code>composes</code> <strong>declarations must come before other rules</strong></p>
<p><code>styles.module.css</code></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">4px</span> solid blueviolet;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">30px</span> <span class="hljs-number">15px</span>;
}

<span class="hljs-selector-class">.curved</span> {
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.text</span> {
  <span class="hljs-attribute">composes</span>: container;
  <span class="hljs-attribute">composes</span>: curved;
  <span class="hljs-attribute">color</span>: seagreen;
  <span class="hljs-attribute">font-weight</span>: bold;
}
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/3lqshk?file=%2Fsrc%2Fstyles.module.css"><strong>Try it on CodeSandbox</strong></a></p>
<p>You can simplify the <code>.text</code> ruleset by using a single <code>composes</code> declaration for multiple classes.</p>
<p><strong>Example: Compose classes with a single</strong> <code>composes</code> <strong>declaration</strong></p>
<p><code>styles.module.css</code></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">4px</span> solid blueviolet;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">30px</span> <span class="hljs-number">15px</span>;
}

<span class="hljs-selector-class">.curved</span> {
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.text</span> {
  <span class="hljs-attribute">composes</span>: container curved;
  <span class="hljs-attribute">color</span>: seagreen;
  <span class="hljs-attribute">font-weight</span>: bold;
}
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/p/sandbox/x4zfyn?file=%2Fsrc%2Fstyles.module.css"><strong>Try it on CodeSandbox</strong></a></p>
<h3 id="heading-how-to-use-a-css-in-js-library-to-style-react-elements">How to use a CSS-in-JS library to style React elements</h3>
<p>A CSS-in-JS library allows you to use the complete features of CSS directly within your JavaScript file.</p>
<p>Some of the popular CSS-in-JS libraries are Linaria, Emotion, Pigment CSS, and Panda CSS.</p>
<p>Feel free to try any CSS-in-JS library you prefer. Here, we’ll use Emotion to illustrate how such a styling technique works in a React application.</p>
<p>So, go ahead and install the library into any of your React projects by running:</p>
<pre><code class="lang-console">npm i @emotion/react@11.14.0
</code></pre>
<p>After you’ve installed Emotion, import it and use it in your component file like so:</p>
<p><code>App.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// The comment below is essential. Emotion will not work without it.</span>
<span class="hljs-comment">/** <span class="hljs-doctag">@jsxImportSource </span><span class="hljs-doctag">@emotion</span>/react */</span>

<span class="hljs-comment">// Define your styles using the JavaScript object syntax.</span>
<span class="hljs-keyword">const</span> codesweetlyStyles = {
  <span class="hljs-attr">border</span>: <span class="hljs-string">"8px ridge #71380f"</span>,
  <span class="hljs-attr">backgroundColor</span>: <span class="hljs-string">"#ffe5b4"</span>,
  <span class="hljs-attr">padding</span>: <span class="hljs-string">"20px 0 7px"</span>,
  <span class="hljs-attr">textAlign</span>: <span class="hljs-string">"center"</span>,
  <span class="hljs-attr">color</span>: <span class="hljs-string">"maroon"</span>,
  <span class="hljs-string">"@media(min-width: 768px)"</span>: {
    <span class="hljs-attr">color</span>: <span class="hljs-string">"darkslategray"</span>,
  },
};

<span class="hljs-comment">// Apply the styles to your element.</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">css</span>=<span class="hljs-string">{codesweetlyStyles}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Random Image<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://picsum.photos/400/400"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Random Image"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Get a new image each time you refresh your browser.<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><a target="_blank" href="https://codesandbox.io/p/sandbox/t4ttkx?file=%2Fsrc%2FApp.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above does the following:</p>
<ol>
<li><p>Uses the <code>/** @jsxImportSource @emotion/react */</code> comment (JSX Pragma) to tell the Babel JSX plugin to convert the script’s JSX calls to an Emotion function called <code>jsx</code> instead of <code>React.createElement</code>. Make sure you place the pragma directive above your import statements. Otherwise, the Emotion library will not work.</p>
</li>
<li><p>Defines styles in a JavaScript object.</p>
</li>
<li><p>Uses Emotion’s <code>css</code> prop feature to apply the styles to the JSX element.</p>
</li>
</ol>
<p>Notice that the <code>css</code> prop is like the inline <code>style</code> attribute. The main difference is that the <code>css</code> props support more CSS features like nested selectors, auto vendor-prefixing, media queries, and event states (such as <code>hover</code>, <code>focus</code>, and <code>active</code>). So, using CSS-in-JS libraries like Emotion lets you write highly flexible and responsive styles directly in your JavaScript files.</p>
<p><strong>Tip:</strong> The <code>css</code> prop works on any element that supports the <code>className</code> attribute.</p>
<p>Now, go ahead and run your app and check its output in your browser.</p>
<p>And that’s it! You now know how to use the CSS-in-JS library to style your React elements.</p>
<p>I used Emotion in this article because I like how clean its syntax looks. Feel free to test other CSS-in-JS libraries, such as Pigment CSS. You may find one that suits you better.</p>
<h2 id="heading-overview">Overview</h2>
<p>In this handbook, we discussed the core concepts you need to know to start building applications with React. We also used examples to practice creating and styling components.</p>
<p>Whether you’re considering a small personal project or a full-stack app for a larger user base, you now have the foundation to build these projects using React.</p>
<p>Thanks for reading!</p>
<h3 id="heading-dive-deeper-into-react">Dive deeper into React</h3>
<p>This handbook has given you a peek inside my <a target="_blank" href="https://www.amazon.com/dp/B0FRC4R8T3?tag=codesweetly00-20">Code React Sweetly book</a>. Whether you’re just starting or want to sharpen your fundamentals, the book walks you through everything from essential concepts to deploying real apps using JavaScript and TypeScript. It is practical, beginner-friendly, and designed to help you code React sweetly!</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B0FRC4R8T3?tag=codesweetly00-20"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760698961658/f3f297da-1cd2-4777-b440-19b94daaa26f.jpeg" alt="A Beginner’s Guide to React: Learn JSX, Hooks, and Real-World App Development" class="image--center mx-auto" width="970" height="250" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The JavaScript Class Handbook – Complete Guide to Class Fields and the Super Keyword ]]>
                </title>
                <description>
                    <![CDATA[ Classes let you privatize your data while providing users indirect access to it. It is an excellent way to prevent direct access to your constructor’s data. This handbook aims to show you exactly how classes work in JavaScript. We will also discuss c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-class-handbook/</link>
                <guid isPermaLink="false">66ba0df1052fa53219e0a363</guid>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Mon, 20 May 2024 20:05:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/JavaScript-Class-Handbook-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Classes let you privatize your data while providing users indirect access to it. It is an excellent way to prevent direct access to your constructor’s data.</p>
<p>This handbook aims to show you exactly how classes work in JavaScript. We will also discuss class fields and the <code>super</code> keyword.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-a-javascript-class">What is a JavaScript Class?</a></li>
<li><a class="post-section-overview" href="#heading-why-classes-in-javascript">Why Classes in JavaScript?</a></li>
<li><a class="post-section-overview" href="#heading-syntax-of-a-javascript-class">Syntax of a JavaScript Class</a><ul>
<li><a class="post-section-overview" href="#heading-what-is-a-class-keyword">What is a <code>class</code> Keyword?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-class-name">What is a Class Name?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-code-block">What is a Code Block?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-class-body">What is a Class Body?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-is-a-javascript-class-field">What is a JavaScript Class Field?</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-create-class-fields-in-javascript">How to Create Class Fields in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-class-fields-with-computed-names">How to Create Class Fields with Computed Names</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-regular-class-field-methods">How to Create Regular Class Field Methods</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-shorthand-class-field-methods">How to Create Shorthand Class Field Methods</a></li>
<li><a class="post-section-overview" href="#heading-regular-vs-shorthand-class-field-methods-whats-the-difference">Regular vs. Shorthand Class Field Methods: What’s the Difference?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-user-defined-prototypal-method-in-javascript-classes">What is a User-defined Prototypal Method in JavaScript Classes?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-constructor-method-in-javascript-classes">What is a <code>constructor</code> Method in JavaScript Classes?</a></li>
<li><a class="post-section-overview" href="#heading-types-of-class-fields">Types of Class Fields</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-public-class-field-in-javascript-classes-1">What is a Public Class Field in JavaScript Classes?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-private-class-field-in-javascript-classes-1">What is a Private Class Field in JavaScript Classes?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-static-class-field-in-javascript-classes-1">What is a Static Class Field in JavaScript Classes?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-types-of-javascript-classes">Types of JavaScript Classes</a><ul>
<li><a class="post-section-overview" href="#heading-what-is-a-javascript-class-declaration">What is a JavaScript Class Declaration?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-javascript-class-expression">What is a JavaScript Class Expression?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-derived-class-in-javascript">What is a Derived Class in JavaScript?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-is-the-super-keyword-in-javascript">What is the <code>super</code> Keyword in JavaScript?</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-use-the-super-keyword-as-a-function-caller">How to Use the <code>super</code> Keyword as a Function Caller</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-super-keyword-as-a-property-accessor">How to Use the <code>super</code> Keyword as a Property Accessor</a></li>
<li><a class="post-section-overview" href="#heading-super-vs-this-keyword-whats-the-difference"><code>super</code> vs. <code>this</code> Keyword: What’s the Difference?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-components-of-a-javascript-class">Components of a JavaScript Class</a></li>
<li><a class="post-section-overview" href="#heading-how-does-a-javascript-class-help-with-encapsulation">How Does a JavaScript Class Help with Encapsulation?</a></li>
<li><a class="post-section-overview" href="#heading-important-things-to-know-about-javascript-classes">Important Things to Know about JavaScript Classes</a><ul>
<li><a class="post-section-overview" href="#heading-1-declare-your-class-before-you-access-it">1. Declare Your Class Before You Access It</a></li>
<li><a class="post-section-overview" href="#heading-2-classes-are-functions">2. Classes are Functions</a></li>
<li><a class="post-section-overview" href="#heading-3-classes-are-strict">3. Classes are Strict</a></li>
<li><a class="post-section-overview" href="#heading-4-avoid-the-return-keyword-in-your-classs-constructor-method">4. Avoid the <code>return</code> Keyword in Your Class’s <code>constructor</code> Method</a></li>
<li><a class="post-section-overview" href="#heading-5-a-classs-evaluation-starts-from-the-extends-clause-to-its-values">5. A Class’s Evaluation starts from the <code>extends</code> clause to its values</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-overview">Overview</a></li>
</ol>
<p>So, let’s get started from the basics.</p>
<h2 id="heading-what-is-a-javascript-class">What is a JavaScript Class?</h2>
<p>A JavaScript class is an <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/Object">object constructor</a> that the <a target="_blank" href="https://codesweetly.com/javascript-new-keyword"><code>new</code> keyword</a> uses to create a new object instance.</p>
<p>Here’s an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{}

<span class="hljs-comment">// Create an object instance from the Name class:</span>
<span class="hljs-keyword">const</span> yourName = <span class="hljs-keyword">new</span> Name();

<span class="hljs-comment">// Check yourName's content:</span>
yourName;

<span class="hljs-comment">// The invocation above will return an empty object:</span>
{ }
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-explained/js-gtfmeb"><strong>Try Editing It</strong></a></p>
<p>The snippet above used the <code>new</code> keyword to create a new object instance from the <code>class</code> constructor.</p>
<p><strong>Note:</strong> Calling a JavaScript class requires the <code>new</code> keyword. Otherwise, browsers will throw a <code>TypeError</code>.</p>
<h2 id="heading-why-classes-in-javascript">Why Classes in JavaScript?</h2>
<p>Classes provide a way to create a template for creating objects that have access to private data through public methods.</p>
<p>In other words, classes help you <a target="_blank" href="https://codesweetly.com/encapsulation-in-javascript">encapsulate</a> your data while providing users indirect access to an instance’s internal workings. This lets you provide users with a clean and friendly interface that is independent of an object’s internal implementations.</p>
<p>For instance, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date"><code>Date</code></a> is a JavaScript class that allows you to access its date data through its public methods, such as <code>getDate()</code>, <code>setDate()</code>, and <code>getFullYear()</code>.</p>
<h2 id="heading-syntax-of-a-javascript-class">Syntax of a JavaScript Class</h2>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NameOfClass</span> </span>{
  <span class="hljs-comment">// class's body</span>
}
</code></pre>
<p>A class is composed of four components:</p>
<ol>
<li>A <code>class</code> keyword</li>
<li>The name of the class</li>
<li>A code block (<code>{...}</code>)</li>
<li>The body of the class</li>
</ol>
<p>Let’s discuss each component.</p>
<h3 id="heading-what-is-a-class-keyword">What is a <code>class</code> Keyword?</h3>
<p>We use the <code>class</code> keyword to declare to browsers that a specific piece of code is a JavaScript class—not a mathematical or other generic class.</p>
<h3 id="heading-what-is-a-class-name">What is a Class Name?</h3>
<p>A class name allows you to create an identifier for your class, which you can use to reference it.</p>
<p><strong>Note:</strong> Developers typically use uppercase to begin a class's name. This convention helps to differentiate a constructor from other functions.</p>
<h3 id="heading-what-is-a-code-block">What is a Code Block?</h3>
<p>A block is a pair of braces (<code>{...}</code>) used to group multiple statements together.</p>
<p>Here’s an example:</p>
<pre><code class="lang-js">{
  <span class="hljs-keyword">var</span> bestColor = <span class="hljs-string">"White"</span>;
}
</code></pre>
<p>The block in the snippet above encased one <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements">JavaScript statement</a>.</p>
<p>Here’s another example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours() &lt; <span class="hljs-number">18</span>) {
  <span class="hljs-keyword">const</span> hourNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours();
  <span class="hljs-keyword">const</span> minutesNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getMinutes();
  <span class="hljs-keyword">const</span> secondsNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getSeconds();
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Check your plans now. The time is <span class="hljs-subst">${hourNow}</span>:<span class="hljs-subst">${minutesNow}</span>:<span class="hljs-subst">${secondsNow}</span>.`</span>);
}
</code></pre>
<p>The <code>if</code> condition’s code block grouped four JavaScript statements together.</p>
<p>Now, consider this snippet:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Time</span> </span>{
  hourNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours();
  minutesNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getMinutes();
  secondsNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getSeconds();
}

<span class="hljs-keyword">if</span> (<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours() &lt; <span class="hljs-number">18</span>) {
   <span class="hljs-keyword">const</span> currentTime = <span class="hljs-keyword">new</span> Time();
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Check your plans now. The time is <span class="hljs-subst">${currentTime.hourNow}</span>:<span class="hljs-subst">${currentTime.minutesNow}</span>:<span class="hljs-subst">${currentTime.secondsNow}</span>.`</span>);
}
</code></pre>
<p>The <code>Time</code> class’s code block grouped three JavaScript statements, while the <code>if</code> condition’s code block grouped two.</p>
<p>Note the following:</p>
<ul>
<li><code>hourNow</code>, <code>minutesNow</code>, and <code>secondsNow</code> are the class fields (properties).</li>
<li>The snippet above used the <code>new</code> keyword to construct a new object from the <code>Time</code> class. Therefore, the <code>currentTime</code> object is an instance of the <code>Time</code> constructor class.</li>
</ul>
<h3 id="heading-what-is-a-class-body">What is a Class Body?</h3>
<p>A class body is where you place a sequence of statements.</p>
<p>Here’s the syntax:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NameOfClass</span> </span>{
  <span class="hljs-comment">// class' body</span>
}
</code></pre>
<p><strong>Note:</strong> A class’s body houses only class fields. But what exactly is a class field? Let’s find out.</p>
<h2 id="heading-what-is-a-javascript-class-field">What is a JavaScript Class Field?</h2>
<p>A class field is a property defined directly in a class’s body—not inside any of the class’s <a target="_blank" href="https://codesweetly.com/method-in-javascript">methods</a>.</p>
<h3 id="heading-how-to-create-class-fields-in-javascript">How to Create Class Fields in JavaScript</h3>
<p>You can create a class field by using an equal sign (<code>=</code>)—not a colon (<code>:</code>)—to assign a value to a property.</p>
<p>Here’s an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create two class fields:</span>
  firstName = <span class="hljs-string">"Oluwatobi"</span>;
  lastName = <span class="hljs-string">"Sofela"</span>;
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> fullName = <span class="hljs-keyword">new</span> Name();

<span class="hljs-built_in">console</span>.log(fullName.firstName + <span class="hljs-string">" "</span> + fullName.lastName);
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-bxe9or"><strong>Try Editing It</strong></a></p>
<p>The <code>Name</code> class in the snippet above has two class fields (<code>firstName</code> and <code>lastName</code>).</p>
<p>Note the following:</p>
<ul>
<li>JavaScript class fields default to <code>undefined</code> if you do not provide any value.</li>
<li>Class fields are like the regular object <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Property/JavaScript">properties</a> whose names you can <a target="_blank" href="https://codesweetly.com/javascript-properties-object#computed-property-names-in-javascript">compute</a>. Let’s discuss how.</li>
</ul>
<h3 id="heading-how-to-create-class-fields-with-computed-names">How to Create Class Fields with Computed Names</h3>
<p>You can compute (evaluate) a class field’s name by putting an expression in a square bracket like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Initialize a num variable with a number:</span>
<span class="hljs-keyword">let</span> num = <span class="hljs-number">0</span>;

<span class="hljs-comment">// Assign a string value to an enSuites variable:</span>
<span class="hljs-keyword">const</span> enSuites = <span class="hljs-string">"East"</span>;

<span class="hljs-comment">// Define a Room class and compute each of its class fields' names:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Room</span> </span>{
  [enSuites + ++num] = num;
  [enSuites + ++num] = num;
  [enSuites + ++num] = num;
}

<span class="hljs-comment">// Create an ensuiteRooms object instance:</span>
<span class="hljs-keyword">const</span> ensuiteRooms = <span class="hljs-keyword">new</span> Room();

<span class="hljs-comment">// Check the ensuiteRooms's content:</span>
<span class="hljs-built_in">console</span>.log(ensuiteRooms);

<span class="hljs-comment">// The invocation above will return:</span>
{<span class="hljs-attr">East1</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">East2</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">East3</span>: <span class="hljs-number">3</span>}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-b9jwfx"><strong>Try Editing It</strong></a></p>
<p>We used the <code>[enSuites + ++num]</code> syntax in the snippet above to compute the class fields’ names.</p>
<p>In other words, JavaScript evaluated the <code>enSuites + ++num</code> expression and used the result as each class field’s name.</p>
<p><strong>Note:</strong> You can also define class fields as regular JavaScript methods. Let’s talk more about this now.</p>
<h3 id="heading-how-to-create-regular-class-field-methods">How to Create Regular Class Field Methods</h3>
<p>You can create a regular class field method by using an equal sign (<code>=</code>) to assign a function to a property.</p>
<p>Here’s an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Time</span> </span>{
  <span class="hljs-comment">// Create two regular class field methods:</span>
  hourNow = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours();
  }
  minutesNow = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getMinutes();
  }
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> currentTime = <span class="hljs-keyword">new</span> Time();

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The time is <span class="hljs-subst">${currentTime.hourNow()}</span>:<span class="hljs-subst">${currentTime.minutesNow()}</span>.`</span>);
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-fro6pz"><strong>Try Editing It</strong></a></p>
<p>The <code>hourNow</code> and <code>minutesNow</code> methods in the snippet above are class field methods because they are properties containing regular JavaScript functions.</p>
<p>JavaScript allows you to use shorthand syntax to shorten your class’s methods. Let’s see how.</p>
<h3 id="heading-how-to-create-shorthand-class-field-methods">How to Create Shorthand Class Field Methods</h3>
<p>The shorthand class field method is a concise way of defining JavaScript methods in the body of your classes.</p>
<p>Here’s an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Time</span> </span>{
  <span class="hljs-comment">// Create two shorthand class field methods: </span>
  hourNow() {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours();
  }
  minutesNow() {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getMinutes();
  }
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> currentTime = <span class="hljs-keyword">new</span> Time();

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The time is <span class="hljs-subst">${currentTime.hourNow()}</span>:<span class="hljs-subst">${currentTime.minutesNow()}</span>.`</span>);
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-j6kpwy"><strong>Try Editing It</strong></a></p>
<p>Although you can use the regular and shorthand methods interchangeably in your class’s body, you should know a significant difference between the two syntaxes. Let’s discuss it now.</p>
<h3 id="heading-regular-vs-shorthand-class-field-methods-whats-the-difference">Regular vs. Shorthand Class Field Methods: What’s the Difference?</h3>
<p>The main difference between regular and shorthand class field methods is this:</p>
<ul>
<li>Regular methods are <a target="_blank" href="https://codesweetly.com/web-tech-terms-i#instance-property-in-javascript">instance properties</a>, while shorthand methods are <a target="_blank" href="https://codesweetly.com/web-tech-terms-p#prototypal-property-in-javascript">prototypal properties</a>.</li>
</ul>
<p>In other words, JavaScript treats regular and shorthand methods differently as follows:</p>
<ul>
<li><strong>Regular method:</strong> JavaScript adds the method to the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">object instance</a> you construct with the <code>new</code> keyword. Therefore, regular methods are properties of the object instance.</li>
<li><strong>Shorthand method:</strong> JavaScript adds the method to the class’s <a target="_blank" href="https://codesweetly.com/default-function-properties-in-javascript#what-is-the-default-prototype-property-in-javascript-functions"><code>prototype</code> property</a>. Therefore, shorthand methods are prototypal properties of an object instance.</li>
</ul>
<p>Here’s an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Time</span> </span>{
  <span class="hljs-comment">// Create a regular method:</span>
  hourNow = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours();
  }
  <span class="hljs-comment">// Create a shorthand method:</span>
  minutesNow() {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getMinutes();
  }
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> currentTime = <span class="hljs-keyword">new</span> Time();

<span class="hljs-comment">// Check currentTime's content:</span>
<span class="hljs-built_in">console</span>.log(currentTime);

<span class="hljs-comment">// The invocation above will return:</span>
{ <span class="hljs-attr">hourNow</span>: hourNow() }
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-xgekwn"><strong>Try Editing It</strong></a></p>
<p>The <code>currentTime</code> object instance contains only the <code>hourNow</code> property because regular methods are instance properties the <code>new</code> keyword assigned to the object it constructs from its constructor class.</p>
<p>On the other hand, shorthand methods are prototypal methods that JavaScript adds to the <code>prototype</code> property of the class you’ve defined.</p>
<p>Therefore, you can access the <code>minuteNow</code> method through its class’s <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">prototypal inheritance</a> like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Time</span> </span>{
  <span class="hljs-comment">// Create a regular method:</span>
  hourNow = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours();
  }
  <span class="hljs-comment">// Create a shorthand method:</span>
  minutesNow() {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getMinutes();
  }
}

<span class="hljs-comment">// Check Time's prototype content:</span>
<span class="hljs-built_in">console</span>.log(Time.prototype);

<span class="hljs-comment">// The invocation above will return:</span>
{...}:
  <span class="hljs-keyword">constructor</span>: class Time {}
  <span class="hljs-attr">minutesNow</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">minutesNow</span>(<span class="hljs-params"></span>)
  [[<span class="hljs-title">Prototype</span>]]: <span class="hljs-title">Object</span> </span>{...}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-tfz2hb"><strong>Try Editing It</strong></a></p>
<p>You can see that <code>Time</code>’s <code>prototype</code> property contains the <code>minutesNow</code> method, which all object instances will inherit automatically.</p>
<p>Here’s an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Time</span> </span>{
  <span class="hljs-comment">// Create a shorthand method:</span>
  minutesNow() {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getMinutes();
  }
}

<span class="hljs-comment">// Create an object instance from the Time class:</span>
<span class="hljs-keyword">const</span> currentTime = <span class="hljs-keyword">new</span> Time();

<span class="hljs-comment">// Check currentTime's content:</span>
<span class="hljs-built_in">console</span>.log(currentTime);

<span class="hljs-comment">// The invocation above will return an empty object:</span>
{ }

<span class="hljs-comment">// Invoke currentTime's minutesNow method:</span>
<span class="hljs-built_in">console</span>.log(currentTime.minutesNow());
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-gzhxdi"><strong>Try Editing It</strong></a></p>
<p>The <code>currentTime.minutesNow()</code> code returned a valid value because <code>currentTime</code> inherited the <code>minuteNow()</code> method from its constructor’s <code>prototype</code> property.</p>
<p><strong>Note:</strong> A JavaScript class has two types of prototypal methods:</p>
<ul>
<li>User-defined methods</li>
<li>Constructor methods</li>
</ul>
<p>Let’s discuss the two types now.</p>
<h3 id="heading-what-is-a-user-defined-prototypal-method-in-javascript-classes">What is a User-defined Prototypal Method in JavaScript Classes?</h3>
<p>A user-defined prototypal method is the shorthand method you create yourself in the body of your JavaScript class.</p>
<p>Here’s an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create a shorthand method:</span>
  firstName(name) {
    <span class="hljs-keyword">return</span> name;
  }
}

<span class="hljs-comment">// Create an object instance from the Name class:</span>
<span class="hljs-keyword">const</span> myName = <span class="hljs-keyword">new</span> Name().firstName(<span class="hljs-string">"Oluwatobi"</span>);

<span class="hljs-comment">// Log myName's content to the console:</span>
<span class="hljs-built_in">console</span>.log(myName);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Oluwatobi"</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-pqgqew"><strong>Try Editing It</strong></a></p>
<p>The <code>firstName()</code> method is a user-defined method because we created it ourselves in the body of the <code>Name</code> class.</p>
<h2 id="heading-what-is-a-constructor-method-in-javascript-classes">What is a Constructor Method in JavaScript Classes?</h2>
<p>A <code>constructor()</code> is the default prototypal method that comes built-in with every JavaScript class.</p>
<p>Creating a <code>constructor</code> method is optional. However, if you do not create one, JavaScript will automatically add an empty one.</p>
<p>The <code>constructor</code> method automatically receives the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments">arguments</a> you pass to the class. Therefore, it is the ideal place to define the class fields that depend on the <a target="_blank" href="https://codesweetly.com/declaration-initialization-invocation-in-programming#what-does-invocation-mean">class invocator</a>’s arguments.</p>
<p>Here’s an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Use the built-in constructor method:</span>
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }
}

<span class="hljs-comment">// Create an object instance from the Name class:</span>
<span class="hljs-keyword">const</span> myName = <span class="hljs-keyword">new</span> Name(<span class="hljs-string">"Oluwatobi"</span>);

<span class="hljs-comment">// Log myName's content to the console:</span>
<span class="hljs-built_in">console</span>.log(myName);

<span class="hljs-comment">// The invocation above will return:</span>
{ <span class="hljs-attr">name</span>: <span class="hljs-string">"Oluwatobi"</span> }
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-stxiye"><strong>Try Editing It</strong></a></p>
<p>The <code>Name</code> class above has a <code>constructor</code> method with one <a target="_blank" href="https://codesweetly.com/web-tech-terms-i#instance-property-in-javascript">instance property</a> in its code block.</p>
<p><strong>Tip:</strong> A <code>constructor()</code> method’s <code>this</code> keyword refers to the class’s object instance.</p>
<p>JavaScript executes the <code>constructor</code> method before any other user-defined methods. Therefore, it is the best place to define any code you want to run before other methods in the class’s body. For instance, consider the code below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CarColor</span> </span>{
  <span class="hljs-comment">// Use the built-in constructor method:</span>
  <span class="hljs-keyword">constructor</span>(color) {
    <span class="hljs-built_in">this</span>.carColor = <span class="hljs-string">`<span class="hljs-subst">${color}</span> car`</span>;
  }
  <span class="hljs-comment">// Create a shorthand method:</span>
  revealColor() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I have a <span class="hljs-subst">${<span class="hljs-built_in">this</span>.carColor}</span>`</span>);
  }
}

<span class="hljs-comment">// Create an object instance from the CarColor class:</span>
<span class="hljs-keyword">const</span> myCarColor = <span class="hljs-keyword">new</span> CarColor(<span class="hljs-string">"white"</span>);

<span class="hljs-comment">// Invoke myCarColor's revealColor prototypal method:</span>
myCarColor.revealColor();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"I have a white car"</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-vkvnuv"><strong>Try Editing It</strong></a></p>
<p>The snippet above automatically invoked the <code>constructor</code> method while creating <code>myCarColor</code>’s object instance.</p>
<p>Therefore, the computer processed the <code>constructor</code>’s statements before executing the <code>myCarColor.revealColor()</code> code.</p>
<p>Note the following:</p>
<ul>
<li>You can only use the <a target="_blank" href="https://codesweetly.com/method-in-javascript#shorthand-for-javascript-methods">JavaScript method shorthand</a> technique to define a <code>constructor</code>. Otherwise, browsers will throw an <code>Uncaught SyntaxError</code>.</li>
<li>A class can have only one <code>constructor</code> method. Otherwise, browsers will throw an <code>Uncaught SyntaxError</code>.</li>
</ul>
<p>Now that we know how to create class fields, we can discuss the available types.</p>
<h2 id="heading-types-of-class-fields">Types of Class Fields</h2>
<p>The three types of class fields are:</p>
<ul>
<li>Public class fields</li>
<li>Private class fields</li>
<li>Static class fields</li>
</ul>
<p>Let’s discuss each type.</p>
<h3 id="heading-what-is-a-public-class-field-in-javascript-classes">What is a Public Class Field in JavaScript Classes?</h3>
<p>A public class field is a property an object instance has access to.</p>
<p><strong>Tip:</strong> Although you can define multiple public class fields with the same name, the last field will overwrite the previous ones.</p>
<h4 id="heading-example-how-to-create-public-class-fields">Example: How to create public class fields</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create two public class fields:</span>
  myName = <span class="hljs-string">"Oluwatobi"</span>;
  updateMyName(name) {
    <span class="hljs-built_in">this</span>.myName = name;
  }
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> author = <span class="hljs-keyword">new</span> Name();

<span class="hljs-comment">// Check myName's current value:</span>
author.myName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Oluwatobi"</span>

<span class="hljs-comment">// Use the author variable's property to modify myName's value:</span>
author.myName = <span class="hljs-string">"Sofela"</span>;

<span class="hljs-comment">// Check myName's current value:</span>
author.myName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Sofela"</span>

<span class="hljs-comment">// Use the author variable's method to update myName's value:</span>
author.updateMyName(<span class="hljs-string">"CodeSweetly"</span>);

<span class="hljs-comment">// Check myName's current value:</span>
author.myName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"CodeSweetly"</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-88zwpt"><strong>Try Editing It</strong></a></p>
<p>The <code>Name</code> class in the snippet above contains public class fields because you can use the class’s object instances to access and modify the two properties.</p>
<p>Suppose you define multiple public class fields with the same name. In that case, the last property will overwrite the previous ones.</p>
<h4 id="heading-example-the-last-public-class-field-overwrites-the-previous-ones-with-the-same-name">Example: The last public class field overwrites the previous ones with the same name</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create three public class fields:</span>
  myName = <span class="hljs-string">"Oluwatobi"</span>;
  myName = <span class="hljs-string">"Sofela"</span>;
  myName = <span class="hljs-string">"CodeSweetly"</span>;
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> author = <span class="hljs-keyword">new</span> Name();

<span class="hljs-comment">// Check myName's current value:</span>
author.myName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"CodeSweetly"</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-4gefar"><strong>Try Editing It</strong></a></p>
<p>The snippet above returned <code>"CodeSweetly"</code> because the last <code>myName</code> public class field overwrites the previously declared ones.</p>
<h3 id="heading-what-is-a-private-class-field-in-javascript-classes">What is a Private Class Field in JavaScript Classes?</h3>
<p>A private class field is a property you can only access and modify within the class’s body.</p>
<p>You can prefix a class field with the hash (<code>#</code>) symbol to make it a private property.</p>
<p><strong>Tip:</strong> Private class field names must be unique. You cannot redeclare a private field in the same class. Otherwise, the browser will throw an <code>Uncaught SyntaxError</code>.</p>
<h4 id="heading-example-how-to-create-private-class-fields">Example: How to create private class fields</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create a private class field:</span>
  #myName = <span class="hljs-string">"Oluwatobi"</span>;
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> author = <span class="hljs-keyword">new</span> Name();

<span class="hljs-comment">// Check myName's current value:</span>
author.myName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-literal">undefined</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-mkabvf"><strong>Try Editing It</strong></a></p>
<p>The snippet above returned <code>undefined</code> because <code>myName</code> is a private class field that can only be read and modified from within the class’s body.</p>
<p>Therefore, you need to use an internal code to access <code>myName</code>.</p>
<h4 id="heading-example-how-to-access-private-class-fields">Example: How to access private class fields</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create a private class field:</span>
  #myName = <span class="hljs-string">"Oluwatobi"</span>;

  <span class="hljs-comment">// Create a public class field:</span>
  fullName = <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.#myName}</span> Sofela`</span>;

  <span class="hljs-comment">// Create another public class field:</span>
  showMyName() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.#myName;
  }
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> author = <span class="hljs-keyword">new</span> Name();

<span class="hljs-comment">// Check fullName's current value:</span>
author.fullName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Oluwatobi Sofela"</span>

<span class="hljs-comment">// Check myName's current value:</span>
author.showMyName();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Oluwatobi"</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-7acrhs"><strong>Try Editing It</strong></a></p>
<p><strong>Note:</strong></p>
<ul>
<li>A <code>constructor()</code> method can only be public. Browsers will throw an <code>Uncaught SyntaxError</code> if you define it as a private class field.</li>
<li>You cannot create private class fields later (outside the class’s body). For instance, writing <code>author.#wifeName = "Sarah"</code> will throw an <code>Uncaught SyntaxError</code>.</li>
<li>Private class fields make data encapsulation possible in JavaScript classes.</li>
</ul>
<h3 id="heading-what-is-a-static-class-field-in-javascript-classes">What is a Static Class Field in JavaScript Classes?</h3>
<p>A static class field is a property you can only access and modify directly from the class itself.</p>
<p>In other words, JavaScript interprets static fields as a class’s own properties—not <a target="_blank" href="https://codesweetly.com/web-tech-terms-i#instance-property-in-javascript">instance</a> or <a target="_blank" href="https://codesweetly.com/web-tech-terms-p#prototypal-property-in-javascript">prototypal</a> properties.</p>
<p>Therefore, a class’s instance or <code>prototype</code> object cannot access static class fields.</p>
<p><strong>Tip:</strong></p>
<ul>
<li>Although you can define multiple static class fields with the same name, the last field will overwrite the previous ones.</li>
<li>JavaScript does not add static fields to the <code>prototype</code> property. They remain in the class’s body as its own properties. So, they are ideal for properties you wish to avoid replicating across the class’s instance objects.</li>
</ul>
<p>We prefix a class field with the <code>static</code> keyword to make it a static property.</p>
<h4 id="heading-example-how-to-create-static-class-fields">Example: How to create static class fields</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create a static class field:</span>
  <span class="hljs-keyword">static</span> myName = <span class="hljs-string">"Oluwatobi"</span>;
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> author = <span class="hljs-keyword">new</span> Name();

<span class="hljs-comment">// Check myName's current value:</span>
author.myName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-literal">undefined</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-dcx7ck"><strong>Try Editing It</strong></a></p>
<p>The snippet above returned <code>undefined</code> because <code>myName</code> is a static class field that can only be read and modified from the class itself, not through its instance.</p>
<p>In other words, you need to call <code>myName</code> on the class itself to read or modify it.</p>
<h4 id="heading-example-how-to-access-static-class-fields">Example: How to access static class fields</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create a static class field:</span>
  <span class="hljs-keyword">static</span> myName = <span class="hljs-string">"Oluwatobi"</span>;
}

<span class="hljs-comment">// Check myName's current value:</span>
Name.myName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Oluwatobi"</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-cvbm6x"><strong>Try Editing It</strong></a></p>
<p>Suppose you define multiple static class fields with the same name. In that case, the last property will overwrite the previous ones.</p>
<h4 id="heading-example-the-last-static-class-field-overwrites-the-previous-ones-with-the-same-name">Example: The last static class field overwrites the previous ones with the same name</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create static class fields:</span>
  <span class="hljs-keyword">static</span> myName = <span class="hljs-string">"Oluwatobi"</span>;
  <span class="hljs-keyword">static</span> myName = <span class="hljs-string">"Sofela"</span>;
  <span class="hljs-keyword">static</span> myName = <span class="hljs-string">"CodeSweetly"</span>;
}

<span class="hljs-comment">// Check myName's current value:</span>
Name.myName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"CodeSweetly"</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-field/js-wtvny3"><strong>Try Editing It</strong></a></p>
<p>The snippet above returned <code>"CodeSweetly"</code> because the last <code>myName</code> static class field overwrites the previously declared ones.</p>
<p>Now that we know the components of a JavaScript class, we can discuss its types.</p>
<h2 id="heading-types-of-javascript-classes">Types of JavaScript Classes</h2>
<p>The three types of JavaScript classes are:</p>
<ul>
<li>Class declaration</li>
<li>Class expression</li>
<li>Derived class</li>
</ul>
<p>Let’s discuss each type.</p>
<h3 id="heading-what-is-a-javascript-class-declaration">What is a JavaScript Class Declaration?</h3>
<p>A class declaration is a class created without assigning it to a <a target="_blank" href="https://codesweetly.com/javascript-variable">variable</a>.</p>
<p>We sometimes call class declaration a “class definition” or “class statement.”</p>
<p>Here’s an example:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Numbers</span> </span>{}
</code></pre>
<p>The class above is a class declaration because we defined it without storing it in a variable.</p>
<h3 id="heading-what-is-a-javascript-class-expression">What is a JavaScript Class Expression?</h3>
<p>A class expression is a class you create and assign to a variable.</p>
<p>Here’s an example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myClassExpr = <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Numbers</span> </span>{};
</code></pre>
<p>The class above is a named class expression that we assigned to the <code>myClassExpr</code> variable.</p>
<p><strong>Note:</strong> You can only use a class expression’s name within the class’s body. In other words, JavaScript allows you to use <code>myClassExpr</code> and <code>Numbers</code> interchangeably within the class’s body. However, only <code>myClassExpr</code> is callable outside the class. Otherwise, browsers will throw a <code>ReferenceError</code>.</p>
<p>You can also write the snippet above as an anonymous class expression like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myClassExpr = <span class="hljs-class"><span class="hljs-keyword">class</span> </span>{};
</code></pre>
<p>The class above is an anonymous function expression assigned to the <code>myClassExpr</code> variable.</p>
<p><strong>Tip:</strong></p>
<ul>
<li>An anonymous class is a class with no name.</li>
<li>A named class is a class with a name.</li>
</ul>
<p>Let’s now discuss derived classes.</p>
<h3 id="heading-what-is-a-derived-class-in-javascript">What is a Derived Class in JavaScript?</h3>
<p>A derived class is a class that extends the <a class="post-section-overview" href="#heading-what-is-a-public-class-field-in-javascript-classes-1">public</a> and <a class="post-section-overview" href="#heading-what-is-a-static-class-field-in-javascript-classes-1">static</a> features of an existing class.</p>
<p>In other words, a derived class is the child of a parent class.</p>
<p><strong>Important:</strong> A derived class <em>cannot</em> access its parent class’s <a class="post-section-overview" href="#heading-what-is-a-private-class-field-in-javascript-classes-1">private features</a>.</p>
<h4 id="heading-syntax-of-a-derived-class">Syntax of a derived class</h4>
<p>We use the <code>extends</code> keyword to create a derived class.</p>
<p><strong>Tip:</strong> The <code>extends</code> keyword in JavaScript makes one class the child of another constructor. In other words, the <code>extends</code> keyword assigns a constructor (class or function) as a specified class’s <a target="_blank" href="https://codesweetly.com/default-function-properties-in-javascript#what-is-the-default-prototype-property-in-javascript-functions-1">dunder proto</a>.</p>
<p>Here’s the syntax:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DerivedClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">BaseClass</span> </span>{
  <span class="hljs-comment">// derived class's body</span>
}
</code></pre>
<ul>
<li>A derived class is sometimes called a child class.</li>
<li>A base class is sometimes called a parent class.</li>
<li>You can extend any constructor (class or function) that meets the following criteria:<ul>
<li>You can use the <code>new</code> keyword to create an object instance from it.</li>
<li>It has a <a target="_blank" href="https://codesweetly.com/default-function-properties-in-javascript#what-is-the-default-prototype-property-in-javascript-functions"><code>prototype</code></a> property.</li>
<li>Its <code>prototype</code> property’s value is an <a target="_blank" href="https://codesweetly.com/javascript-properties-object">object</a> or <code>null</code>.</li>
</ul>
</li>
</ul>
<p>Once you extend a child class to a parent class, the derived class will inherit all its base class’s public and static class fields.</p>
<h4 id="heading-example-how-to-use-a-base-classs-features-in-a-derived-class">Example: How to use a base class’s features in a derived class</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create a public class field:</span>
  myName = <span class="hljs-string">"Oluwatobi"</span>;
}

<span class="hljs-comment">// Create a derived class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bio</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Name</span> </span>{ }

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> myBio = <span class="hljs-keyword">new</span> Bio();

<span class="hljs-comment">// Check myBio's current value:</span>
myBio;

<span class="hljs-comment">// The invocation above will return:</span>
{ <span class="hljs-attr">myName</span>: <span class="hljs-string">"Oluwatobi"</span> }
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-explained/js-jivp9r"><strong>Try Editing It</strong></a></p>
<p>The <code>Bio</code> class inherited its parent’s property because we used the <code>extends</code> keyword to assign the <code>Name</code> class as the derived class’s dunder proto.</p>
<p><strong>Note:</strong> A derived class’s class field will override its parent class’s property with the same name. For example, consider the following code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  myName = <span class="hljs-string">"Oluwatobi"</span>;
}

<span class="hljs-comment">// Create a derived class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bio</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Name</span> </span>{
  myName = <span class="hljs-string">"Sofela"</span>;
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> myBio = <span class="hljs-keyword">new</span> Bio();

<span class="hljs-comment">// Check myBio's current value:</span>
myBio;

<span class="hljs-comment">// The invocation above will return:</span>
{ <span class="hljs-attr">myName</span>: <span class="hljs-string">"Sofela"</span> }
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-explained/js-kxiztt"><strong>Try Editing It</strong></a></p>
<p>JavaScript also allows you to use the <code>super</code> keyword to access a parent class’s static or prototypal class fields from derived classes. Let’s discuss more on this now.</p>
<h2 id="heading-what-is-the-super-keyword-in-javascript">What is the <code>super</code> Keyword in JavaScript?</h2>
<p>The <code>super</code> keyword searches a parent class or object literal for a specified static or prototypal property.</p>
<p>For instance, consider the following snippet:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Oluwatobi is my Name"</span>);
  }
}

<span class="hljs-comment">// Create a child class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bio</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-comment">// Use super to access the parent class's constructor:</span>
    <span class="hljs-built_in">super</span>();
  }
}

<span class="hljs-comment">// Invoke the Bio constructor class:</span>
<span class="hljs-keyword">new</span> Bio();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Oluwatobi is my Name."</span>
{}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/operators/super-keyword/js-qcdu2a"><strong>Try Editing It</strong></a></p>
<p>The <code>super()</code> function call in the snippet above tells the computer to find a <code>constructor</code> in the parent class’s prototype chain.</p>
<p>You can use the <code>super</code> keyword as a “function caller” or “property accessor.” Let’s discuss how.</p>
<h3 id="heading-how-to-use-the-super-keyword-as-a-function-caller">How to Use the <code>super</code> Keyword as a Function Caller</h3>
<p>The <code>super()</code> function caller finds and invokes the parent class’s <code>constructor()</code> method.</p>
<p>In other words, <code>super()</code> allows you to access a parent class’s <code>constructor</code> from the <code>constructor</code> of a derived class.</p>
<h4 id="heading-syntax-of-the-super-keyword-as-a-function-caller">Syntax of the <code>super</code> keyword as a function caller</h4>
<pre><code class="lang-js"><span class="hljs-built_in">super</span>(argument1, …, argumentN);
</code></pre>
<p><strong>Note:</strong> A <code>super()</code> function caller is valid only in a derived class’s <code>constructor()</code> method.</p>
<h4 id="heading-example-how-to-use-the-super-function-caller">Example: How to use the <code>super()</code> function caller</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }
}

<span class="hljs-comment">// Create a derived class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bio</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-keyword">constructor</span>(firstName) {
    <span class="hljs-comment">// Use super to access the parent class's constructor:</span>
    <span class="hljs-built_in">super</span>(firstName);
  }
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> myBio = <span class="hljs-keyword">new</span> Bio(<span class="hljs-string">"Oluwatobi"</span>);

<span class="hljs-comment">// Check myBio's current value:</span>
myBio;

<span class="hljs-comment">// The invocation above will return:</span>
{ <span class="hljs-attr">name</span>: <span class="hljs-string">"Oluwatobi"</span> }
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/operators/super-keyword/js-cdc4ks"><strong>Try Editing It</strong></a></p>
<p>The <code>super()</code> function call in the snippet above tells the computer to find and invoke the parent class’s <code>constructor()</code>.</p>
<p>In other words, the <code>super()</code> function call searches for a <code>constructor</code> in <code>Name</code>’s prototype chain.</p>
<p><strong>Note the following:</strong></p>
<ul>
<li>Calling <code>super()</code> allows JavaScript to use the parent class’s <code>constructor</code> to initialize <code>this</code>. So, a <code>super()</code> function call is similar to writing <code>this = new ParentClass()</code>.</li>
<li>JavaScript requires you to call <code>super()</code> before using the <a target="_blank" href="https://www.freecodecamp.org/news/the-this-keyword-in-javascript/">keyword</a> <code>this</code>. Otherwise, the browser will throw a <code>ReferenceError</code>. In other words, a derived class’s <code>constructor</code> cannot access an uninitialized keyword <code>this</code>.</li>
</ul>
<h4 id="heading-example-what-happens-if-you-access-this-before-super-in-a-derived-classs-constructor">Example: What happens if you access <code>this</code> before <code>super</code> in a derived class’s <code>constructor</code>?</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }
}

<span class="hljs-comment">// Create a derived class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bio</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-keyword">constructor</span>(firstName) {
    <span class="hljs-built_in">this</span>.lastName = <span class="hljs-string">"Sofela"</span>; <span class="hljs-comment">// Using the keyword this before super will cause the browser to throw a ReferenceError:</span>
    <span class="hljs-built_in">super</span>(firstName);
  }
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> myBio = <span class="hljs-keyword">new</span> Bio(<span class="hljs-string">"Oluwatobi"</span>);
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/operators/super-keyword/js-zyd4dm"><strong>Try Editing It</strong></a></p>
<p>The snippet above throws an <code>Uncaught ReferenceError</code> because a derived class’s <code>constructor</code> cannot access the keyword <code>this</code> before the <code>super()</code> function caller.</p>
<h4 id="heading-example-what-happens-if-you-use-only-this-keyword-in-a-derived-classs-constructor">Example: What happens if you use only <code>this</code> keyword in a derived class’s <code>constructor</code>?</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  createName() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Sofela"</span>;
  }
}

<span class="hljs-comment">// Create a derived class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bio</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">this</span>.firstName = <span class="hljs-string">"Oluwatobi"</span>; <span class="hljs-comment">// Using the keyword this before super will cause the browser to throw a ReferenceError:</span>
  }
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> myBio = <span class="hljs-keyword">new</span> Bio();
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/operators/super-keyword/js-sgc2tx"><strong>Try Editing It</strong></a></p>
<p>The snippet above throws an <code>Uncaught ReferenceError</code> because a derived class’s <code>constructor</code> cannot access the keyword <code>this</code> before the <code>super()</code> function caller.</p>
<p>Now that we know how to use the <code>super</code> keyword as a function caller, we can discuss using it as a property accessor.</p>
<h3 id="heading-how-to-use-the-super-keyword-as-a-property-accessor">How to Use the <code>super</code> Keyword as a Property Accessor</h3>
<p>You can use the <code>super</code> keyword as a property accessor in your JavaScript classes and object literals.</p>
<ul>
<li><strong>Class Usage:</strong> The <code>super</code> keyword searches a class’s parent for a specified static or prototypal class field. In other words, <code>super</code> allows you to access a parent class’s static or prototypal properties from a child class.</li>
<li><strong>Object Literal Usage:</strong> The <code>super</code> keyword searches an object’s parent for a specified prototypal property. In other words, <code>super</code> allows you to access the parent object’s prototypal properties from a child object.</li>
</ul>
<h4 id="heading-syntax-of-the-super-keyword-as-a-dot-notation-property-accessor">Syntax of the <code>super</code> keyword as a dot notation property accessor</h4>
<pre><code class="lang-js"><span class="hljs-built_in">super</span>.parentClassOrObjectProperty;
</code></pre>
<h4 id="heading-example-use-the-super-keywords-dot-notation-to-access-the-parent-classs-static-field">Example: Use the <code>super</code> keyword’s dot notation to access the parent class’s static field</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create a static class field:</span>
  <span class="hljs-keyword">static</span> myName = <span class="hljs-string">"Oluwatobi"</span>;
}

<span class="hljs-comment">// Create a derived class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bio</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create a static property from the parent class's static class field:</span>
  <span class="hljs-keyword">static</span> firstName = <span class="hljs-built_in">super</span>.myName;
}

<span class="hljs-comment">// Check firstName's current value:</span>
Bio.firstName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Oluwatobi"</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/operators/super-keyword/js-cr3jfd"><strong>Try Editing It</strong></a></p>
<p>We used the <code>super</code> keyword in the snippet above to access the parent class’s static class field.</p>
<p><strong>Note:</strong> Prefixing the <code>firstName</code> statement with a <code>static</code> keyword makes <code>super</code> find a <code>myName</code> <a target="_blank" href="https://codesweetly.com/web-tech-terms-s#static-class-field-in-javascript">static property</a> in the parent class.</p>
<p>Suppose you omit the <code>static</code> keyword. In that case, <code>super</code> will search for a <code>myName</code> <a target="_blank" href="https://codesweetly.com/web-tech-terms-p#prototypal-property-in-javascript">prototypal property</a> in the parent class.</p>
<h4 id="heading-example-use-the-super-keywords-dot-notation-to-access-the-parent-classs-prototypal-field">Example: Use the <code>super</code> keyword’s dot notation to access the parent class’s prototypal field</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Time</span> </span>{
  <span class="hljs-comment">// Create a prototypal method:</span>
  hourNow() {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours();
  }

  <span class="hljs-comment">// Create a second prototypal method:</span>
  minutesNow() {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getMinutes();
  }
}

<span class="hljs-comment">// Create a derived class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Moment</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Time</span> </span>{
  <span class="hljs-comment">// Create an instance property using the parent class's prototypal methods:</span>
  currentMoment = <span class="hljs-string">`The time is <span class="hljs-subst">${<span class="hljs-built_in">super</span>.hourNow()}</span>:<span class="hljs-subst">${<span class="hljs-built_in">super</span>.minutesNow()}</span>.`</span>
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> momentNow = <span class="hljs-keyword">new</span> Moment();

<span class="hljs-comment">// Check momentNow's current value:</span>
<span class="hljs-built_in">console</span>.log(momentNow);
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/operators/super-keyword/js-fr9bvs"><strong>Try Editing It</strong></a></p>
<p>We used the <code>super</code> keyword in the snippet above to access the parent class’s prototypal class fields.</p>
<h4 id="heading-example-use-the-super-keywords-dot-notation-to-access-a-parent-objects-prototypal-property">Example: Use the <code>super</code> keyword’s dot notation to access a parent object’s prototypal property</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new object:</span>
<span class="hljs-keyword">const</span> website = {
  <span class="hljs-comment">// Create a method:</span>
  showName() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"CodeSweetly"</span>;
  }
}

<span class="hljs-comment">// Create another object:</span>
<span class="hljs-keyword">const</span> company = {
  <span class="hljs-comment">// Create a method:</span>
  showCompany() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">super</span>.showName();
  }
}

<span class="hljs-comment">// Change company's dunder proto to the website object:</span>
<span class="hljs-built_in">Object</span>.setPrototypeOf(company, website);

<span class="hljs-comment">// Invoke the showCompany method:</span>
company.showCompany()

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"CodeSweetly"</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/operators/super-keyword/js-mxdvkm"><strong>Try Editing It</strong></a></p>
<p>We used the <code>super</code> keyword in the snippet above to access the parent object’s <code>showName()</code> method.</p>
<p><strong>Note:</strong> The <code>Object.setPrototypeOf()</code> code changes the company’s <a target="_blank" href="https://codesweetly.com/default-function-properties-in-javascript#what-is-the-default-prototype-property-in-javascript-functions-1"><code>[[Prototype]]</code> property</a> to the website object. Therefore, the <code>company</code> object’s <a target="_blank" href="https://codesweetly.com/default-function-properties-in-javascript#the-javascript-prototype-chain-diagram">prototype chain</a> will look like this:</p>
<pre><code class="lang-txt">{ showCompany: showCompany() } ---&gt; { showName: showName() } ---&gt; Object.prototype ---&gt; null
</code></pre>
<p>You can also use the <code>super</code> keyword as a bracket notation property accessor to search a parent class or object literal for a specified static or prototypal property.</p>
<h4 id="heading-syntax-of-the-super-keyword-as-a-bracket-notation-property-accessor">Syntax of the <code>super</code> keyword as a bracket notation property accessor</h4>
<pre><code class="lang-js"><span class="hljs-built_in">super</span>[expresssion];
</code></pre>
<h4 id="heading-example-use-the-super-keywords-bracket-notation-to-access-a-parent-classs-static-field">Example: Use the <code>super</code> keyword’s bracket notation to access a parent class’s static field</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create a static class field:</span>
  <span class="hljs-keyword">static</span> myName = <span class="hljs-string">"Oluwatobi"</span>;
}

<span class="hljs-comment">// Create a derived class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bio</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create a static property from the parent class's static class field:</span>
  <span class="hljs-keyword">static</span> firstName = <span class="hljs-built_in">super</span>[<span class="hljs-string">"myName"</span>];
}

<span class="hljs-comment">// Check firstName's current value:</span>
Bio.firstName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Oluwatobi"</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/operators/super-keyword/js-vpw14s"><strong>Try Editing It</strong></a></p>
<p>We used the <code>super</code> keyword in the snippet above to access the parent class’s static class field.</p>
<p><strong>Note:</strong> <code>super</code> cannot access a parent class’s instance class field because JavaScript sets an instance property on the object instance, not the class itself or its prototype chain. (<code>super</code> searches only for a parent’s static or prototypal properties.)</p>
<h4 id="heading-example-use-the-super-keyword-to-access-the-parent-classs-instance-field">Example: Use the <code>super</code> keyword to access the parent class’s instance field</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create an instance class field:</span>
  myName = <span class="hljs-string">"Oluwatobi"</span>;
}

<span class="hljs-comment">// Create a derived class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bio</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create an instance property from the parent class's instance class field:</span>
  firstName = <span class="hljs-built_in">super</span>.myName;
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> myBio = <span class="hljs-keyword">new</span> Bio();

<span class="hljs-comment">// Check myBio's current value:</span>
myBio;

<span class="hljs-comment">// The invocation above will return:</span>
{ <span class="hljs-attr">myName</span>: <span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-attr">firstName</span>: <span class="hljs-literal">undefined</span> }
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/operators/super-keyword/js-kqsqqe"><strong>Try Editing It</strong></a></p>
<p>The <code>firstName</code> property’s value is <code>undefined</code> because <code>super</code> could not find a prototypal <code>myName</code> field on the parent class.</p>
<p><strong>Note:</strong> The keywords <code>super</code> and <code>[this](https://codesweetly.com/javascript-this-keyword)</code> allow you to search for a specified property in an object’s prototype chain. But they work in different ways. Let’s discuss their differences now.</p>
<h3 id="heading-super-vs-this-keyword-whats-the-difference"><code>super</code> vs. <code>this</code> keyword: What’s the Difference?</h3>
<p>The difference between the <code>super</code> and <code>this</code> keyword is as follows:</p>
<ul>
<li><code>super</code> searches for a specified prototypal property in a parent class’s prototype chain.</li>
<li><code>this</code> searches for a specified prototypal property from a class’s object instance’s own properties to its prototype chain.</li>
</ul>
<p>In other words, <code>super</code> starts its search from the parent class’s <code>prototype</code> property. But <code>this</code> searches from an object instance’s local scope to its prototype chain.</p>
<p>For instance, consider the following code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ParentClass</span> </span>{
  <span class="hljs-comment">// Create a prototypal method:</span>
  showId() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"I am a parent."</span>;
  }
}

<span class="hljs-comment">// Create a derived class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ParentClass</span> </span>{
  <span class="hljs-comment">// Create a prototypal method:</span>
  showId() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"I am a child."</span>;
  }
  <span class="hljs-comment">// Create another prototypal method:</span>
  getId() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">super</span>.showId());
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.showId());
  }
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> instanceObject = <span class="hljs-keyword">new</span> ChildClass();

<span class="hljs-comment">// Invoke the instanceObject's getId() method:</span>
instanceObject.getId();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"I am a parent."</span>
<span class="hljs-string">"I am a child."</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/operators/super-keyword/js-v2st2a"><strong>Try Editing It</strong></a></p>
<p>Here’s how <code>super</code> and <code>this</code> performed their searches:</p>
<table>
  <thead>
    <tr>
      <th></th>
      <th>super</th>
      <th>this</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1.</td>
      <td>
        Find <code>showId()</code> in <code>ParentClass</code>’s prototype chain, starting from
        <code>ParentClass.prototype</code>. <em>Found it.</em>
      </td>
      <td>
        Find <code>showId()</code> in <code>instanceObject</code>’s own properties. <em>Found none.</em>
      </td>
    </tr>
    <tr>
      <td>2.</td>
      <td>
        (Suppose <code>showId()</code> is not in <code>ParentClass.prototype</code>. In that case,
        <code>super</code> will continue its search in <code>Object.prototype</code>.)
      </td>
      <td>
        Find <code>showId()</code> in <code>instanceObject</code>’s prototype chain, starting from
        <code>ChildClass.prototype</code>. <em>Found it.</em>
      </td>
    </tr>
    <tr>
      <td>3.</td>
      <td></td>
      <td>
        (Suppose <code>showId()</code> is not in <code>ChildClass.prototype</code>. In that case,
        <code>this</code> will continue its search in <code>ParentClass.prototype</code>.)
      </td>
    </tr>
    <tr>
      <td>4.</td>
      <td></td>
      <td>
        (Suppose <code>showId()</code> is not in <code>ChildClass.prototype</code> and
        <code>ParentClass.prototype</code>. In that case, <code>this</code> will continue its search
        in <code>Object.prototype</code>.)
      </td>
    </tr>
  </tbody>
</table>

<p>You can see that <code>super</code> shortens the steps required to find a prototypal method.</p>
<p>Now that we know how to use the three types of JavaScript classes, let’s look at the main components in one piece.</p>
<h2 id="heading-components-of-a-javascript-class">Components of a JavaScript Class</h2>
<p>The main features of a JavaScript class are as follows:</p>
<ol>
<li>A <code>class</code> keyword</li>
<li>The class’s name</li>
<li>The <code>extends</code> clause</li>
<li>A code block (<code>{...}</code>)</li>
<li>The class’s body</li>
<li>A <code>constructor</code> method</li>
<li><code>super()</code> function caller</li>
<li><code>super</code> property accessor</li>
<li>Instance class fields</li>
<li>Prototypal class fields</li>
<li>Private class fields</li>
<li>Static class fields</li>
<li>Static initialization blocks</li>
</ol>
<p>Let’s look at these features in a class declaration.</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ParentClass</span> </span>{
  <span class="hljs-keyword">constructor</span>(parameter) {
    <span class="hljs-built_in">super</span>(parameter);
  }
  instanceClassField = <span class="hljs-string">"Value can be any valid JavaScript data type"</span>;
  prototypalClassField() {
    <span class="hljs-comment">// prototypalClassField's body</span>
  }
  #privateClassField = <span class="hljs-string">"Value can be any valid JavaScript data type"</span>;
  <span class="hljs-keyword">static</span> classField = <span class="hljs-string">"Value can be any valid JavaScript data type"</span>;
  <span class="hljs-keyword">static</span> classFieldWithSuperValue = <span class="hljs-built_in">super</span>.parentProperty;
  <span class="hljs-keyword">static</span> #privateClassField = <span class="hljs-string">"Value can be any valid JavaScript data type"</span>;
  <span class="hljs-keyword">static</span> {
    <span class="hljs-comment">// Static initialization block's body</span>
  }
}
</code></pre>
<p>The constructor function equivalence of the snippet above looks like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildClass</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">this</span>.instanceClassField = <span class="hljs-string">"Value can be any valid JavaScript data type"</span>;
}

<span class="hljs-built_in">Object</span>.setPrototypeOf(ChildClass, ParentClass);

ChildClass.prototype.prototypalClassField = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// prototypalClassField's body</span>
}

ChildClass.staticClassField = <span class="hljs-string">"Value can be any valid JavaScript data type"</span>;

ChildClass.staticClassFieldWithSuperValue = <span class="hljs-built_in">Object</span>.getPrototypeOf(ChildClass).parentProperty;

(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Static initialization block's body</span>
})();
</code></pre>
<p><strong>Note:</strong> You currently cannot create private fields in constructor functions. They are one of the latest features JavaScript introduced in classes.</p>
<h2 id="heading-how-does-a-javascript-class-help-with-encapsulation">How Does a JavaScript Class Help with Encapsulation?</h2>
<p>Classes let you prevent external code from interacting with internal class fields. Instead, external code would use public methods to operate on the class’s internal implementations.</p>
<p>For instance, consider the following code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create a private class field data:</span>
  #myName = <span class="hljs-string">"Oluwatobi"</span>;

  <span class="hljs-comment">// Create a publicly available method:</span>
  showMyName() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.#myName;
  }

  <span class="hljs-comment">// Create another publicly available method:</span>
  updateMyName(value) {
    <span class="hljs-built_in">this</span>.#myName = value;
  }
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> bio = <span class="hljs-keyword">new</span> Name();

<span class="hljs-comment">// Check the instance's data value:</span>
bio.myName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-literal">undefined</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/encapsulation/js-q7uqv4"><strong>Try Editing It</strong></a></p>
<p>The snippet above <a target="_blank" href="https://codesweetly.com/web-tech-terms-e#encapsulation">encapsulated</a> <code>Name</code>’s data because it defined <code>myName</code> as a private feature and provided two public methods for users to read and update the class’s internal implementation.</p>
<p>Consequently, the <code>bio</code> instance object knows nothing about the class’s internal data and cannot interact with it directly.</p>
<p>Whenever users need to access the encapsulated data, they would use the publicly available methods like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Check the instance's data value:</span>
bio.showMyName();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Oluwatobi"</span>

<span class="hljs-comment">// Update the instance's data value:</span>
bio.updateMyName(<span class="hljs-string">"Sofela"</span>);

<span class="hljs-comment">// Check the instance's data value:</span>
bio.showMyName();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Sofela"</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/encapsulation/js-3vq4es"><strong>Try Editing It</strong></a></p>
<p>Encapsulating your data is an excellent way to keep your class clean. It prevents minor internal refactoring from breaking users’ code.</p>
<p>For instance, consider the following code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Create a public class field data:</span>
  myName = <span class="hljs-string">"Oluwatobi"</span>;
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> bio = <span class="hljs-keyword">new</span> Name();

<span class="hljs-comment">// Check the instance's data value:</span>
bio.myName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Oluwatobi"</span>

<span class="hljs-comment">// Update the instance's data value:</span>
bio.myName = <span class="hljs-string">"Sofela"</span>;

<span class="hljs-comment">// Check the instance's data value:</span>
bio.myName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Sofela"</span>
</code></pre>
<p>Since the snippet above did not encapsulate the class’s data, refactoring the class field’s name would break users’ code.</p>
<p>Here’s an example:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Update the data's name from myName to myFirstName:</span>
  myFirstName = <span class="hljs-string">"Oluwatobi"</span>;
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> bio = <span class="hljs-keyword">new</span> Name();

<span class="hljs-comment">// Check the instance's data value:</span>
bio.myName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-literal">undefined</span>
</code></pre>
<p>The snippet above returned <code>undefined</code> because refactoring the class’s internal implementation broke the user’s <code>bio.myName</code> code. For the application to work appropriately, the user must update every instance of the code (which can be burdensome for large projects).</p>
<p>However, encapsulation prevents such refactoring from breaking the user’s code.</p>
<p>Here’s an example:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-comment">// Update the data's name from myName to myFirstName:</span>
  #myFirstName = <span class="hljs-string">"Oluwatobi"</span>;

  <span class="hljs-comment">// Create a publicly available method:</span>
  showMyName() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.#myFirstName;
  }

  <span class="hljs-comment">// Create another publicly available method:</span>
  updateMyName(value) {
    <span class="hljs-built_in">this</span>.#myFirstName = value;
  }
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> bio = <span class="hljs-keyword">new</span> Name();

<span class="hljs-comment">// Check the instance's data value:</span>
bio.showMyName();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Oluwatobi"</span>

<span class="hljs-comment">// Update the instance's data value:</span>
bio.updateMyName(<span class="hljs-string">"Sofela"</span>);

<span class="hljs-comment">// Check the instance's data value:</span>
bio.showMyName();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Sofela"</span>
</code></pre>
<p>You can see that refactoring the class’s internal implementation did not break the user’s code. That’s the beauty of encapsulation!</p>
<p>Encapsulation allows you to provide users with an interface independent of the class’s underlying data. Therefore, you minimize the likelihood of users’ code breaking when you alter internal implementations.</p>
<h2 id="heading-important-things-to-know-about-javascript-classes">Important Things to Know about JavaScript Classes</h2>
<p>Here are five essential facts to remember when using JavaScript classes.</p>
<h3 id="heading-1-declare-your-class-before-you-access-it">1. Declare your class before you access it</h3>
<p>Classes are like constructor functions but have the same <a target="_blank" href="https://codesweetly.com/javascript-temporal-dead-zone#how-does-vars-tdz-differ-from-let-and-const-variables">temporal dead zone</a> behavior as <code>const</code> and <code>let</code> variables.</p>
<p>In other words, JavaScript does not <a target="_blank" href="https://www.freecodecamp.org/news/what-is-hoisting-in-javascript-3/">hoist</a> class declarations. Therefore, you must first declare your class before you can access it. Otherwise, the computer will throw an <code>Uncaught ReferenceError</code>.</p>
<p>Here’s an example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Create an object instance from the Name class:</span>
<span class="hljs-keyword">const</span> name = <span class="hljs-keyword">new</span> Name();

<span class="hljs-comment">// Define the Name class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-explained/js-74u2wt"><strong>Try Editing It</strong></a></p>
<p>The snippet above throws an <code>Uncaught ReferenceError</code> because JavaScript does not hoist classes. So, invoking <code>Name()</code> before its definition is invalid.</p>
<h3 id="heading-2-classes-are-functions">2. Classes are functions</h3>
<p>The <code>typeof</code> a class is a function because, under the hood, the <code>class</code> keyword creates a new <a target="_blank" href="https://codesweetly.com/javascript-function-object">function</a>.</p>
<p>For instance, consider the following code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a JavaScript class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Bio</span> </span>{
  <span class="hljs-comment">// Define two instance class fields:</span>
  firstName = <span class="hljs-string">"Oluwatobi"</span>;
  lastName = <span class="hljs-string">"Sofela"</span>;
  <span class="hljs-comment">// Create a prototypal method:</span>
  showBio() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${ firstName }</span> <span class="hljs-subst">${ lastName }</span> runs CodeSweetly.`</span>;
  }
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> aboutMe = <span class="hljs-keyword">new</span> Bio();

<span class="hljs-comment">// Check what data type the Bio class is:</span>
<span class="hljs-keyword">typeof</span> Bio;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"function"</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-explained/js-spwwdy"><strong>Try Editing It</strong></a></p>
<p>The computer processes the snippet above as follows:</p>
<ol>
<li>Create a new function named <code>Bio</code>.</li>
<li>Add the class’s instance properties to the newly created function’s <code>this</code> keyword.</li>
<li>Add the class’s prototypal properties to the newly created function’s <code>prototype</code> property.</li>
</ol>
<h3 id="heading-3-classes-are-strict">3. Classes are strict</h3>
<p>JavaScript executes classes in strict mode. So, follow the strict syntax rules when you use classes. Otherwise, your code will throw errors—some of which will be silent errors that are difficult to debug.</p>
<h3 id="heading-4-avoid-the-return-keyword-in-your-classs-constructor-method">4. Avoid the <code>return</code> keyword in your class’s <code>constructor</code> method</h3>
<p>Suppose your class’s <code>constructor</code> returns a <a target="_blank" href="https://codesweetly.com/javascript-non-primitive-data-type">non-primitive value</a>. In that case, JavaScript will ignore the values of all the <code>this</code> keywords and assign the non-primitive to the <code>new</code> keyword expression.</p>
<p>In other words, a <code>constructor</code>’s <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_properties#returning_overriding_object"><code>return</code> object overrides</a> its <code>this</code> keyword.</p>
<p>For instance, consider the following code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Create a new class:</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Name</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">this</span>.firstName = <span class="hljs-string">"Oluwatobi"</span>;
    <span class="hljs-built_in">this</span>.lastName = <span class="hljs-string">"Sofela"</span>;
    <span class="hljs-keyword">return</span> { <span class="hljs-attr">companyName</span>: <span class="hljs-string">"CodeSweetly"</span> };
  }
}

<span class="hljs-comment">// Create a new object instance:</span>
<span class="hljs-keyword">const</span> myName = <span class="hljs-keyword">new</span> Name();

<span class="hljs-comment">// Check myName's current value:</span>
myName;

<span class="hljs-comment">// The invocation above will return:</span>
{ <span class="hljs-attr">companyName</span>: <span class="hljs-string">"CodeSweetly"</span> }

<span class="hljs-comment">// Check firstName's current value:</span>
myName.firstName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-literal">undefined</span>

<span class="hljs-comment">// Check lastName's current value:</span>
myName.lastName;

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-literal">undefined</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/function/class/class-explained/js-vgwrmg"><strong>Try Editing It</strong></a></p>
<p>The <code>new</code> keyword expression returned only <code>{ companyName: "CodeSweetly" }</code> because JavaScript ignores the <code>constructor</code> method’s <code>this</code> keywords whenever you use a <code>return</code> operator to produce an object.</p>
<h3 id="heading-5-a-classs-evaluation-starts-from-the-extends-clause-to-its-values">5. A class’s evaluation starts from the <code>extends</code> clause to its values</h3>
<p>JavaScript evaluates your class according to the following order:</p>
<h4 id="heading-1-extends-clause">1. <code>extends</code> clause</h4>
<p>If you declare an <code>extends</code> clause, the computer will first evaluate it.</p>
<p><strong>Note:</strong> Browsers will throw a <code>TypeError</code> if the <code>extends</code> clause does not evaluate to a constructor function or <code>null</code>.</p>
<h4 id="heading-2-extract-the-classs-constructor">2. Extract the class’s <code>constructor</code></h4>
<p>JavaScript extracts the class’s <code>constructor</code>.</p>
<p><strong>Note:</strong> Suppose you did not define a <code>constructor</code> method. In that case, the computer will use the default one.</p>
<h4 id="heading-3-parse-the-classs-property-names">3. Parse the class’s property names</h4>
<p>The computer analyzes the class’s class field names (not their values) according to their order of declaration.</p>
<h4 id="heading-4-parse-the-classs-methods-and-property-accessors">4. Parse the class’s methods and property accessors</h4>
<p>JavaScript analyzes the class’s methods and property accessors according to their order of declaration by doing the following:</p>
<ul>
<li>Add the prototypal methods and property accessors to the class’s <code>prototype</code> property.</li>
<li>Analyze the static methods and property accessors as the class’s own properties, which you can call on the class itself.</li>
<li>Analyze the private instance methods and property accessors as private properties of the class’s instance object.</li>
</ul>
<h4 id="heading-5-parse-the-classs-property-values">5. Parse the class’s property values</h4>
<p>The computer analyzes the class field values according to their order of declaration by doing the following:</p>
<ul>
<li>Save each instance field’s initializer expression for later evaluations. JavaScript will evaluate the initializer expression during the following periods:<ul>
<li>When the <code>new</code> keyword is creating an instance object.</li>
<li>While processing the parent class’s <code>constructor</code>.</li>
<li>Before the <code>super()</code> function call returns.</li>
</ul>
</li>
<li>Set each static field’s keyword <code>this</code> to the class itself and create the static property on the class.</li>
<li>Evaluate the class’s <a target="_blank" href="https://codesweetly.com/web-tech-terms-s#static-initialization-blocks">static initialization blocks</a> and set their keyword <code>this</code> to the class itself.</li>
</ul>
<p><strong>Note:</strong></p>
<ul>
<li>Only after JavaScript parses a class’s property values is the class fully initialized and available as a constructor function.</li>
<li>Any attempt to access the child class before its complete initialization would return a <code>ReferenceError</code>.</li>
</ul>
<h2 id="heading-overview">Overview</h2>
<p>In this article, we discussed what a JavaScript class object is. We also used examples to discuss class fields, the <code>super</code> keyword, and data encapsulation.</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[ 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[ Web Storage Explained – How to Use localStorage and sessionStorage in JavaScript Projects ]]>
                </title>
                <description>
                    <![CDATA[ Web Storage is what the JavaScript API browsers provide for storing data locally and securely within a user’s browser. Session and local storage are the two main types of web storage. They are similar to regular properties objects, but they persist (... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/web-storage-localstorage-vs-sessionstorage-in-javascript/</link>
                <guid isPermaLink="false">66ba0e11256f04965e2bd0c7</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ storage ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Mon, 09 Oct 2023 16:45:31 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/10/web-storage-explained-local-and-session-storage-objects-in-javascript-codesweetly.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><strong>Web Storage</strong> is what the JavaScript <a target="_blank" href="https://codesweetly.com/application-programming-interface-api-explained">API</a> browsers provide for storing data locally and securely within a user’s browser.</p>
<p>Session and local storage are the two main types of web storage. They are similar to regular <a target="_blank" href="https://codesweetly.com/javascript-properties-object">properties objects</a>, but they persist (do not disappear) when the webpage reloads.</p>
<p>This article aims to show you exactly how the two storage objects work in JavaScript. We will also use a To-Do list exercise to practice using web storage in a web app project.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-the-session-storage-object">What is the Session Storage Object?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-local-storage-object">What is the Local Storage Object?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-access-the-session-and-local-storage-objects">How to Access the Session and Local Storage Objects</a></li>
<li><a class="post-section-overview" href="#heading-what-are-web-storages-built-in-interfaces">What are Web Storage’s Built-In Interfaces?</a><ul>
<li><a class="post-section-overview" href="#heading-what-is-web-storages-setitem-method">What is web storage’s <code>setItem()</code> method?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-web-storages-key-method">What is web storage’s <code>key()</code> method?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-web-storages-getitem-method">What is web storage’s <code>getItem()</code> method?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-web-storages-length-property">What is web storage’s <code>length</code> property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-web-storages-removeitem-method">What is web storage’s <code>removeItem()</code> method?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-web-storages-clear-method">What is web storage’s <code>clear()</code> method?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-time-to-practice-with-web-storage">Time to Practice with Web Storage 🤸‍♂️🏋️‍♀️</a><ul>
<li><a class="post-section-overview" href="#heading-the-problem">The Problem</a></li>
<li><a class="post-section-overview" href="#heading-your-exercise">Your Exercise</a></li>
<li><a class="post-section-overview" href="#heading-bonus-exercise">Bonus Exercise</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-did-you-go-about-solving-the-web-storage-exercise">How Did You Go About Solving the Web Storage Exercise?</a><ul>
<li><a class="post-section-overview" href="#heading-how-to-prevent-the-session-storage-panes-to-do-items-from-disappearing-on-page-reload">How to prevent the Session Storage pane’s To-Do items from disappearing on page reload</a></li>
<li><a class="post-section-overview" href="#heading-how-to-prevent-the-local-storage-panes-to-do-items-from-disappearing-on-page-reload-or-reopen">How to prevent the Local Storage pane’s To-Do items from disappearing on page reload or reopen</a></li>
<li><a class="post-section-overview" href="#heading-how-to-auto-display-the-session-sections-previously-added-tasks-on-page-reload">How to auto-display the Session section’s previously added tasks on page reload</a></li>
<li><a class="post-section-overview" href="#heading-how-to-auto-display-the-local-sections-previously-added-tasks-on-page-reload-or-reopen">How to auto-display the Local section’s previously added tasks on page reload or reopen</a></li>
<li><a class="post-section-overview" href="#heading-how-to-check-the-total-items-in-the-browsers-session-storage">How to check the total items in the browser’s session storage</a></li>
<li><a class="post-section-overview" href="#heading-how-to-display-the-local-storages-zeroth-index-items-name">How to display the local storage’s zeroth index item’s name</a></li>
<li><a class="post-section-overview" href="#heading-how-to-empty-the-browsers-session-storage">How to empty the browser’s session storage</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-how-to-continue-practicing-with-web-storage">How to Continue Practicing with Web Storage 🧗‍♀️🚀</a></li>
<li><a class="post-section-overview" href="#heading-web-storage-vs-cookies-what-is-the-difference">Web Storage vs. Cookies: What is the Difference?</a></li>
<li><a class="post-section-overview" href="#heading-wrapping-up">Wrapping up</a></li>
</ol>
<p>Without further ado, let’s discuss session storage.</p>
<h2 id="heading-what-is-the-session-storage-object">What is the Session Storage Object?</h2>
<p>The session storage object (<code>window.sessionStorage</code>) stores data that persists for only one session of an opened tab.</p>
<p>In other words, whatever gets stored in the <code>window.sessionStorage</code> object will not disappear on a reload of the web page. Instead, the computer will delete the stored data only when users close the browser tab or window.</p>
<p><strong>Note the following:</strong></p>
<ul>
<li>The data stored inside the session storage is per-<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">origin</a> and per-instance. In other words, <code>http://freecodecamp.com</code>’s <code>sessionStorage</code> object is different from <code>https://freecodecamp.com</code>’s <code>sessionStorage</code> object because the two origins use different <a target="_blank" href="https://codesweetly.com/web-address-url#scheme">schemes</a> (<code>http</code> and <code>https</code>).</li>
<li>Per-instance means per-window or per-tab. In other words, the <code>sessionStorage</code> object’s lifespan expires once users close the instance (window or tab).</li>
<li>Browsers create a unique page session for each new tab or window. Therefore, users can run multiple instances of an app without interfering with each instance’s session storage. (Note: Cookies do not have good support for running multiple instances of the same app. Such an attempt can cause errors such as <a target="_blank" href="https://html.spec.whatwg.org/multipage/webstorage.html#introduction-15">double entry of bookings</a>.)</li>
<li>Session storage is a property of the global <code>Window</code> object. So <code>sessionStorage.setItem()</code> is equivalent to <code>window.sessionStorage.setItem()</code>.</li>
</ul>
<h2 id="heading-what-is-the-local-storage-object">What is the Local Storage Object?</h2>
<p>The local storage object (<code>window.localStorage</code>) stores data that persists even when users close their browser tab (or window).</p>
<p>In other words, whatever gets stored in the <code>window.localStorage</code> object will not disappear during a reload or reopening of the web page or when users close their browsers. Those data have no expiration time. Browsers never clear them automatically.</p>
<p>The computer will delete the <code>window.localStorage</code> object’s content in the following instances only:</p>
<ol>
<li>When the content gets cleared through JavaScript</li>
<li>When the browser’s cache gets cleared</li>
</ol>
<p><strong>Note the following:</strong></p>
<ul>
<li>The <code>window.localStorage</code> object’s storage limit is larger than the <code>window.sessionStorage</code>.</li>
<li>The data stored inside the local storage is per-<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">origin</a>. In other words, <code>http://freecodecamp.com</code>’s <code>localStorage</code> object is different from <code>https://freecodecamp.com</code>’s <code>localStorage</code> object because the two origins use different <a target="_blank" href="https://codesweetly.com/web-address-url#scheme">schemes</a> (<code>http</code> and <code>https</code>).</li>
<li>There are inconsistencies with how browsers handle the local storage of documents not served from a web server (for instance, pages with a <code>file:</code> URL scheme). Therefore, the <code>localStorage</code> object may behave differently among browsers when used with non-HTTP URLs, such as <code>file:///document/on/users/local/system.html</code>.</li>
<li>Local storage is a property of the global <code>Window</code> object. Therefore, <code>localStorage.setItem()</code> is equivalent to <code>window.localStorage.setItem()</code>.</li>
</ul>
<h2 id="heading-how-to-access-the-session-and-local-storage-objects">How to Access the Session and Local Storage Objects</h2>
<p>You can access the two web storages by:</p>
<ol>
<li>Using the same technique as you'd use for <a target="_blank" href="https://codesweetly.com/javascript-properties-object#how-to-access-an-objects-value">accessing regular JavaScript objects</a></li>
<li>Using web storage’s built-in interfaces</li>
</ol>
<p>For instance, consider the snippet below:</p>
<pre><code class="lang-js">sessionStorage.bestColor = <span class="hljs-string">"Green"</span>;
sessionStorage[<span class="hljs-string">"bestColor"</span>] = <span class="hljs-string">"Green"</span>;
sessionStorage.setItem(<span class="hljs-string">"bestColor"</span>, <span class="hljs-string">"Green"</span>);
</code></pre>
<p>The three statements above do the same thing—they set <code>bestColor</code>’s value. But the third line is recommended because it uses web storage’s <code>setItem()</code> method.</p>
<p><strong>Tip:</strong> you should prefer using the web storage’s built-in interfaces to avoid <a target="_blank" href="https://2ality.com/2012/01/objects-as-maps.html">the pitfalls of using objects as key/value stores</a>.</p>
<p>Let’s discuss more on the web storage’s built-in interfaces below.</p>
<h2 id="heading-what-are-web-storages-built-in-interfaces">What are Web Storage’s Built-In Interfaces?</h2>
<p>The web storage built-in interfaces are the recommended tools for reading and manipulating a browser’s <code>sessionStorage</code> and <code>localStorage</code> objects.</p>
<p>The six (6) built-in interfaces are:</p>
<ul>
<li><code>setItem()</code></li>
<li><code>key()</code></li>
<li><code>getItem()</code></li>
<li><code>length</code></li>
<li><code>removeItem()</code></li>
<li><code>clear()</code></li>
</ul>
<p>Let’s discuss each one now.</p>
<h3 id="heading-what-is-web-storages-setitem-method">What is web storage’s <code>setItem()</code> method?</h3>
<p>The <code>setItem()</code> method stores its <code>key</code> and <code>value</code> arguments inside the specified web storage object.</p>
<h4 id="heading-syntax-of-the-setitem-method">Syntax of the <code>setItem()</code> method</h4>
<p><code>setItem()</code> accepts two required <a target="_blank" href="https://codesweetly.com/javascript-arguments">arguments</a>. Here is the syntax:</p>
<pre><code class="lang-js">webStorageObject.setItem(key, value);
</code></pre>
<ul>
<li><code>webStorageObject</code> represents the storage object (<code>localStorage</code> or <code>sessionStorage</code>) you wish to manipulate.</li>
<li><code>key</code> is the first argument accepted by <code>setItem()</code>. It is a required string argument representing the name of the web storage property you want to create or update.</li>
<li><code>value</code> is the second argument accepted by <code>setItem()</code>. It is a required string argument specifying the value of the <code>key</code> you are creating or updating.</li>
</ul>
<p><strong>Note:</strong></p>
<ul>
<li>The <code>key</code> and <code>value</code> arguments are always strings.</li>
<li>Suppose you provide an integer as a <code>key</code> or <code>value</code>. In that case, browsers will convert them to strings automatically.</li>
<li><code>setItem()</code> may display an error message if the storage object is full.</li>
</ul>
<h4 id="heading-example-1-how-to-store-data-in-the-session-storage-object">Example 1: How to store data in the session storage object</h4>
<ol>
<li>Invoke <code>sessionStorage</code>’s <code>setItem()</code> method.</li>
<li>Provide the name and value of the data you wish to store.</li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// Store color: "Pink" inside the browser's session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"color"</span>, <span class="hljs-string">"Pink"</span>);

<span class="hljs-comment">// Log the session storage object to the console:</span>
<span class="hljs-built_in">console</span>.log(sessionStorage);

<span class="hljs-comment">// The invocation above will return:</span>
{<span class="hljs-attr">color</span>: <span class="hljs-string">"Pink"</span>}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/setitem/js-25hgkp"><strong>Try Editing It</strong></a></p>
<p><strong>Note:</strong> Your browser’s session storage may contain additional data if it already uses the storage object to store information.</p>
<h4 id="heading-example-2-how-to-store-data-in-the-local-storage-object">Example 2: How to store data in the local storage object</h4>
<ol>
<li>Invoke <code>localStorage</code>’s <code>setItem()</code> method.</li>
<li>Provide the name and value of the data you wish to store.</li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// Store color: "Pink" inside the browser's local storage object:</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"color"</span>, <span class="hljs-string">"Pink"</span>);

<span class="hljs-comment">// Log the local storage object to the console:</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">localStorage</span>);

<span class="hljs-comment">// The invocation above will return:</span>
{<span class="hljs-attr">color</span>: <span class="hljs-string">"Pink"</span>}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/setitem/js-2hluvw"><strong>Try Editing It</strong></a></p>
<p><strong>Note:</strong></p>
<ul>
<li>Your browser’s local storage may contain additional data if it already uses the storage object to store information.</li>
<li>It is best to serialize objects before storing them in local or session storage. Otherwise, the computer will store the object as <code>"[object Object]"</code>.</li>
</ul>
<h4 id="heading-example-3-browsers-use-object-object-for-non-serialized-objects-in-the-web-storage">Example 3: Browsers use <code>"[object Object]"</code> for non-serialized objects in the web storage</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Store myBio object inside the browser's session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"myBio"</span>, { <span class="hljs-attr">name</span>: <span class="hljs-string">"Oluwatobi"</span> });

<span class="hljs-comment">// Log the session storage object to the console:</span>
<span class="hljs-built_in">console</span>.log(sessionStorage);

<span class="hljs-comment">// The invocation above will return:</span>
{<span class="hljs-attr">myBio</span>: <span class="hljs-string">"[object Object]"</span>, <span class="hljs-attr">length</span>: <span class="hljs-number">1</span>}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/setitem/js-n8m7hc"><strong>Try Editing It</strong></a></p>
<p>You can see that the computer stored the object as <code>"[object Object]"</code> because we did not serialize it.</p>
<h4 id="heading-example-4-how-to-store-serialized-objects-in-the-web-storage">Example 4: How to store serialized objects in the web storage</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Store myBio object inside the browser's session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"myBio"</span>, <span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">name</span>: <span class="hljs-string">"Oluwatobi"</span> }));

<span class="hljs-comment">// Log the session storage object to the console:</span>
<span class="hljs-built_in">console</span>.log(sessionStorage);

<span class="hljs-comment">// The invocation above will return:</span>
{<span class="hljs-attr">myBio</span>: <span class="hljs-string">'{"name":"Oluwatobi"}'</span>, <span class="hljs-attr">length</span>: <span class="hljs-number">1</span>}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/setitem/js-edfh43"><strong>Try Editing It</strong></a></p>
<p>We used <code>JSON.stringify()</code> to convert the object to JSON before storing it in the web storage.</p>
<p><strong>Tip:</strong> Learn <a target="_blank" href="https://codesweetly.com/json-explained#how-to-convert-a-json-text-to-a-javascript-object">how to convert JSON to JavaScript objects</a>.</p>
<h3 id="heading-what-is-web-storages-key-method">What is web storage’s <code>key()</code> method?</h3>
<p>The <code>key()</code> method retrieves a specified web storage item’s name (key).</p>
<h4 id="heading-syntax-of-the-key-method">Syntax of the <code>key()</code> method</h4>
<p><code>key()</code> accepts one required argument. Here is the syntax:</p>
<pre><code class="lang-js">webStorageObject.key(index);
</code></pre>
<ul>
<li><code>webStorageObject</code> represents the storage object (<code>localStorage</code> or <code>sessionStorage</code>) whose key you wish to get.</li>
<li><code>index</code> is a required argument. It is an <a target="_blank" href="https://codesweetly.com/web-tech-terms-i#integer">integer</a> specifying the <a target="_blank" href="https://codesweetly.com/web-tech-terms-i#index">index</a> of the item whose key you want to get.</li>
</ul>
<h4 id="heading-example-1-how-to-get-the-name-of-an-item-in-the-session-storage-object">Example 1: How to get the name of an item in the session storage object</h4>
<ol>
<li>Invoke <code>sessionStorage</code>’s <code>key()</code> method.</li>
<li>Provide the index of the item whose name you wish to get.</li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// Store carColor: "Pink" inside the browser's session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"carColor"</span>, <span class="hljs-string">"Pink"</span>);

<span class="hljs-comment">// Store pcColor: "Yellow" inside the session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"pcColor"</span>, <span class="hljs-string">"Yellow"</span>);

<span class="hljs-comment">// Store laptopColor: "White" inside the session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"laptopColor"</span>, <span class="hljs-string">"White"</span>);

<span class="hljs-comment">// Get the name of the item at index 1:</span>
sessionStorage.key(<span class="hljs-number">1</span>);
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/key/js-tptqtg"><strong>Try Editing It</strong></a></p>
<p><strong>Important:</strong> The <a target="_blank" href="https://en.wikipedia.org/wiki/User_agent">user-agent</a> defines the order of items in the session storage. In other words, <code>key()</code>’s output may vary based on how the user-agent orders the web storage’s items. So you shouldn't rely on <code>key()</code> to return a constant value.</p>
<h4 id="heading-example-2-how-to-get-the-name-of-an-item-in-the-local-storage-object">Example 2: How to get the name of an item in the local storage object</h4>
<ol>
<li>Invoke <code>localStorage</code>’s <code>key()</code> method.</li>
<li>Provide the index of the item whose name you wish to get.</li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// Store carColor: "Pink" inside the browser's local storage object:</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"carColor"</span>, <span class="hljs-string">"Pink"</span>);

<span class="hljs-comment">// Store pcColor: "Yellow" inside the local storage object:</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"pcColor"</span>, <span class="hljs-string">"Yellow"</span>);

<span class="hljs-comment">// Store laptopColor: "White" inside the local storage object:</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"laptopColor"</span>, <span class="hljs-string">"White"</span>);

<span class="hljs-comment">// Get the name of the item at index 1:</span>
<span class="hljs-built_in">localStorage</span>.key(<span class="hljs-number">1</span>);
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/key/js-tclrbd"><strong>Try Editing It</strong></a></p>
<p><strong>Important:</strong> The user-agent defines the order of items in the local storage. In other words, <code>key()</code>’s output may vary based on how the user-agent orders the web storage’s items. So you shouldn't rely on <code>key()</code> to return a constant value.</p>
<h3 id="heading-what-is-web-storages-getitem-method">What is web storage’s <code>getItem()</code> method?</h3>
<p>The <code>getItem()</code> method retrieves the value of a specified web storage item.</p>
<h4 id="heading-syntax-of-the-getitem-method">Syntax of the <code>getItem()</code> method</h4>
<p><code>getItem()</code> accepts one required argument. Here is the syntax:</p>
<pre><code class="lang-js">webStorageObject.getItem(key);
</code></pre>
<ul>
<li><code>webStorageObject</code> represents the storage object (<code>localStorage</code> or <code>sessionStorage</code>) whose item you wish to get.</li>
<li><code>key</code> is a required argument. It is a <a target="_blank" href="https://codesweetly.com/javascript-primitive-data-type#string-primitive-data-type">string</a> specifying the name of the web storage <a target="_blank" href="https://codesweetly.com/javascript-properties-object#syntax-of-a-javascript-object">property</a> whose value you want to get.</li>
</ul>
<h4 id="heading-example-1-how-to-get-data-from-the-session-storage-object">Example 1: How to get data from the session storage object</h4>
<ol>
<li>Invoke <code>sessionStorage</code>’s <code>getItem()</code> method.</li>
<li>Provide the name of the data you wish to get.</li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// Store color: "Pink" inside the browser's session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"color"</span>, <span class="hljs-string">"Pink"</span>);

<span class="hljs-comment">// Get color's value from the session storage:</span>
sessionStorage.getItem(<span class="hljs-string">"color"</span>);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Pink"</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/getitem/js-xk9auv"><strong>Try Editing It</strong></a></p>
<h4 id="heading-example-2-how-to-get-data-from-the-local-storage-object">Example 2: How to get data from the local storage object</h4>
<ol>
<li>Invoke <code>localStorage</code>’s <code>getItem()</code> method.</li>
<li>Provide the name of the data you wish to get.</li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// Store color: "Pink" inside the browser's local storage object:</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"color"</span>, <span class="hljs-string">"Pink"</span>);

<span class="hljs-comment">// Get color's value from the local storage:</span>
<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"color"</span>);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Pink"</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/getitem/js-terw5e"><strong>Try Editing It</strong></a></p>
<p><strong>Note:</strong> The <code>getItem()</code> method will return <code>null</code> if its argument does not exist in the specified web storage.</p>
<h3 id="heading-what-is-web-storages-length-property">What is web storage’s <code>length</code> property?</h3>
<p>The <code>length</code> property returns the number of <a target="_blank" href="https://codesweetly.com/javascript-properties-object#syntax-of-a-javascript-object">properties</a> in the specified web storage.</p>
<h4 id="heading-syntax-of-the-length-property">Syntax of the <code>length</code> property</h4>
<p>Here is <code>length</code>’s syntax:</p>
<pre><code class="lang-js">webStorageObject.length;
</code></pre>
<p><code>webStorageObject</code> represents the storage object (<code>localStorage</code> or <code>sessionStorage</code>) whose length you wish to verify.</p>
<h4 id="heading-example-1-how-to-verify-the-number-of-items-in-the-session-storage-object">Example 1: How to verify the number of items in the session storage object</h4>
<p>Invoke <code>sessionStorage</code>’s <code>length</code> property.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Store carColor: "Pink" inside the browser's session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"carColor"</span>, <span class="hljs-string">"Pink"</span>);

<span class="hljs-comment">// Store pcColor: "Yellow" inside the session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"pcColor"</span>, <span class="hljs-string">"Yellow"</span>);

<span class="hljs-comment">// Store laptopColor: "White" inside the session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"laptopColor"</span>, <span class="hljs-string">"White"</span>);

<span class="hljs-comment">// Verify the number of items in the session storage:</span>
sessionStorage.length;

<span class="hljs-comment">// The invocation above may return:</span>
<span class="hljs-number">3</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/length/js-zasgst"><strong>Try Editing It</strong></a></p>
<p><strong>Note:</strong> Your <code>sessionStorage.length</code> invocation may return a value greater than <code>3</code> if your browser’s session storage already contains some stored information.</p>
<h4 id="heading-example-2-how-to-verify-the-number-of-items-in-the-local-storage-object">Example 2: How to verify the number of items in the local storage object</h4>
<p>Invoke <code>localStorage</code>’s <code>length</code> property.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Store carColor: "Pink" inside the browser's local storage object:</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"carColor"</span>, <span class="hljs-string">"Pink"</span>);

<span class="hljs-comment">// Store pcColor: "Yellow" inside the local storage object:</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"pcColor"</span>, <span class="hljs-string">"Yellow"</span>);

<span class="hljs-comment">// Store laptopColor: "White" inside the local storage object:</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"laptopColor"</span>, <span class="hljs-string">"White"</span>);

<span class="hljs-comment">// Verify the number of items in the local storage:</span>
<span class="hljs-built_in">localStorage</span>.length;

<span class="hljs-comment">// The invocation above may return:</span>
<span class="hljs-number">3</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/length/js-3f6lac"><strong>Try Editing It</strong></a></p>
<p><strong>Note:</strong> Your <code>localStorage.length</code> invocation may return a value greater than <code>3</code> if your browser's local storage already contains some stored information.</p>
<h3 id="heading-what-is-web-storages-removeitem-method">What is web storage’s <code>removeItem()</code> method?</h3>
<p>The <code>removeItem()</code> method removes a property from the specified web storage.</p>
<h4 id="heading-syntax-of-the-removeitem-method">Syntax of the <code>removeItem()</code> Method</h4>
<p><code>removeItem()</code> accepts one required argument. Here is the syntax:</p>
<pre><code class="lang-js">webStorageObject.removeItem(key);
</code></pre>
<ul>
<li><code>webStorageObject</code> represents the storage object (<code>localStorage</code> or <code>sessionStorage</code>) whose item you wish to remove.</li>
<li><code>key</code> is a required argument. It is a string specifying the name of the web storage property you want to remove.</li>
</ul>
<h4 id="heading-example-1-how-to-remove-data-from-the-session-storage-object">Example 1: How to remove data from the session storage object</h4>
<ol>
<li>Invoke <code>sessionStorage</code>’s <code>removeItem()</code> method.</li>
<li>Provide the name of the data you wish to remove.</li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// Store carColor: "Pink" inside the browser's session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"carColor"</span>, <span class="hljs-string">"Pink"</span>);

<span class="hljs-comment">// Store pcColor: "Yellow" inside the session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"pcColor"</span>, <span class="hljs-string">"Yellow"</span>);

<span class="hljs-comment">// Store laptopColor: "White" inside the session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"laptopColor"</span>, <span class="hljs-string">"White"</span>);

<span class="hljs-comment">// Remove the pcColor item from the session storage:</span>
sessionStorage.removeItem(<span class="hljs-string">"pcColor"</span>);

<span class="hljs-comment">// Confirm whether the pcColor item still exists in the session storage:</span>
sessionStorage.getItem(<span class="hljs-string">"pcColor"</span>);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-literal">null</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/removeitem/js-1mywnh"><strong>Try Editing It</strong></a></p>
<p><strong>Note:</strong> The <code>removeItem()</code> method will do nothing if its argument does not exist in the session storage.</p>
<h4 id="heading-example-2-how-to-remove-data-from-the-local-storage-object">Example 2: How to remove data from the local storage object</h4>
<ol>
<li>Invoke <code>localStorage</code>’s <code>removeItem()</code> method.</li>
<li>Provide the name of the data you wish to remove.</li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// Store carColor: "Pink" inside the browser's local storage object:</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"carColor"</span>, <span class="hljs-string">"Pink"</span>);

<span class="hljs-comment">// Store pcColor: "Yellow" inside the local storage object:</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"pcColor"</span>, <span class="hljs-string">"Yellow"</span>);

<span class="hljs-comment">// Store laptopColor: "White" inside the local storage object:</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"laptopColor"</span>, <span class="hljs-string">"White"</span>);

<span class="hljs-comment">// Remove the pcColor item from the local storage:</span>
<span class="hljs-built_in">localStorage</span>.removeItem(<span class="hljs-string">"pcColor"</span>);

<span class="hljs-comment">// Confirm whether the pcColor item still exists in the local storage:</span>
<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"pcColor"</span>);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-literal">null</span>
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/removeitem/js-8doou3"><strong>Try Editing It</strong></a></p>
<p><strong>Note:</strong> The <code>removeItem()</code> method will do nothing if its argument does not exist in the local storage.</p>
<h3 id="heading-what-is-web-storages-clear-method">What is web storage’s <code>clear()</code> method?</h3>
<p>The <code>clear()</code> method clears (deletes) all the items in the specified web storage.</p>
<h4 id="heading-syntax-of-the-clear-method">Syntax of the <code>clear()</code> Method</h4>
<p><code>clear()</code> accepts no argument. Here is the syntax:</p>
<pre><code class="lang-js">webStorageObject.clear();
</code></pre>
<p><code>webStorageObject</code> represents the storage object (<code>localStorage</code> or <code>sessionStorage</code>) whose items you wish to clear.</p>
<h4 id="heading-example-1-how-to-clear-all-items-from-the-session-storage-object">Example 1: How to clear all items from the session storage object</h4>
<p>Invoke <code>sessionStorage</code>’s <code>clear()</code> method.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Store carColor: "Pink" inside the browser's session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"carColor"</span>, <span class="hljs-string">"Pink"</span>);

<span class="hljs-comment">// Store pcColor: "Yellow" inside the session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"pcColor"</span>, <span class="hljs-string">"Yellow"</span>);

<span class="hljs-comment">// Store laptopColor: "White" inside the session storage object:</span>
sessionStorage.setItem(<span class="hljs-string">"laptopColor"</span>, <span class="hljs-string">"White"</span>);

<span class="hljs-comment">// Clear all items from the session storage:</span>
sessionStorage.clear();

<span class="hljs-comment">// Confirm whether the session storage still contains any item:</span>
<span class="hljs-built_in">console</span>.log(sessionStorage);

<span class="hljs-comment">// The invocation above will return:</span>
{<span class="hljs-attr">length</span>: <span class="hljs-number">0</span>}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/clear/js-an86yu"><strong>Try Editing It</strong></a></p>
<h4 id="heading-example-2-how-to-clear-all-items-from-the-local-storage-object">Example 2: How to clear all items from the local storage object</h4>
<p>Invoke <code>localStorage</code>’s <code>clear()</code> method.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Store carColor: "Pink" inside the browser's local storage object:</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"carColor"</span>, <span class="hljs-string">"Pink"</span>);

<span class="hljs-comment">// Store pcColor: "Yellow" inside the local storage object:</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"pcColor"</span>, <span class="hljs-string">"Yellow"</span>);

<span class="hljs-comment">// Store laptopColor: "White" inside the local storage object:</span>
<span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"laptopColor"</span>, <span class="hljs-string">"White"</span>);

<span class="hljs-comment">// Clear all items from the local storage:</span>
<span class="hljs-built_in">localStorage</span>.clear();

<span class="hljs-comment">// Confirm whether the local storage still contains any item:</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">localStorage</span>);

<span class="hljs-comment">// The invocation above will return:</span>
{<span class="hljs-attr">length</span>: <span class="hljs-number">0</span>}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/clear/js-w5vyem"><strong>Try Editing It</strong></a></p>
<p>Now that we know what web storage is and how to access it, we can practice using it in a JavaScript project.</p>
<h2 id="heading-time-to-practice-with-web-storage">Time to Practice with Web Storage 🤸‍♂️🏋️‍♀️</h2>
<p>Consider the following To-Do List app:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/78MRup0PN7c" 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>
<h3 id="heading-the-problem">The Problem</h3>
<p>The issue with the <a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/to-do-app/js-mgl6ie">To-Do List app</a> is this:</p>
<ul>
<li>Tasks disappear whenever users refresh the webpage.</li>
</ul>
<h3 id="heading-your-exercise">Your Exercise</h3>
<p>Use the appropriate Web Storage APIs to accomplish the following tasks:</p>
<ol>
<li>Prevent the Session pane’s To-Do items from disappearing whenever users reload the browser.</li>
<li>Prevent the Local section’s To-Do items from disappearing whenever users reload or close their browser tab (or window).</li>
<li>Auto-display the Session section's previously added tasks on page reload.</li>
<li>Auto-display the Local section's previously added tasks on page reload (or browser reopen).</li>
</ol>
<h3 id="heading-bonus-exercise">Bonus Exercise</h3>
<p>Use your browser’s console to:</p>
<ol>
<li>Check the number of items in your browser’s session storage object.</li>
<li>Display the name of your local storage’s zeroth index item.</li>
<li>Delete all the items in your browser’s session storage.</li>
</ol>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/to-do-app/js-mgl6ie"><strong>Try the Web Storage Exercise</strong></a></p>
<p><strong>Note:</strong> You will benefit much more from this tutorial if you attempt the exercise yourself.</p>
<p>If you get stuck, don’t be discouraged. Instead, review the lesson and give it another try.</p>
<p>Once you’ve given it your best shot (you’ll only cheat yourself if you don’t!), we can discuss how I approached the exercise below.</p>
<h2 id="heading-how-did-you-go-about-solving-the-web-storage-exercise">How Did You Go About Solving the Web Storage Exercise?</h2>
<p>Below are feasible ways to get the exercise done.</p>
<h3 id="heading-how-to-prevent-the-session-storage-panes-to-do-items-from-disappearing-on-page-reload">How to prevent the Session Storage pane’s To-Do items from disappearing on page reload</h3>
<p>Whenever users click the “Add task” button,</p>
<ol>
<li>Get existing session storage’s content, if any. Otherwise, return an empty array.</li>
<li>Merge the existing to-do items with the user’s new input.</li>
<li>Add the new to-do list to the browser’s session storage object.</li>
</ol>
<p><strong>Here’s the code:</strong></p>
<pre><code class="lang-js">sessionAddTaskBtn.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// Get existing session storage's content, if any. Otherwise, return an empty array:</span>
  <span class="hljs-keyword">const</span> currentTodoArray =
    <span class="hljs-built_in">JSON</span>.parse(sessionStorage.getItem(<span class="hljs-string">'codesweetlyStore'</span>)) || [];

  <span class="hljs-comment">// Merge currentTodoArray with the user's new input:</span>
  <span class="hljs-keyword">const</span> newTodoArray = [
    ...currentTodoArray,
    { <span class="hljs-attr">checked</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">text</span>: sessionInputEle.value },
  ];

  <span class="hljs-comment">// Add newTodoArray to the session storage object:</span>
  sessionStorage.setItem(<span class="hljs-string">'codesweetlyStore'</span>, <span class="hljs-built_in">JSON</span>.stringify(newTodoArray));

  <span class="hljs-keyword">const</span> todoLiElements = createTodoLiElements(newTodoArray);
  sessionTodosContainer.replaceChildren(...todoLiElements);
  sessionInputEle.value = <span class="hljs-string">''</span>;
});
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/to-do-app/js-txyt66"><strong>Try Editing It</strong></a></p>
<p><strong>Note:</strong> The three dots (<code>...</code>) preceding the <code>currentTodoArray</code> variable represent the <a target="_blank" href="https://codesweetly.com/spread-operator">spread operator</a>. We used it in the <code>newTodoArray</code> object to copy <code>currentTodoArray</code>’s items into <code>newTodoArray</code>.</p>
<h3 id="heading-how-to-prevent-the-local-storage-panes-to-do-items-from-disappearing-on-page-reload-or-reopen">How to prevent the Local Storage pane’s To-Do items from disappearing on page reload or reopen</h3>
<ol>
<li>Get existing local storage’s content, if any. Otherwise, return an empty array.</li>
<li>Merge the existing to-do items with the user’s new input.</li>
<li>Add the new to-do list to the browser’s local storage object.</li>
</ol>
<p><strong>Here’s the code:</strong></p>
<pre><code class="lang-js">localAddTaskBtn.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// Get existing local storage's content, if any. Otherwise, return an empty array:</span>
  <span class="hljs-keyword">const</span> currentTodoArray =
    <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'codesweetlyStore'</span>)) || [];

  <span class="hljs-comment">// Merge currentTodoArray with the user's new input:</span>
  <span class="hljs-keyword">const</span> newTodoArray = [
    ...currentTodoArray,
    { <span class="hljs-attr">checked</span>: <span class="hljs-literal">false</span>, <span class="hljs-attr">text</span>: localInputEle.value },
  ];

  <span class="hljs-comment">// Add newTodoArray to the local storage object:</span>
  sessionStorage.setItem(<span class="hljs-string">'codesweetlyStore'</span>, <span class="hljs-built_in">JSON</span>.stringify(newTodoArray));

  <span class="hljs-keyword">const</span> todoLiElements = createTodoLiElements(newTodoArray);
  localTodosContainer.replaceChildren(...todoLiElements);
  localInputEle.value = <span class="hljs-string">''</span>;
});
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/to-do-app/js-dpuffp"><strong>Try Editing It</strong></a></p>
<p><strong>Note:</strong> The <code>localTodosContainer.replaceChildren(...todoLiElements)</code> statement tells the browser to replace <code>localTodosContainer</code>’s current children elements with the list of <code>&lt;li&gt;</code>s in the <code>todoLiElements</code> array.</p>
<h3 id="heading-how-to-auto-display-the-session-sections-previously-added-tasks-on-page-reload">How to auto-display the Session section’s previously added tasks on page reload</h3>
<p>Whenever users reload the page,</p>
<ol>
<li>Get existing session storage’s content, if any. Otherwise, return an empty array.</li>
<li>Use the retrieved content to create <code>&lt;li&gt;</code> elements.</li>
<li>Populate the tasks display space with the <code>&lt;li&gt;</code> elements.</li>
</ol>
<p><strong>Here’s the code:</strong></p>
<pre><code class="lang-js"><span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// Get existing session storage's content, if any. Otherwise, return an empty array:</span>
  <span class="hljs-keyword">const</span> sessionTodoArray =
    <span class="hljs-built_in">JSON</span>.parse(sessionStorage.getItem(<span class="hljs-string">'codesweetlyStore'</span>)) || [];

  <span class="hljs-comment">// Use the retrieved sessionTodoArray to create &lt;li&gt; elements:</span>
  <span class="hljs-keyword">const</span> todoLiElements = createTodoLiElements(sessionTodoArray);

  <span class="hljs-comment">// Populate the tasks display space with the todoLiElements:</span>
  sessionTodosContainer.replaceChildren(...todoLiElements);
});
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/to-do-app/js-zga551"><strong>Try Editing It</strong></a></p>
<h3 id="heading-how-to-auto-display-the-local-sections-previously-added-tasks-on-page-reload-or-reopen">How to auto-display the Local section’s previously added tasks on page reload or reopen</h3>
<p>Whenever users reload or reopen the page,</p>
<ol>
<li>Get existing local storage’s content, if any. Otherwise, return an empty array.</li>
<li>Use the retrieved content to create <code>&lt;li&gt;</code> elements.</li>
<li>Populate the tasks display space with the <code>&lt;li&gt;</code> elements.</li>
</ol>
<p><strong>Here’s the code:</strong></p>
<pre><code class="lang-js"><span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// Get existing local storage's content, if any. Otherwise, return an empty array:</span>
  <span class="hljs-keyword">const</span> localTodoArray =
    <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'codesweetlyStore'</span>)) || [];

  <span class="hljs-comment">// Use the retrieved localTodoArray to create &lt;li&gt; elements:</span>
  <span class="hljs-keyword">const</span> todoLiElements = createTodoLiElements(localTodoArray);

  <span class="hljs-comment">// Populate the tasks display space with the todoLiElements:</span>
  localTodosContainer.replaceChildren(...todoLiElements);
});
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/to-do-app/js-srmnst"><strong>Try Editing It</strong></a></p>
<h3 id="heading-how-to-check-the-total-items-in-the-browsers-session-storage">How to check the total items in the browser’s session storage</h3>
<p>Use session storage’s <code>length</code> property like so:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(sessionStorage.length);
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/to-do-app/js-m4pmhf"><strong>Try Editing It</strong></a></p>
<h3 id="heading-how-to-display-the-local-storages-zeroth-index-items-name">How to display the local storage’s zeroth index item’s name</h3>
<p>Use the local storage’s <code>key()</code> method as follows:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">localStorage</span>.key(<span class="hljs-number">0</span>));
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/to-do-app/js-th8xr7"><strong>Try Editing It</strong></a></p>
<h3 id="heading-how-to-empty-the-browsers-session-storage">How to empty the browser’s session storage</h3>
<p>Use the session storage’s <code>clear()</code> method as follows:</p>
<pre><code class="lang-js">sessionStorage.clear();
</code></pre>
<h2 id="heading-how-to-continue-practicing-with-web-storage">How to Continue Practicing with Web Storage 🧗‍♀️🚀</h2>
<p>The to-do app still has a lot of potential. For instance, you can:</p>
<ul>
<li>Convert it to a React TypeScript application.</li>
<li>Make it keyboard accessible.</li>
<li>Allow users to delete or edit individual tasks.</li>
<li>Allow users to star (mark as important) specific tasks.</li>
<li>Let users specify due dates.</li>
</ul>
<p>So, feel free to continue developing what we’ve built in this tutorial so you can better understand the web storage objects.</p>
<p>For instance, here’s my attempt at <a target="_blank" href="https://codesweetly.com/try-it-sdk/javascript/web-storage-apis/to-do-app/js-ax8tvk">making the two panes functional</a>:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/gDiU-ubWPD4" 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>Before we wrap up our discussion, you should know some differences between web storage and cookies. So, let’s talk about that below.</p>
<h2 id="heading-web-storage-vs-cookies-what-is-the-difference">Web Storage vs. Cookies: What is the Difference?</h2>
<p>Web storage and cookies are two main ways to store data locally within a user’s browser. But they work differently. Below are the main distinctions between them.</p>
<h3 id="heading-storage-limit">Storage limit</h3>
<p><strong>Cookies:</strong> Have 4 kilobytes maximum <a target="_blank" href="https://docs.devexpress.com/AspNet/11912/common-concepts/cookies-support#browser-limitations">storage limit</a>.</p>
<p><strong>Web storage:</strong> Can store a lot more than 4 kilobytes of data. For instance, Safari 8 can store up to 5 MB, while Firefox 34 permits 10 MB.</p>
<h3 id="heading-data-transfer-to-the-server">Data transfer to the server</h3>
<p><strong>Cookies:</strong> Transfer data to the server whenever browsers send HTTP requests to the web server.</p>
<p><strong>Web storage:</strong> Never transfers data to the server.</p>
<p><strong>Note:</strong> It is a waste of users’ bandwidth to send data to the server if such information is needed only by the client (browser), not the server.</p>
<h3 id="heading-weak-integrity-and-confidentiality">Weak integrity and confidentiality</h3>
<p><strong>Cookies:</strong> Suffer from <a target="_blank" href="https://datatracker.ietf.org/doc/html/rfc6265#section-8.6">weak integrity</a> and <a target="_blank" href="https://datatracker.ietf.org/doc/html/rfc6265#section-8.5">weak confidentiality</a> issues.</p>
<p><strong>Web storage:</strong> Do not suffer from weak integrity and confidentiality issues because it stores data per <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Origin">origin</a>.</p>
<h3 id="heading-property">Property</h3>
<p><strong>Cookies:</strong> Cookies are a property of the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Document"><code>Document</code></a> object.</p>
<p><strong>Web storage:</strong> Web storage is a property of the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window"><code>Window</code></a> object.</p>
<h3 id="heading-expiration">Expiration</h3>
<p><strong>Cookie:</strong> You can specify a cookie’s expiration date.</p>
<p><strong>Web storage:</strong> Browsers determine web storage’s expiration date.</p>
<h3 id="heading-retrieving-individual-data">Retrieving individual data</h3>
<p><strong>Cookies:</strong> There’s no way to retrieve individual data. You always have to recall all the data to read any single one.</p>
<p><strong>Web storage:</strong> You can choose the specific data you wish to retrieve.</p>
<h3 id="heading-the-syntax-for-storing-data">The syntax for storing data</h3>
<p><strong>Cookies:</strong></p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">"key=value"</span>;
</code></pre>
<p><strong>Web storage:</strong></p>
<pre><code class="lang-js">webStorageObject.setItem(key, value);
</code></pre>
<h3 id="heading-the-syntax-for-reading-data">The syntax for reading data</h3>
<p><strong>Cookies:</strong></p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.cookie;
</code></pre>
<p><strong>Web storage:</strong></p>
<pre><code class="lang-js">webStorageObject.getItem(key);
</code></pre>
<h3 id="heading-the-syntax-for-removing-data">The syntax for removing data</h3>
<p><strong>Cookies:</strong></p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.cookie = <span class="hljs-string">"key=; expires=Thu, 01 May 1930 00:00:00 UTC"</span>;
</code></pre>
<p>The snippet above deletes the cookie by assigning an empty value to the <code>key</code> property and setting a past expiration date.</p>
<p><strong>Web storage:</strong></p>
<pre><code class="lang-js">webStorageObject.removeItem(key);
</code></pre>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>In this article, we discussed how to use web storage and its built-in interfaces. We also used a to-do list project to practice using the local and session storage objects to store data locally and securely within users’ browsers.</p>
<p>Thanks for reading!</p>
<h3 id="heading-and-heres-a-useful-react-typescript-resource">And here’s a useful React TypeScript resource:</h3>
<p>I wrote a book about <a target="_blank" href="https://amzn.to/3Pa4bI4">Creating NPM Packages</a>!</p>
<p>It is a beginner-friendly book that takes you from zero to creating, testing, and publishing NPM packages like a pro.</p>
<p><a target="_blank" href="https://amzn.to/3Pa4bI4"><img src="https://www.freecodecamp.org/news/content/images/2023/09/creating-npm-package-banner-codesweetly.png" alt="Creating NPM Package Book Now Available at Amazon" width="600" height="400" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ CSS Transition vs Animation Handbook – How to Animate Elements in CSS ]]>
                </title>
                <description>
                    <![CDATA[ CSS transitions and animations provide smooth, gradual ways to change an element's style. But they work in different ways. Here are the main distinctions between them:                         ]]>
                </description>
                <link>https://www.freecodecamp.org/news/css-transition-vs-css-animation-handbook/</link>
                <guid isPermaLink="false">66ba0dea79b7f411df58de98</guid>
                
                    <category>
                        <![CDATA[ animation ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ transitions ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Tue, 12 Sep 2023 00:20:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/How-to-Animate-Elements-in-CSS-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>CSS transitions and animations provide smooth, gradual ways to change an element's style. But they work in different ways.</p>
<p>Here are the main distinctions between them:</p>
<table>
    <thead>
        <tr>
            <th>CSS Transition</th>
            <th>CSS Animation</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <ul>
                    <li>
                        Creates smooth transitions from one CSS value to another.
                    </li>
                    <li>
                        You need triggers to run CSS transitions. For instance, you can use the <code>:hover</code> <a href="https://codesweetly.com/css-pseudo-selectors">pseudo-class</a> to run transitions when a user's pointer hovers over an element.
                    </li>
                    <li>
                        Transition has only two states: an initial and a final state. You cannot create intermediate steps.
                    </li>
                    <li>Runs only once.</li>
                    <li>Best used for basic style changes.</li>
                </ul>
            </td>
            <td>
                <ul>
                    <li>
                        Animates the style change from one CSS keyframe to another.
                    </li>
                    <li>CSS animations do not need triggers.</li>
                    <li>Animation allows you to create multiple states.</li>
                    <li>
                        You can run multiple animation iterations—even to infinity.
                    </li>
                    <li>Best used for dynamic style changes.</li>
                </ul>
            </td>
        </tr>
    </tbody>
</table>

<p>This handbook uses examples to explain the two animating techniques 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-are-css-transitions">What Are CSS Transitions?</a></li>
<li><a class="post-section-overview" href="#heading-categories-of-css-transition-properties">Categories of CSS Transition Properties</a><ul>
<li><a class="post-section-overview" href="#heading-what-are-the-required-css-transition-properties">What Are the Required CSS Transition Properties?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-css-transition-property">What is the CSS <code>transition-property</code>?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-css-transition-duration-property">What is the CSS <code>transition-duration</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-examples-of-the-required-css-transition-properties">Examples of the Required CSS Transition Properties</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-optional-css-transition-properties">What Are the Optional CSS Transition Properties?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-css-transition-timing-function-property">What is the CSS <code>transition-timing-function</code> Property?</a></li>
<li><a class="post-section-overview" href="#what-is-a-css-transition-delay-property">What is the CSS <code>transition-delay</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-examples-of-the-optional-css-transition-properties">Examples of the Optional CSS Transition Properties</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-shorthand-for-defining-the-css-transition-properties">Shorthand for Defining the CSS Transition Properties</a></li>
<li><a class="post-section-overview" href="#heading-what-is-css-animation">What is CSS Animation?</a><ul>
<li><a class="post-section-overview" href="#heading-components-of-css-animations">Components of CSS Animations</a></li>
<li><a class="post-section-overview" href="#heading-what-are-css-keyframes">What are CSS @keyframes?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#heading-what-are-css-animation-properties">What Are CSS Animation Properties?</a><ul>
<li><a class="post-section-overview" href="#heading-what-is-the-css-animation-name-property">What is the CSS <code>animation-name</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-css-animation-duration-property">What is the CSS <code>animation-duration</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-css-animation-timing-function-property">What is the CSS <code>animation-timing-function</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-css-animation-delay-property">What is the CSS <code>animation-delay</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-css-animation-iteration-count-property">What is the CSS <code>animation-iteration-count</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-css-animation-direction-property">What is the CSS <code>animation-direction</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-css-animation-play-state-property">What is the CSS <code>animation-play-state</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-the-css-animation-fill-mode-property">What is the CSS <code>animation-fill-mode</code> Property?</a></li>
</ul>
</li>
<li><a class="post-section-overview" href="#what-is-a-css-animation-property">What is the CSS <code>animation</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-important-stuff-to-know-about-css-transitions-and-animations">Important Stuff to Know about CSS Transitions and Animations</a></li>
<li><a class="post-section-overview" href="#heading-wrapping-up">Wrapping up</a></li>
</ol>
<p>Without further ado, let's discuss CSS transitions.</p>
<h2 id="heading-what-are-css-transitions">What Are CSS Transitions?</h2>
<p><strong>CSS transitions</strong> provide a smooth and gradual way to change a specific CSS property's value.</p>
<p>So, instead of allowing browsers to change a property's value immediately, CSS transitions cause the change to happen smoothly over a specified period of time.</p>
<p>For instance, suppose you wish to change an element's size on hover. In that case, you have two options:</p>
<ol>
<li>Implement the change without CSS transitions.</li>
<li>Use CSS transitions to transition smoothly from the element's initial size to its new state.</li>
</ol>
<p>Let's see some examples of the two options.</p>
<h3 id="heading-how-to-change-an-images-size-on-mouse-hover-without-using-css-transitions">How to change an image's size on mouse hover without using CSS transitions</h3>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
}

<span class="hljs-selector-tag">img</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-transitions/js-dsymqf"><strong>Try Editing It</strong></a></p>
<p>The code above instantaneously changes the image's size from its initial width (<code>40%</code>) to its new dimension (<code>100%</code>) because we did not use CSS transitions.</p>
<p>With CSS transitions, you will get a much more pleasing experience. Let's see an example below.</p>
<h3 id="heading-how-to-change-an-images-size-on-mouse-hover-with-css-transitions">How to change an image's size on mouse hover with CSS transitions</h3>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
  <span class="hljs-attribute">transition</span>: width <span class="hljs-number">3s</span> ease-out <span class="hljs-number">0.4s</span>;
}

<span class="hljs-selector-tag">img</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-transitions/js-ufwgbu"><strong>Try Editing It</strong></a></p>
<p>The <code>transition</code> property applied a smooth and gradual transition from <code>width: 40%</code> to <code>width: 100%</code> on the image.</p>
<h2 id="heading-categories-of-css-transition-properties">Categories of CSS Transition Properties</h2>
<p>We have two categories of CSS transition properties:</p>
<ul>
<li><em>Required</em> transition properties</li>
<li><em>Optional</em> transition properties</li>
</ul>
<p>Let's discuss the two.</p>
<h3 id="heading-what-are-the-required-css-transition-properties">What Are the Required CSS Transition Properties?</h3>
<p>The two required properties you need to create CSS transitions are:</p>
<ul>
<li><code>transition-property</code></li>
<li><code>transition-duration</code></li>
</ul>
<h4 id="heading-what-is-the-css-transition-property">What is the CSS transition-property?</h4>
<p>The CSS <code>transition-property</code> specifies the CSS property you wish to transition from its initial to its new state.</p>
<h4 id="heading-what-is-the-css-transition-duration-property">What is the CSS transition-duration Property?</h4>
<p>The CSS <code>transition-duration</code> property defines the length of time in which browsers should complete the selected element's transition. In other words, <code>transition-duration</code> sets the total start-to-finish time.</p>
<p><strong>Note the following:</strong></p>
<ul>
<li>The <code>transition-duration</code> property only accepts time in milliseconds (ms) or seconds (s).</li>
<li>Zero seconds (<code>0s</code>) is the <code>transition-duration</code>'s default value. Therefore, no <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Element/transitionend_event">transition event</a> will occur if you do not define a <code>transition-duration</code> property.</li>
<li><code>transition-duration</code> accepts only a zero (<code>0</code>) or a positive numeric value. Browsers will ignore the duration declaration if you provide anything else.</li>
</ul>
<h3 id="heading-examples-of-the-required-css-transition-properties">Examples of the Required CSS Transition Properties</h3>
<p>Below are some examples of the two required CSS transition properties.</p>
<h4 id="heading-how-to-transition-an-elements-width-within-three-seconds">How to transition an element's width within three seconds</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
  <span class="hljs-attribute">transition-property</span>: width;
  <span class="hljs-attribute">transition-duration</span>: <span class="hljs-number">3s</span>;
}

<span class="hljs-selector-tag">img</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-transitions/js-cq27rd"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>transition-property</code> tells browsers to transition the <code>img</code>'s <code>width</code> from its initial value (<code>40%</code>) to its new state (<code>100%</code>).</li>
<li>We used the <code>transition-duration</code> property to define three seconds (<code>3s</code>) duration from the start to the end of the transition.</li>
</ol>
<p>Therefore, instead of an instantaneous change from the image's initial width (<code>40%</code>) to its new size (<code>100%</code>), browsers will transition smoothly between the old and new state in three seconds (<code>3s</code>).</p>
<h4 id="heading-how-to-transition-a-fonts-size-within-five-seconds">How to transition a font's size within five seconds</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1rem</span>;
  <span class="hljs-attribute">transition-property</span>: font-size;
  <span class="hljs-attribute">transition-duration</span>: <span class="hljs-number">5s</span>;
}

<span class="hljs-selector-tag">p</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">7rem</span>;
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-transitions/js-huvkzp"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>transition-property</code> informs browsers to transition the <code>p</code> element's <code>font-size</code>.</li>
<li>We used the <code>transition-duration</code> property to define a five-second (<code>5s</code>) duration from the start to the end of the transition.</li>
</ol>
<p>Therefore, instead of an immediate change from the paragraph's initial font size (<code>1rem</code>) to its new size (<code>7rem</code>), browsers will transition smoothly between the old and new state in five seconds (<code>5s</code>).</p>
<p>Let's now discuss the optional CSS transition properties.</p>
<h3 id="heading-what-are-the-optional-css-transition-properties">What Are the Optional CSS Transition Properties?</h3>
<p>The two optional CSS transition properties are:</p>
<ul>
<li><code>transition-timing-function</code></li>
<li><code>transition-delay</code></li>
</ul>
<h4 id="heading-what-is-the-css-transition-timing-function-property">What is the CSS transition-timing-function Property?</h4>
<p>The CSS <code>transition-timing-function</code> property defines the implementation timing (speed) of the selected element's transition.</p>
<p>In other words, the <code>transition-timing-function</code> specifies the speed for implementing the transition at various intervals of its duration.</p>
<p>The values the <code>transition-timing-function</code> property accepts are:</p>
<ul>
<li><code>ease</code>: Starts the transition slowly. Then, speeds it up and ends it slowly. <code>ease</code> is the <code>transition-timing-function</code> property's default value. It is equivalent to <code>cubic-bezier(0.25,0.1,0.25,1)</code>.</li>
<li><code>ease-in</code>: Starts the transition slowly with a gradual increase in speed. It is equal to <code>cubic-bezier(0.42,0,1,1)</code>.</li>
<li><code>ease-out</code>: Starts fast and ends the transition slowly. It is equivalent to <code>cubic-bezier(0,0,0.58,1)</code>.</li>
<li><code>ease-in-out</code>: Starts and ends the transition slowly. It is equal to <code>cubic-bezier(0.42,0,0.58,1)</code>.</li>
<li><code>linear</code>: Starts and ends the transition using a consistent speed throughout the transition's duration. It is equivalent to <code>cubic-bezier(0,0,1,1)</code>.</li>
<li><code>cubic-bezier(p1, p2, p3, p4)</code>: Allows you to define the values of the <a target="_blank" href="https://www.cssportal.com/css-cubic-bezier-generator/">cubic-bezier curve</a>.</li>
</ul>
<h3 id="heading-what-is-the-css-transition-delay-property">What is the CSS transition-delay Property?</h3>
<p>The CSS <code>transition-delay</code> property defines how long the browser should wait before it starts the transition.</p>
<p><strong>Note the following:</strong></p>
<ul>
<li>The <code>transition-delay</code> property must be in milliseconds (ms) or seconds (s).</li>
<li><code>0s</code> is the <code>transition-delay</code>'s default value. It causes the transition to start immediately from the moment browsers apply it to an HTML element.</li>
<li>A negative value causes the transition to begin immediately from the specified time. For instance, suppose an element's <code>transition-delay</code> value is <code>-3s</code>. In that case, the transition will start immediately at 3 seconds.</li>
<li>A positive value causes the transition to begin after the specified delay time has elapsed. For instance, suppose an element's <code>transition-delay</code> value is <code>3s</code>. In that case, the transition will start after a 3-second delay.</li>
</ul>
<h3 id="heading-examples-of-the-optional-css-transition-properties">Examples of the Optional CSS Transition Properties</h3>
<p>Below are some examples of the two optional CSS transition properties.</p>
<h4 id="heading-how-to-transition-an-elements-width-with-an-ease-out-speed">How to transition an element's width with an ease-out speed</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
  <span class="hljs-attribute">transition-property</span>: width;
  <span class="hljs-attribute">transition-duration</span>: <span class="hljs-number">3s</span>;
  <span class="hljs-attribute">transition-timing-function</span>: ease-out;
}

<span class="hljs-selector-tag">img</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-transitions/js-tqzgmf"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>transition-property</code> informs browsers to transition the <code>img</code> element's width.</li>
<li>We used the <code>transition-duration</code> property to define three seconds (<code>3s</code>) duration from the start to the end of the transition.</li>
<li>We used the <code>transition-timing-function</code> property to begin the transition quickly and end it slowly.</li>
</ol>
<h4 id="heading-how-to-transition-an-elements-width-with-a-linear-speed">How to transition an element's width with a linear speed</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
  <span class="hljs-attribute">transition-property</span>: width;
  <span class="hljs-attribute">transition-duration</span>: <span class="hljs-number">3s</span>;
  <span class="hljs-attribute">transition-timing-function</span>: linear;
}

<span class="hljs-selector-tag">img</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-transitions/js-1gqwai"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>transition-property</code> informs browsers to transition the <code>img</code> element's width.</li>
<li>We used the <code>transition-duration</code> property to define three seconds (<code>3s</code>) duration from the start to the end of the transition.</li>
<li>The <code>transition-timing-function</code> property tells browsers to transition from the element's initial width to its new size using a consistent transition speed throughout.</li>
</ol>
<h4 id="heading-how-to-transition-an-elements-width-with-a-two-second-delay">How to transition an element's width with a two-second delay</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
  <span class="hljs-attribute">transition-property</span>: width;
  <span class="hljs-attribute">transition-duration</span>: <span class="hljs-number">3s</span>;
  <span class="hljs-attribute">transition-timing-function</span>: linear;
  <span class="hljs-attribute">transition-delay</span>: <span class="hljs-number">2s</span>;
}

<span class="hljs-selector-tag">img</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-transitions/js-ejjufi"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>transition-property</code> informs browsers to transition the <code>img</code> element's <code>width</code> property.</li>
<li>We used the <code>transition-duration</code> property to define three seconds (<code>3s</code>) duration from the start to the end of the transition.</li>
<li>The <code>transition-timing-function</code> property transitions the <code>img</code> element's width using a consistent transition speed.</li>
<li>We used the <code>transition-delay</code> property to apply a two-second (<code>2s</code>) delay to the starting time of the transition.</li>
</ol>
<p>Now that we know the CSS transition properties, we can discuss defining them with a shorthand syntax.</p>
<h2 id="heading-shorthand-for-defining-the-css-transition-properties">Shorthand for Defining the CSS Transition Properties</h2>
<p>We use the <code>transition</code> property as shorthand for the <code>transition-property</code>, <code>transition-duration</code>, <code>transition-timing-function</code>, and <code>transition-delay</code> properties.</p>
<p>In other words, instead of writing:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transition-property</span>: width;
  <span class="hljs-attribute">transition-duration</span>: <span class="hljs-number">3s</span>;
  <span class="hljs-attribute">transition-timing-function</span>: linear;
  <span class="hljs-attribute">transition-delay</span>: <span class="hljs-number">2s</span>;
}
</code></pre>
<p>You can alternatively use the <code>transition</code> property to shorten your code like so:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transition</span>: width <span class="hljs-number">3s</span> linear <span class="hljs-number">2s</span>;
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-transitions/js-vtvbpo"><strong>Try Editing It</strong></a></p>
<p>Here is the <code>transition</code> property's syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">transition</span>: &lt;<span class="hljs-selector-tag">property-name</span>&gt; &lt;<span class="hljs-selector-tag">duration</span>&gt; &lt;<span class="hljs-selector-tag">timing-function</span>&gt; &lt;<span class="hljs-selector-tag">delay</span>&gt;;
</code></pre>
<p>Note that you can use the <code>transition</code> property to transition the state of multiple CSS properties.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
  <span class="hljs-attribute">opacity</span>: <span class="hljs-number">0.4</span>;
  <span class="hljs-attribute">transition</span>: width <span class="hljs-number">3s</span> linear, opacity <span class="hljs-number">4s</span> ease-out, transform <span class="hljs-number">5s</span>;
}

<span class="hljs-selector-tag">img</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">opacity</span>: <span class="hljs-number">1</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotate</span>(<span class="hljs-number">45deg</span>);
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-transitions/js-ajygzm"><strong>Try Editing It</strong></a></p>
<p>The snippet above used commas (<code>,</code>) to separate each of the transitional properties we are applying to the <code>img</code> element.</p>
<p>So, now that we know what CSS transitions are and how they work, we can discuss CSS animations.</p>
<h2 id="heading-what-is-css-animation">What is CSS Animation?</h2>
<p><strong>CSS animations</strong> provide a smooth and gradual way to animate an element's style changes from one keyframe to another.</p>
<h3 id="heading-components-of-css-animations">Components of CSS Animations</h3>
<p>CSS animations consist of two components:</p>
<ol>
<li>Keyframes</li>
<li>Animation properties</li>
</ol>
<h3 id="heading-what-are-css-keyframes">What are CSS @keyframes?</h3>
<p><strong>@keyframes</strong> define the styles you want browsers to apply smoothly to an element at some specified key moments (frames).</p>
<h3 id="heading-syntax-of-css-keyframes">Syntax of CSS @keyframes</h3>
<p>A CSS @keyframes <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule">at-rule</a> consists of the following:</p>
<ol>
<li>An <code>@keyframes</code> keyword</li>
<li>The <code>@keyframes</code>' name</li>
<li>A block of zero or more keyframes</li>
<li>The animation's key moment selector</li>
<li>The key moment's style declarations</li>
</ol>
<p><strong>Here's an illustration:</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/09/css-animation-keyframes-illustration-codesweetly.png" alt="Anatomy of CSS @keyframes at-rule" width="600" height="400" loading="lazy">
<em>A CSS @keyframes at-rule consists of a keyword, a name, and a block of keyframes</em></p>
<h3 id="heading-examples-of-css-keyframes">Examples of CSS @keyframes</h3>
<p>Below are examples of the CSS @keyframes.</p>
<h4 id="heading-how-to-define-change-colors-keyframes">How to define <code>change-color</code>'s keyframes</h4>
<pre><code class="lang-css"><span class="hljs-keyword">@keyframes</span> change-color {
  <span class="hljs-comment">/* The first keyframe */</span>
  0% {<span class="hljs-attribute">background-color</span>: purple;}
  <span class="hljs-comment">/* The last keyframe */</span>
  100% {<span class="hljs-attribute">background-color</span>: yellow;}
}
</code></pre>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>We created the <code>@keyframes</code> at-rule named <code>change-color</code>.</li>
<li>We defined a keyframe for browsers to apply when an associated element's animation is at its zero percent (<code>0%</code>) duration.</li>
<li>We defined a keyframe for browsers to apply when an associated element's animation is at its one hundred percent (<code>100%</code>) duration.</li>
</ol>
<p><strong>Note:</strong></p>
<ul>
<li>You can name your <code>@keyframes</code> anything you wish.</li>
<li><code>0%</code> is equivalent to the keyword <code>from</code>. And <code>100%</code> is the same as the keyword <code>to</code>. In other words, the snippet above is equal to the following:</li>
</ul>
<pre><code class="lang-css"><span class="hljs-keyword">@keyframes</span> change-color {
  <span class="hljs-comment">/* The first keyframe */</span>
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">background-color</span>: purple;} 
  <span class="hljs-comment">/* The last keyframe */</span>
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">background-color</span>: yellow;} 
}
</code></pre>
<ul>
<li>An animation's start and end states (<code>from</code> and <code>to</code>) are optional.</li>
<li>Suppose you omit an <code>@keyframes</code>' start (<code>0%</code>) or end (<code>100%</code>) state. In that case, browsers will default to the element's existing styles for either state.</li>
<li>The important rule (<code>!important</code>) does not work in keyframes. Browsers will ignore any keyframe declaration with an <code>!important</code> rule.</li>
</ul>
<p>Let's see another example.</p>
<h4 id="heading-how-to-define-shape-images-keyframes">How to define <code>shape-image</code>'s keyframes</h4>
<pre><code class="lang-css"><span class="hljs-keyword">@keyframes</span> shape-image {
  0% { <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>; <span class="hljs-attribute">border</span>: <span class="hljs-number">5px</span> solid blue;}
  40% { <span class="hljs-attribute">width</span>: <span class="hljs-number">70%</span>; <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid red; <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">50%</span>;}
  75% { <span class="hljs-attribute">width</span>: <span class="hljs-number">50%</span>; <span class="hljs-attribute">border</span>: <span class="hljs-number">30px</span> solid green;}
  100% { <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>; <span class="hljs-attribute">border</span>: <span class="hljs-number">7px</span> solid purple;}
}
</code></pre>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>We created the <code>@keyframes</code> <a target="_blank" href="https://codesweetly.com/css-ruleset">ruleset</a> named <code>shape-image</code>.</li>
<li>We defined four keyframes for browsers to apply when an associated element's animation is at the specified key moments.</li>
</ol>
<p><strong>Tip:</strong> Use the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/CSSKeyframesRule">CSSKeyframesRule</a> interface in JavaScript to access the CSS <code>@keyframes</code> at-rules.</p>
<p>So, now that we know the CSS @keyframes ruleset, we can discuss the other component of CSS animations—<em>animation properties</em>.</p>
<h2 id="heading-what-are-css-animation-properties">What Are CSS Animation Properties?</h2>
<p><strong>CSS animation properties</strong> inform browsers about the animation you wish to apply to a specific element.</p>
<p>In other words, CSS animation properties describe the animation's attributes, such as its name, duration, direction, and iteration.</p>
<p>The nine (9) types of CSS animation properties are:</p>
<ul>
<li><code>animation-name</code></li>
<li><code>animation-duration</code></li>
<li><code>animation-timing-function</code></li>
<li><code>animation-delay</code></li>
<li><code>animation-iteration-count</code></li>
<li><code>animation-direction</code></li>
<li><code>animation-play-state</code></li>
<li><code>animation-fill-mode</code></li>
<li><code>animation</code></li>
</ul>
<p>Let's discuss each one now.</p>
<h3 id="heading-what-is-the-css-animation-name-property">What is the CSS <code>animation-name</code> property?</h3>
<p>The CSS <code>animation-name</code> property defines the name of the <code>@keyframes</code> at-rules containing the styles you wish to apply to a specific element.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">150px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">150px</span>;
  <span class="hljs-attribute">animation-name</span>: change-color;
}

<span class="hljs-keyword">@keyframes</span> change-color {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">background-color</span>: purple;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">background-color</span>: yellow;}
}
</code></pre>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>div</code> element.</li>
<li>We created <code>change-color</code>'s <code>@keyframes</code> ruleset.</li>
<li>We defined two keyframes for browsers to use when the <code>div</code> element's animation is at its zero percent (<code>0%</code>) and one hundred percent (<code>100%</code>) duration.</li>
</ol>
<p><strong>Tip:</strong> You can use the keyword <code>none</code> to deactivate an animation.</p>
<h3 id="heading-what-is-the-css-animation-duration-property">What is the CSS <code>animation-duration</code> property?</h3>
<p>The CSS <code>animation-duration</code> property defines the time to complete one animation cycle.</p>
<p><strong>Note the following:</strong></p>
<ul>
<li>The <code>animation-duration</code> property must be in milliseconds (ms) or seconds (s) units.</li>
<li><code>animation-duration</code>'s value must be zero or positive. Otherwise, browsers will ignore the duration declaration.</li>
<li>Zero seconds (<code>0s</code>) is <code>animation-duration</code>'s default value.</li>
<li>Suppose <code>0s</code> is <code>animation-duration</code>'s value. In that case, browsers will still execute the animation by firing the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Element/animationstart_event"><code>animationStart</code></a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Element/animationend_event"><code>animationEnd</code></a> events. But the <a target="_blank" href="https://codesweetly.com/css-animations-explained#what-is-an-animation-fill-mode-property-in-css"><code>animation-fill-mode</code></a>'s value will determine whether the animation is visible. For instance, if you set the <code>animation-fill-mode</code> to <code>none</code>, the animation will be invisible.</li>
</ul>
<p>Let's see some examples of the <code>animation-duration</code> property.</p>
<h4 id="heading-how-to-animate-an-elements-color-change-within-three-seconds">How to animate an element's color change within three seconds</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">150px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">150px</span>;
  <span class="hljs-attribute">animation-name</span>: change-color;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">3s</span>;
}

<span class="hljs-keyword">@keyframes</span> change-color {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">background-color</span>: purple;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">background-color</span>: yellow;}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-h6mb4k"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>div</code> element.</li>
<li>The <code>animation-duration</code> property sets the animation's runtime for one cycle to three seconds (<code>3s</code>).</li>
<li>We created <code>change-color</code>'s @keyframes <a target="_blank" href="https://codesweetly.com/css-ruleset">ruleset</a>.</li>
<li>We defined two keyframes for browsers to apply when the <code>div</code> element's animation is at zero percent (<code>0%</code>) and one hundred percent (<code>100%</code>) duration.</li>
</ol>
<p>Therefore, browsers will create a smooth three-second animation from <code>change-color</code>'s first keyframe to its last.</p>
<h4 id="heading-how-to-animate-an-images-border-and-width-changes-within-seven-seconds">How to animate an image's border and width changes within seven seconds</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">animation-name</span>: shape-image;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">7s</span>;
}

<span class="hljs-keyword">@keyframes</span> shape-image {
  0% { <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>; <span class="hljs-attribute">border</span>: <span class="hljs-number">5px</span> solid blue;}
  40% { <span class="hljs-attribute">width</span>: <span class="hljs-number">70%</span>; <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid red; <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">50%</span>;}
  75% { <span class="hljs-attribute">width</span>: <span class="hljs-number">50%</span>; <span class="hljs-attribute">border</span>: <span class="hljs-number">30px</span> solid green;}
  100% { <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>; <span class="hljs-attribute">border</span>: <span class="hljs-number">7px</span> solid purple;}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-prumgo"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>img</code> element.</li>
<li>The <code>animation-duration</code> property sets the animation's runtime for one cycle to seven seconds (<code>7s</code>).</li>
<li>We created <code>shape-image</code>'s @keyframes ruleset.</li>
<li>We defined four keyframes for browsers to apply when the image's animation is at the specified key moments.</li>
</ol>
<p>Therefore, browsers will create a smooth seven-second animation from <code>shape-image</code>'s first keyframe to its last.</p>
<h3 id="heading-what-is-the-css-animation-timing-function-property">What is the CSS <code>animation-timing-function</code> property?</h3>
<p>The CSS <code>animation-timing-function</code> property defines an animation's implementation timing (speed) throughout its duration.</p>
<p>In other words, the <code>animation-timing-function</code> property specifies the speed for implementing the animation at various intervals of its duration.</p>
<p>The values the <code>animation-timing-function</code> property accepts are:</p>
<ul>
<li><code>ease</code>: Starts the animation slowly. Then speeds it up and ends it slowly. <code>ease</code> is the <code>animation-timing-function</code> property's default value. It is equivalent to <code>cubic-bezier(0.25, 0.1, 0.25, 1)</code>.</li>
<li><code>ease-in</code>: Starts the animation slowly with a gradual increase in speed. It is equivalent to <code>cubic-bezier(0.42, 0, 1, 1)</code>.</li>
<li><code>ease-out</code>: Starts fast and ends the animation slowly. It is equivalent to <code>cubic-bezier(0, 0, 0.58, 1)</code>.</li>
<li><code>ease-in-out</code>: Starts and ends the animation slowly. It is equivalent to <code>cubic-bezier(0.42, 0, 0.58, 1)</code>.</li>
<li><code>linear</code>: Starts and ends the animation using a consistent speed throughout the animation's duration. It is equivalent to <code>cubic-bezier(0, 0, 1, 1)</code>.</li>
<li><code>cubic-bezier(p1, p2, p3, p4)</code>: Allows you to define the values of the <a target="_blank" href="https://www.cssportal.com/css-cubic-bezier-generator/">cubic-Bezier curve</a>.</li>
</ul>
<p>Let's see some examples of the <code>animation-timing-function</code> property.</p>
<h4 id="heading-how-to-animate-an-elements-width-change-using-a-linear-speed">How to animate an element's width change using a linear speed</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">150px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">150px</span>;
  <span class="hljs-attribute">background-color</span>: purple;
  <span class="hljs-attribute">animation-name</span>: change-width;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">7s</span>;
  <span class="hljs-attribute">animation-timing-function</span>: linear;
}

<span class="hljs-keyword">@keyframes</span> change-width {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">50px</span>;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-tzwrdc"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>div</code> element.</li>
<li>The <code>animation-duration</code> property sets the animation's runtime for one cycle to seven seconds (<code>7s</code>).</li>
<li>The <code>linear</code> timing function applied a consistent speed to the <code>div</code>'s animation.</li>
<li>We created <code>change-width</code>'s @keyframes ruleset.</li>
<li>We defined two keyframes for browsers to apply when the <code>div</code>'s animation is at zero percent (<code>0%</code>) and one hundred percent (<code>100%</code>) duration.</li>
</ol>
<p>Therefore, browsers will create a smooth seven-second animation from <code>change-width</code>'s first keyframe to its last.</p>
<p>Let's see another example.</p>
<h4 id="heading-how-to-animate-an-elements-width-change-using-an-ease-in-out-and-a-linear-speed">How to animate an element's width change using an ease-in-out and a linear speed</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">150px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">150px</span>;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">animation-name</span>: change-width;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">7s</span>;
}

<span class="hljs-selector-class">.first-div</span> {
  <span class="hljs-attribute">background-color</span>: purple;
  <span class="hljs-attribute">animation-timing-function</span>: ease-in-out;
}

<span class="hljs-selector-class">.second-div</span> {
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">animation-timing-function</span>: linear;
}

<span class="hljs-keyword">@keyframes</span> change-width {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">50px</span>;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-janmqa"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>div</code> element.</li>
<li>The <code>animation-duration</code> property sets the animation's runtime for one cycle to seven seconds (<code>7s</code>).</li>
<li>We used the <code>ease-in-out</code> timing function to apply a slow start and slow end speed to the <code>first-div</code>'s animation.</li>
<li>The <code>linear</code> timing function applied a consistent speed to the <code>second-div</code>'s animation.</li>
<li>We created <code>change-width</code>'s @keyframes ruleset.</li>
<li>We defined two keyframes for browsers to apply when the <code>div</code> elements' animations are at their zero percent (<code>0%</code>) and one hundred percent (<code>100%</code>) durations.</li>
</ol>
<p>Therefore, browsers will create a smooth seven-second animation from <code>change-width</code>'s first keyframe to its last.</p>
<h3 id="heading-what-is-the-css-animation-delay-property">What is the CSS <code>animation-delay</code> property?</h3>
<p>The CSS <code>animation-delay</code> property defines how long browsers should wait before starting an animation.</p>
<p>In other words, use <code>animation-delay</code> to specify whether the animation should start immediately from the beginning, immediately from a specific time, or later (after some delay).</p>
<p><strong>Note the following:</strong></p>
<ul>
<li>The <code>animation-delay</code> property must be in milliseconds (ms) or seconds (s) units.</li>
<li><code>0s</code> is <code>animation-delay</code>'s default value. It causes the animation to start once browsers apply it to an HTML element.</li>
<li>A negative value causes the animation to start immediately from the specified time. For instance, suppose an element's <code>animation-delay</code> value is <code>-3s</code>. In that case, the animation will begin immediately at 3 seconds.</li>
<li>A positive value causes the animation to start after the specified delay time has elapsed. For instance, suppose an element's <code>animation-delay</code> value is <code>3s</code>. In that case, the animation will begin after a 3-second delay.</li>
</ul>
<p>Let's see some examples of the <code>animation-delay</code> property.</p>
<h4 id="heading-how-to-animate-an-elements-width-change-with-a-four-second-delay">How to animate an element's width change with a four-second delay</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">150px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">150px</span>;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">animation-name</span>: change-width;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">7s</span>;
}

<span class="hljs-selector-class">.first-div</span> {
  <span class="hljs-attribute">background-color</span>: purple;
  <span class="hljs-attribute">animation-timing-function</span>: ease-in-out;
}

<span class="hljs-selector-class">.second-div</span> {
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">animation-timing-function</span>: linear;
  <span class="hljs-attribute">animation-delay</span>: <span class="hljs-number">4s</span>;
}

<span class="hljs-keyword">@keyframes</span> change-width {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">50px</span>;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-iidpmk"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>div</code> elements.</li>
<li>The <code>animation-duration</code> property sets the animation's runtime for one cycle to seven seconds (<code>7s</code>).</li>
<li>We used the <code>ease-in-out</code> timing function to apply a slow start and slow end speed to the <code>first-div</code>'s animation.</li>
<li>The <code>linear</code> timing function applied a consistent speed to the <code>second-div</code>'s animation.</li>
<li>The <code>animation-delay</code> property applied a four-second (<code>4s</code>) delay to the starting time of the <code>second-div</code>'s animation.</li>
<li>We created <code>change-width</code>'s @keyframes ruleset.</li>
<li>We defined two keyframes for browsers to apply when the <code>div</code> elements' animations are at their zero percent (<code>0%</code>) and one hundred percent (<code>100%</code>) durations.</li>
</ol>
<p>Therefore, browsers will delay the <code>second-div</code>'s animation for four seconds while starting the <code>first-div</code>'s animation immediately.</p>
<p>Below is another example of the <code>animation-delay</code> property.</p>
<h4 id="heading-how-to-animate-an-elements-width-change-from-the-fourth-second-mark-of-the-animation-sequence">How to animate an element's width change from the fourth-second mark of the animation sequence</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">150px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">150px</span>;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">animation-name</span>: change-width;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">7s</span>;
}

<span class="hljs-selector-class">.first-div</span> {
  <span class="hljs-attribute">background-color</span>: purple;
  <span class="hljs-attribute">animation-timing-function</span>: ease-in-out;
}

<span class="hljs-selector-class">.second-div</span> {
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">animation-timing-function</span>: linear;
  <span class="hljs-attribute">animation-delay</span>: -<span class="hljs-number">4s</span>;
}

<span class="hljs-keyword">@keyframes</span> change-width {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">50px</span>;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-6xga4t"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>div</code> elements.</li>
<li>The <code>animation-duration</code> property sets the animation's runtime for one cycle to seven seconds (<code>7s</code>).</li>
<li>We used the <code>ease-in-out</code> timing function to apply a slow start and slow end speed to the <code>first-div</code>'s animation.</li>
<li>The <code>linear</code> timing function applied a consistent speed to the <code>second-div</code>'s animation.</li>
<li>The <code>animation-delay</code> property makes the <code>second-div</code>'s animation start from the fourth-second mark of the animation sequence.</li>
<li>We created <code>change-width</code>'s @keyframes ruleset.</li>
<li>We defined two keyframes for browsers to apply when the <code>div</code> elements' animations are at their zero percent (<code>0%</code>) and one hundred percent (<code>100%</code>) durations.</li>
</ol>
<p>Therefore, browsers will start the <code>second-div</code>'s animation immediately at the fourth-second mark.</p>
<h3 id="heading-what-is-the-css-animation-iteration-count-property">What is the CSS <code>animation-iteration-count</code> property?</h3>
<p>The CSS <code>animation-iteration-count</code> property defines the number of times browsers should repeat an animation.</p>
<p><strong>Note the following:</strong></p>
<ul>
<li><code>1</code> is <code>animation-iteration-count</code>'s default value.</li>
<li>The <code>animation-iteration-count</code> property accepts non-integer values—for instance, <code>0.5</code> tells browsers to play half of a single animation cycle.</li>
<li><code>animation-iteration-count</code> does <em>not</em> accept negative values.</li>
<li>An <code>infinite</code> value means browsers should repeat the animation forever.</li>
</ul>
<p>Below are some examples.</p>
<h4 id="heading-how-to-animate-an-elements-width-change-with-a-two-cycle-iteration">How to animate an element's width change with a two-cycle iteration</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">background-color</span>: purple;
  <span class="hljs-attribute">animation-name</span>: change-width;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">5s</span>;
  <span class="hljs-attribute">animation-timing-function</span>: ease-in-out;
  <span class="hljs-attribute">animation-iteration-count</span>: <span class="hljs-number">2</span>;
}

<span class="hljs-keyword">@keyframes</span> change-width {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-vbcswe"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>div</code> element.</li>
<li>The <code>animation-duration</code> property sets the animation's runtime for one cycle to five seconds (<code>5s</code>).</li>
<li>We used the <code>ease-in-out</code> timing function to apply a slow start and slow end speed to the <code>div</code>'s animation.</li>
<li>The <code>animation-iteration-count</code> property tells browsers to run the animation twice.</li>
<li>We created <code>change-width</code>'s @keyframes ruleset.</li>
<li>We defined two keyframes for browsers to apply when the <code>div</code> element's animation is at zero percent (<code>0%</code>) and one hundred percent (<code>100%</code>) duration.</li>
</ol>
<p>Therefore, browsers will run the <code>div</code>'s animation in two cycles.</p>
<p>Below is another example of the <code>animation-iteration-count</code> property.</p>
<h4 id="heading-how-to-animate-an-elements-width-change-with-an-infinite-iteration">How to animate an element's width change with an infinite iteration</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">animation-name</span>: change-width;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">5s</span>;
  <span class="hljs-attribute">animation-timing-function</span>: ease-in-out;
  <span class="hljs-attribute">animation-iteration-count</span>: infinite;
}

<span class="hljs-keyword">@keyframes</span> change-width {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>; <span class="hljs-attribute">background-color</span>: purple;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>; <span class="hljs-attribute">background-color</span>: orange;}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-p1zwk5"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>div</code> element.</li>
<li>The <code>animation-duration</code> property sets the animation's runtime for one cycle to five seconds (<code>5s</code>).</li>
<li>We used the <code>ease-in-out</code> timing function to apply a slow start and slow end speed to the <code>div</code>'s animation.</li>
<li>The <code>animation-iteration-count</code> property tells browsers to run the animation infinitely.</li>
<li>We created <code>change-width</code>'s @keyframes ruleset.</li>
<li>We defined two keyframes for browsers to apply when the <code>div</code> element's animation is at its zero percent (<code>0%</code>) and one hundred percent (<code>100%</code>) duration.</li>
</ol>
<p>Therefore, browsers will run the <code>div</code>'s animation infinitely.</p>
<h3 id="heading-what-is-the-css-animation-direction-property">What is the CSS <code>animation-direction</code> property?</h3>
<p>The CSS <code>animation-direction</code> property specifies whether the animation's first iteration should run forward or backward. It also defines whether browsers should alternate the direction of subsequent iterations.</p>
<p>The values <code>animation-direction</code> accepts are:</p>
<ul>
<li><code>normal</code>: Play the animation in the normal direction (that is, forward). <code>normal</code> is <code>animation-direction</code>'s default value.</li>
<li><code>reverse</code>: Play the animation in the reverse direction (backward).</li>
<li><code>alternate</code>: Play the first animation cycle in the normal direction. Then, alternates the subsequent iterations between the backward and forward directions.</li>
<li><code>alternate-reverse</code>: Play the first animation cycle in the reverse direction. Then, alternates the subsequent iterations between the forward and backward directions.</li>
</ul>
<p>Below are some examples.</p>
<h4 id="heading-how-to-animate-an-elements-width-change-while-starting-each-animation-cycle-backward">How to animate an element's width change while starting each animation cycle backward</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">animation-name</span>: change-width;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">5s</span>;
  <span class="hljs-attribute">animation-timing-function</span>: ease-in-out;
  <span class="hljs-attribute">animation-iteration-count</span>: infinite;
  <span class="hljs-attribute">animation-direction</span>: reverse;
}

<span class="hljs-keyword">@keyframes</span> change-width {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>; <span class="hljs-attribute">background-color</span>: purple;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>; <span class="hljs-attribute">background-color</span>: orange;}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-d2n3zt"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>div</code> element.</li>
<li>The <code>animation-duration</code> property sets the animation's runtime for one cycle to five seconds (<code>5s</code>).</li>
<li>We used the <code>ease-in-out</code> timing function to apply a slow start and slow end speed to the <code>div</code>'s animation.</li>
<li>The <code>animation-iteration-count</code> property tells browsers to run the animation infinitely.</li>
<li>The <code>animation-direction</code> property starts each animation cycle in reverse (backward).</li>
<li>We created <code>change-width</code>'s @keyframes ruleset.</li>
<li>We defined two keyframes for browsers to apply when the <code>div</code> element's animation is at zero percent (<code>0%</code>) and one hundred percent (<code>100%</code>) duration.</li>
</ol>
<p>Below is another example of the <code>animation-direction</code> property.</p>
<h4 id="heading-how-to-animate-an-elements-width-change-while-alternating-the-animations-direction">How to animate an element's width change while alternating the animation's direction</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">animation-name</span>: change-width;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">5s</span>;
  <span class="hljs-attribute">animation-timing-function</span>: ease-in-out;
  <span class="hljs-attribute">animation-iteration-count</span>: infinite;
  <span class="hljs-attribute">animation-direction</span>: alternate;
}

<span class="hljs-keyword">@keyframes</span> change-width {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>; <span class="hljs-attribute">background-color</span>: purple;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>; <span class="hljs-attribute">background-color</span>: orange;}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-ld9kms"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>div</code> element.</li>
<li>The <code>animation-duration</code> property sets the animation's runtime for one cycle to five seconds (<code>5s</code>).</li>
<li>We used the <code>ease-in-out</code> timing function to apply a slow start and slow end speed to the <code>div</code>'s animation.</li>
<li>The <code>animation-iteration-count</code> property tells browsers to run the animation infinitely.</li>
<li>The <code>animation-direction</code> property alternates the direction of each cycle's animation.</li>
<li>We created <code>change-width</code>'s @keyframes ruleset.</li>
<li>We defined two keyframes for browsers to apply when the <code>div</code> element's animation is at zero percent (<code>0%</code>) and one hundred percent (<code>100%</code>) duration.</li>
</ol>
<h3 id="heading-what-is-the-css-animation-play-state-property">What is the CSS <code>animation-play-state</code> property?</h3>
<p>The CSS <code>animation-play-state</code> property specifies whether the browser is running or has paused a specific animation.</p>
<p>The values the <code>animation-play-state</code> property accepts are:</p>
<ul>
<li><code>running</code>: Specifies that the browser is running the animation. <code>running</code> is <code>animation-play-state</code>'s default value.</li>
<li><code>paused</code>: Specifies that the browser has paused the animation.</li>
</ul>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">animation-name</span>: change-width;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">5s</span>;
  <span class="hljs-attribute">animation-timing-function</span>: ease-in-out;
  <span class="hljs-attribute">animation-iteration-count</span>: infinite;
  <span class="hljs-attribute">animation-direction</span>: alternate;
}

<span class="hljs-selector-tag">div</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">animation-play-state</span>: paused;
}

<span class="hljs-keyword">@keyframes</span> change-width {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>; <span class="hljs-attribute">background-color</span>: purple;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>; <span class="hljs-attribute">background-color</span>: orange;}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-kbommn"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>div</code> element.</li>
<li>The <code>animation-duration</code> property sets the animation's runtime for one cycle to five seconds (<code>5s</code>).</li>
<li>We used the <code>ease-in-out</code> timing function to apply a slow start and slow end speed to the <code>div</code>'s animation.</li>
<li>The <code>animation-iteration-count</code> property tells browsers to run the animation infinitely.</li>
<li>The <code>animation-direction</code> property alternates the direction of each cycle's animation.</li>
<li>We used the <code>animation-play-state</code> on the <code>div</code>'s hover <a target="_blank" href="https://codesweetly.com/css-pseudo-selectors">pseudo-class</a> to pause the animation whenever users move their mouse over the <code>div</code> element.</li>
<li>We created <code>change-width</code>'s @keyframes ruleset.</li>
<li>We defined two keyframes for browsers to apply when the <code>div</code> element's animation is at zero percent (<code>0%</code>) and one hundred percent (<code>100%</code>) duration.</li>
</ol>
<h3 id="heading-what-is-the-css-animation-fill-mode-property">What is the CSS <code>animation-fill-mode</code> property?</h3>
<p>The CSS <code>animation-fill-mode</code> property defines the styles browsers should apply to an element before (or after) its animation runs.</p>
<p>The values the <code>animation-fill-mode</code> property accepts are:</p>
<ul>
<li><code>none</code>: Browsers will apply <em>no</em> style to the element before or after the animation runs. <code>none</code> is <code>animation-fill-mode</code>'s default value.</li>
<li><code>forwards</code>: The element will retain the last keyframe's style declarations when the animation ends. (Note: The <code>animation-direction</code> and <code>animation-iteration-count</code> properties determine the last keyframe.)</li>
<li><code>backwards</code>: The element will retain the first keyframe's style declarations during the <code>animation-delay</code> period. (Note: The <code>animation-direction</code> property determines the first keyframe.)</li>
<li><code>both</code>: Browsers will apply both the forwards and backwards rules. Therefore, the animation properties will extend in both directions.</li>
</ul>
<p>Below are some examples.</p>
<h4 id="heading-how-to-style-an-element-after-its-animation-ends">How to style an element after its animation ends</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">background-color</span>: green;
  <span class="hljs-attribute">animation-name</span>: change-width;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">5s</span>;
  <span class="hljs-attribute">animation-timing-function</span>: ease-in-out;
  <span class="hljs-attribute">animation-fill-mode</span>: forwards;
}

<span class="hljs-keyword">@keyframes</span> change-width {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>; <span class="hljs-attribute">background-color</span>: purple;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>; <span class="hljs-attribute">background-color</span>: orange;}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-lkc7mw"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>div</code> element.</li>
<li>The <code>animation-duration</code> property sets the animation's runtime for one cycle to five seconds (<code>5s</code>).</li>
<li>We used the <code>ease-in-out</code> timing function to apply a slow start and slow end speed to the <code>div</code>'s animation.</li>
<li>The <code>animation-fill-mode</code> property tells browsers to retain the last keyframe's style declarations when the animation ends.</li>
<li>We created <code>change-width</code>'s @keyframes ruleset.</li>
<li>We defined two keyframes for browsers to apply when the <code>div</code> element's animation is at zero percent (<code>0%</code>) and one hundred percent (<code>100%</code>) duration.</li>
</ol>
<p>Below is another example of the <code>animation-fill-mode</code> property.</p>
<h4 id="heading-how-to-style-an-element-during-its-animation-delay-period">How to style an element during its animation delay period</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">background-color</span>: green;
  <span class="hljs-attribute">animation-name</span>: change-width;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">5s</span>;
  <span class="hljs-attribute">animation-timing-function</span>: ease-in-out;
  <span class="hljs-attribute">animation-delay</span>: <span class="hljs-number">3s</span>;
  <span class="hljs-attribute">animation-fill-mode</span>: backwards;
}

<span class="hljs-keyword">@keyframes</span> change-width {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>; <span class="hljs-attribute">background-color</span>: purple;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>; <span class="hljs-attribute">background-color</span>: orange;}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-nfmq3r"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>div</code> element.</li>
<li>The <code>animation-duration</code> property sets the animation's runtime for one cycle to five seconds (<code>5s</code>).</li>
<li>We used the <code>ease-in-out</code> timing function to apply a slow start and slow end speed to the <code>div</code>'s animation.</li>
<li>The <code>animation-fill-mode</code> property tells browsers to retain the first keyframe's style declarations during the <code>animation-delay</code> period.</li>
<li>We created <code>change-width</code>'s @keyframes ruleset.</li>
<li>We defined two keyframes for browsers to apply when the <code>div</code> element's animation is at zero percent (<code>0%</code>) and one hundred percent (<code>100%</code>) duration.</li>
</ol>
<p>Let's see a third example of the <code>animation-fill-mode</code> property.</p>
<h4 id="heading-how-to-style-an-element-during-its-animation-delay-and-after-the-animation">How to style an element during its animation delay and after the animation</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">background-color</span>: green;
  <span class="hljs-attribute">animation-name</span>: change-width;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">5s</span>;
  <span class="hljs-attribute">animation-timing-function</span>: ease-in-out;
  <span class="hljs-attribute">animation-delay</span>: <span class="hljs-number">3s</span>;
  <span class="hljs-attribute">animation-fill-mode</span>: both;
}

<span class="hljs-keyword">@keyframes</span> change-width {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>; <span class="hljs-attribute">background-color</span>: purple;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>; <span class="hljs-attribute">background-color</span>: orange;}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-gbypmt"><strong>Try Editing It</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>animation-name</code> property specifies the <code>@keyframes</code> we wish to apply to the <code>div</code> element.</li>
<li>The <code>animation-duration</code> property sets the animation's runtime for one cycle to five seconds (<code>5s</code>).</li>
<li>We used the <code>ease-in-out</code> timing function to apply a slow start and slow end speed to the <code>div</code>'s animation.</li>
<li>The <code>animation-fill-mode</code> property tells browsers to apply both the forwards and backwards rules.</li>
<li>We created <code>change-width</code>'s @keyframes ruleset.</li>
<li>We defined two keyframes for browsers to use when the <code>div</code> element's animation is at zero percent (<code>0%</code>) and one hundred percent (<code>100%</code>) duration.</li>
</ol>
<h2 id="heading-what-is-the-css-animation-property">What is the CSS <code>animation</code> Property?</h2>
<p>We use the <code>animation</code> property as a shorthand for:</p>
<ul>
<li><code>animation-name</code></li>
<li><code>animation-duration</code></li>
<li><code>animation-timing-function</code></li>
<li><code>animation-delay</code></li>
<li><code>animation-iteration-count</code></li>
<li><code>animation-direction</code></li>
<li><code>animation-play-state</code></li>
<li><code>animation-fill-mode</code></li>
</ul>
<p>In other words, instead of writing:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">animation-name</span>: change-width;
  <span class="hljs-attribute">animation-duration</span>: <span class="hljs-number">5s</span>;
  <span class="hljs-attribute">animation-timing-function</span>: ease-in-out;
  <span class="hljs-attribute">animation-delay</span>: <span class="hljs-number">2s</span>;
  <span class="hljs-attribute">animation-iteration-count</span>: <span class="hljs-number">3</span>;
  <span class="hljs-attribute">animation-direction</span>: alternate;
  <span class="hljs-attribute">animation-play-state</span>: running;
  <span class="hljs-attribute">animation-fill-mode</span>: both;
}
</code></pre>
<p>You can alternatively use the <code>animation</code> property to shorten your code like so:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">animation</span>: <span class="hljs-number">5s</span> ease-in-out <span class="hljs-number">2s</span> <span class="hljs-number">3</span> alternate both running change-width;
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-37ccew"><strong>Try Editing It</strong></a></p>
<p>Here is the <code>animation</code> property's syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">animation</span>: <span class="hljs-selector-tag">animation-duration</span> <span class="hljs-selector-tag">animation-timing-function</span> <span class="hljs-selector-tag">animation-delay</span> <span class="hljs-selector-tag">animation-iteration-count</span> <span class="hljs-selector-tag">animation-direction</span> <span class="hljs-selector-tag">animation-fill-mode</span> <span class="hljs-selector-tag">animation-play-state</span> <span class="hljs-selector-tag">animation-name</span>;
</code></pre>
<p><strong>Note:</strong></p>
<ul>
<li>The way you arrange the time values is essential. Browsers read the first time-value as <code>animation-duration</code>. And they assign the second one to <code>animation-delay</code>.</li>
<li>It is best to list <code>animation-name</code> last. Otherwise, browsers may assign the <code>animation-name</code>'s value to other properties.</li>
<li>You can apply multiple <code>@keyframes</code> <a target="_blank" href="https://codesweetly.com/css-ruleset">rulesets</a> to an element using the <code>animation</code> property. Here's an example:</li>
</ul>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">70px</span>;
  <span class="hljs-attribute">background-color</span>: green;
  <span class="hljs-attribute">animation</span>: 
    <span class="hljs-number">5s</span> ease-in-out <span class="hljs-number">3s</span> <span class="hljs-number">3</span> alternate both change-width, 
    <span class="hljs-number">5s</span> <span class="hljs-number">3s</span> infinite alternate both change-shape, 
    <span class="hljs-number">5s</span> <span class="hljs-number">3s</span> infinite rotate-hue;
}

<span class="hljs-keyword">@keyframes</span> change-width {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">70px</span>; <span class="hljs-attribute">background-color</span>: purple;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>; <span class="hljs-attribute">background-color</span>: orange;}
}

<span class="hljs-keyword">@keyframes</span> change-shape {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">border-radius</span>: <span class="hljs-number">0%</span>; <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid blue;}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">border-radius</span>: <span class="hljs-number">50%</span>; <span class="hljs-attribute">border</span>: <span class="hljs-number">7px</span> solid green;}
}

<span class="hljs-keyword">@keyframes</span> rotate-hue {
  <span class="hljs-selector-tag">from</span> {<span class="hljs-attribute">filter</span>: <span class="hljs-built_in">hue-rotate</span>(<span class="hljs-number">0deg</span>);}
  <span class="hljs-selector-tag">to</span> {<span class="hljs-attribute">filter</span>: <span class="hljs-built_in">hue-rotate</span>(<span class="hljs-number">360deg</span>);}
}
</code></pre>
<p><a target="_blank" href="https://codesweetly.com/try-it-sdk/css/css-animations/js-4lyg4d"><strong>Try Editing It</strong></a></p>
<p>The snippet above applied three <code>@keyframes</code> rulesets to the <code>div</code> element using commas (<code>,</code>) to separate each <code>@keyframes</code>' configurations.</p>
<p><strong>Note:</strong> We used the <a target="_blank" href="https://www.quackit.com/css/functions/css_hue-rotate_function.cfm"><code>hue-rotate()</code></a> function to rotate the <code>div</code>'s colors.</p>
<h2 id="heading-important-stuff-to-know-about-css-transitions-and-animations">Important Stuff to Know about CSS Transitions and Animations</h2>
<ol>
<li>You can't animate all CSS properties. Have a look at MDN's <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties">Animatable CSS properties</a> article to see the ones you can animate.</li>
<li>CSS transitions and animations are <a target="_blank" href="https://codesweetly.com/web-tech-terms-e#expensive-operation-computing">expensive operations</a> for most CSS properties—except <code>opacity</code> and <code>transform</code>. In other words, applying transitions (or animations) to any CSS box model property is inherently a <a target="_blank" href="https://codesweetly.com/web-tech-terms-c#cpu-intensive">CPU-intensive</a> task. Therefore, animate only <code>opacity</code>, and <code>transform</code> properties if you are concerned about your page's performance.</li>
<li>Be mindful of the <a target="_blank" href="https://dzhavat.github.io/2021/02/18/debugging-layout-repaint-issues-triggered-by-css-transition.html">layout repainting issues</a> that CSS transitions may cause through your elements' stacking order.</li>
</ol>
<h2 id="heading-wrapping-up">Wrapping up</h2>
<p>In this article, we discuss the differences between CSS transitions and animations. We also used examples to discuss how to use them.</p>
<p>Thanks for reading.</p>
<h3 id="heading-and-heres-a-useful-react-typescript-resource">And here's a useful React TypeScript resource:</h3>
<p>I wrote a book about <a target="_blank" href="https://amzn.to/3Pa4bI4">Creating NPM Packages</a>!</p>
<p>It is a beginner-friendly book that takes you from zero to creating, testing, and publishing NPM packages like a pro.</p>
<p><a target="_blank" href="https://amzn.to/3Pa4bI4"><img src="https://www.freecodecamp.org/news/content/images/2023/09/creating-npm-package-banner-codesweetly.png" alt="Creating NPM Package Book Now Available at Amazon" width="600" height="400" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ CSS Transform Handbook – Complete Guide to CSS Transform Functions and Properties ]]>
                </title>
                <description>
                    <![CDATA[ CSS transform allows you to translate, rotate, skew, scale, or add perspective effects to HTML elements. This tutorial discusses everything you need to know to transform HTML elements like a pro. Table of Contents What is the CSS transform Property?... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/complete-guide-to-css-transform-functions-and-properties/</link>
                <guid isPermaLink="false">66ba0de37fb82b484b253a29</guid>
                
                    <category>
                        <![CDATA[ code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Mon, 19 Jun 2023 21:13:33 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738338625918/27521e84-35de-4453-a153-1d419e1d0e2b.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><strong>CSS transform</strong> allows you to translate, rotate, skew, scale, or add perspective effects to HTML elements.</p>
<p>This tutorial discusses everything you need to know to transform HTML elements like a pro.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-transform-property">What is the CSS <code>transform</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-rotate-function">What is the CSS <code>rotate()</code> Function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-rotatex-function">What is the CSS <code>rotateX()</code> Function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-rotatey-function">What is the CSS <code>rotateY()</code> Function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-rotatez-function">What is the CSS <code>rotateZ()</code> Function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-rotate3d-function">What is the CSS <code>rotate3d()</code> Function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-css-rotate-functions-vs-rotate-property-whats-the-difference">CSS Rotate Functions vs. <code>rotate</code> Property: What's the Difference?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-scale-function">What is the CSS <code>scale()</code> Function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-css-scale-function-vs-scale-property-whats-the-difference">CSS <code>scale()</code> Function vs. <code>scale</code> Property: What's the Difference?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-scalez-function">What is the CSS <code>scaleZ()</code> Function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-scale3d-function">What is the CSS <code>scale3d()</code> Function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-skew-function">What is the CSS <code>skew()</code> Function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-translate-function">What is the CSS <code>translate()</code> Function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-translatez-function">What is the CSS <code>translateZ()</code> Function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-translate3d-function">What is the CSS <code>translate3d()</code> Function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-css-translate-functions-vs-translate-property-whats-the-difference">CSS Translate Functions vs. <code>translate</code> Property: What's the Difference?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-perspective-function">What is the CSS <code>perspective()</code> Function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-css-perspective-function-vs-perspective-property-whats-the-difference">CSS <code>perspective()</code> Function vs. <code>perspective</code> Property: What's the Difference?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-css-matrix-function">What is the CSS <code>matrix()</code> Function?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-does-the-css-transform-functions-order-matter">Why Does the CSS Transform Functions' Order Matter?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-tools-for-converting-transform-functions-to-matrix">Tools for Converting Transform Functions to <code>matrix()</code></a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-important-stuff-to-know-about-transforming-elements-in-css">Important Stuff to Know about Transforming Elements in CSS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ol>
<p>So, without further ado, let's discuss the CSS <code>transform</code> property.</p>
<h2 id="heading-what-is-the-css-transform-property">What Is the CSS <code>transform</code> Property?</h2>
<p>The CSS <code>transform</code> property specifies the transformational effect you wish to apply to an HTML element.</p>
<p><strong>Here's the syntax:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">html-element</span> {
  <span class="hljs-attribute">transform</span>: value;
}
</code></pre>
<p>The CSS <code>transform</code> property accepts the following values:</p>
<ul>
<li><p><code>inherit</code>: Transforms the element with its parent element's <code>transform</code> value.</p>
</li>
<li><p><code>initial</code>: Transforms the HTML element with its default <code>transform</code> value.</p>
</li>
<li><p><code>matrix()</code>: Transforms the element two-dimensionally with a matrix of six values.</p>
</li>
<li><p><code>matrix3d()</code>: Transforms the HTML element three-dimensionally with a 4x4 matrix of sixteen values.</p>
</li>
<li><p><code>none</code>: Applies <em>no</em> transformation to the HTML element.</p>
</li>
<li><p><code>perspective()</code>: Transforms a 3D transformed element with a perspective view.</p>
</li>
<li><p><code>rotate()</code>: Transforms the element by rotating it two-dimensionally.</p>
</li>
<li><p><code>rotate3d()</code>: Transforms the element by rotating it three-dimensionally.</p>
</li>
<li><p><code>rotateX()</code>: Transforms the element by rotating it three-dimensionally along the X-axis.</p>
</li>
<li><p><code>rotateY()</code>: Transforms the element by rotating it three-dimensionally along the Y-axis.</p>
</li>
<li><p><code>rotateZ()</code>: Transforms the HTML element by rotating it three-dimensionally along the Z-axis.</p>
</li>
<li><p><code>scale()</code>: Transforms the element by scaling it two-dimensionally.</p>
</li>
<li><p><code>scale3d()</code>: Transforms the element by scaling it three-dimensionally.</p>
</li>
<li><p><code>scaleX()</code>: Transforms the element by scaling it along the X-axis.</p>
</li>
<li><p><code>scaleY()</code>: Transforms the element by scaling it along the Y-axis.</p>
</li>
<li><p><code>scaleZ()</code>: Transforms the HTML element by scaling it three-dimensionally along the Z-axis.</p>
</li>
<li><p><code>skew()</code>: Transforms the element by skewing it two-dimensionally along the X- and Y-axis.</p>
</li>
<li><p><code>skewX()</code>: Transforms the element by skewing it two-dimensionally along the X-axis.</p>
</li>
<li><p><code>skewY()</code>: Transforms the element by skewing it two-dimensionally along the Y-axis.</p>
</li>
<li><p><code>translate()</code>: Transforms the HTML element by translating (moving) it two-dimensionally.</p>
</li>
<li><p><code>translate3d()</code>: Transforms the element by translating it three-dimensionally.</p>
</li>
<li><p><code>translateX()</code>: Transforms the element by translating it along the X-axis.</p>
</li>
<li><p><code>translateY()</code>: Transforms the element by translating it along the Y-axis.</p>
</li>
<li><p><code>translateZ()</code>: Transforms the element by translating it three-dimensionally along the Z-axis.</p>
</li>
</ul>
<p><strong>Note:</strong> The <code>transform</code> property accepts one or more <a target="_blank" href="https://codesweetly.com/web-tech-terms-c#css-transform-functions">CSS transform functions</a>. For instance, here's a valid <code>transform</code> declaration:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">perspective</span>(<span class="hljs-number">370px</span>) <span class="hljs-built_in">scaleZ</span>(<span class="hljs-number">5</span>) <span class="hljs-built_in">rotate</span>(<span class="hljs-number">17deg</span>);
}
</code></pre>
<p>In the snippet above, we assigned three transform functions to the <code>transform</code> property. Let's talk more about some of <code>transform</code>'s values.</p>
<h2 id="heading-what-is-the-css-rotate-function">What is the CSS <code>rotate()</code> Function?</h2>
<p><code>rotate()</code> transforms an element by rotating it two-dimensionally around a fixed point.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>"Transform origin" is the fixed point around which an element rotates.</p>
</li>
<li><p>You can define your element's fixed point using the CSS <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/transform-origin"><code>transform-origin</code></a> property. But the default is <code>center</code>.</p>
</li>
</ul>
<h3 id="heading-syntax-of-the-css-rotate-function">Syntax of the CSS <code>rotate()</code> function</h3>
<p><code>rotate()</code> accepts a single <a target="_blank" href="https://codesweetly.com/javascript-arguments-vs-parameters">argument</a>. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">element</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotate</span>(angle);
}
</code></pre>
<p><strong>Note the following:</strong></p>
<ul>
<li><p>The <code>rotate(angle)</code> function is equivalent to <code>rotate3d(0, 0, 1, angle)</code> or <code>rotateZ(angle)</code>.</p>
</li>
<li><p>The <code>angle</code> argument specifies the element's angle of rotation.</p>
</li>
<li><p><code>angle</code> can be in <a target="_blank" href="https://en.wikipedia.org/wiki/Degree_%28angle%29">degrees</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Gradian">gradians</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Radian">radians</a>, or <a target="_blank" href="https://en.wikipedia.org/wiki/Turn_\(angle\)">turns</a>.</p>
</li>
<li><p>An <code>angle</code> argument consists of a number followed by the unit you wish to use—for instance, <code>45deg</code>.</p>
</li>
<li><p>Your browser's writing direction determines the element's direction of rotation.</p>
</li>
<li><p>A positive angle will rotate the element clockwise in a left-to-right writing direction. But a negative angle will do a counterclockwise rotation.</p>
</li>
<li><p>A positive angle will rotate the element counterclockwise in a right-to-left writing context. But a negative angle will do a clockwise rotation.</p>
</li>
</ul>
<h3 id="heading-examples-of-the-css-rotate-function">Examples of the CSS <code>rotate()</code> function</h3>
<p>Below are some examples of how the CSS <code>rotate()</code> function works.</p>
<h4 id="heading-how-to-do-a-zero-degree-rotation-in-css">How to do a zero-degree rotation in CSS:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotate</span>(<span class="hljs-number">0deg</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-zcgvaa?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotate()</code> function to specify a zero-degree (0⁰) rotation for the image element.</p>
<h4 id="heading-how-to-do-a-45-degree-rotation-in-css">How to do a 45-degree rotation in CSS:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotate</span>(<span class="hljs-number">45deg</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-86xhmx?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotate()</code> function to specify a forty-five-degree (45⁰) rotation for the image element.</p>
<h4 id="heading-how-to-do-a-negative-seventy-degree-rotation-in-css">How to do a negative seventy-degree rotation in CSS:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotate</span>(-<span class="hljs-number">70deg</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-3gb1my?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotate()</code> function to specify a negative seventy-degree (70⁰) rotation for the image element.</p>
<h2 id="heading-what-is-the-css-rotatex-function">What is the CSS <code>rotateX()</code> Function?</h2>
<p><code>rotateX()</code> transforms an element by rotating it three-dimensionally around the X-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/cartesian-coordinate-system-three-dimensional-diagram-codesweetly.png" alt="Illustration of the 3D Cartesian coordinate system" width="600" height="400" loading="lazy"></p>
<p><em>A three-dimensional Cartesian coordinate system showing the X-, Y-, and Z-axis</em></p>
<h3 id="heading-syntax-of-the-css-rotatex-function">Syntax of the CSS <code>rotateX()</code> function</h3>
<p><code>rotateX()</code> accepts a single argument. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">element</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotateX</span>(angle);
}
</code></pre>
<p><strong>Note the following:</strong></p>
<ul>
<li><p>The <code>rotateX(angle)</code> function is equivalent to <code>rotate3d(1, 0, 0, angle)</code>.</p>
</li>
<li><p>The <code>angle</code> argument specifies the element's angle of rotation.</p>
</li>
<li><p><code>angle</code> can be in degree, gradian, radian, or turn.</p>
</li>
<li><p>An <code>angle</code> argument consists of a number followed by the unit you wish to use—for instance, <code>45deg</code>.</p>
</li>
</ul>
<h3 id="heading-examples-of-the-css-rotatex-function">Examples of the CSS <code>rotateX()</code> function</h3>
<p>Below are some examples of how the CSS <code>rotateX()</code> function works.</p>
<h4 id="heading-how-to-do-a-zero-degree-rotation-around-the-x-axis">How to do a zero-degree rotation around the X-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotateX</span>(<span class="hljs-number">0deg</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ej9ent?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotateX()</code> function to specify a zero-degree (0⁰) rotation for the image around the X-axis.</p>
<h4 id="heading-how-to-do-a-70-degree-rotation-around-the-x-axis">How to do a 70-degree rotation around the X-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotateX</span>(<span class="hljs-number">70deg</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-fvhyjx?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotateX()</code> function to specify a seventy-degree (70⁰) rotation for the image around the X-axis.</p>
<h2 id="heading-what-is-the-css-rotatey-function">What is the CSS <code>rotateY()</code> Function?</h2>
<p><code>rotateY()</code> transforms an element by rotating it three-dimensionally around the Y-axis.</p>
<h3 id="heading-syntax-of-the-css-rotatey-function">Syntax of the CSS <code>rotateY()</code> function</h3>
<p><code>rotateY()</code> accepts a single argument. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">element</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotateY</span>(angle);
}
</code></pre>
<p><strong>Note the following:</strong></p>
<ul>
<li><p>The <code>rotateY(angle)</code> function is equivalent to <code>rotate3d(0, 1, 0, angle)</code>.</p>
</li>
<li><p>The <code>angle</code> argument specifies the element's angle of rotation.</p>
</li>
<li><p><code>angle</code> can be in degrees, gradians, radians, or turns.</p>
</li>
<li><p>An <code>angle</code> argument consists of a number followed by the unit you wish to use—for instance, <code>45deg</code>.</p>
</li>
</ul>
<h3 id="heading-examples-of-the-css-rotatey-function">Examples of the CSS <code>rotateY()</code> function</h3>
<p>Below are some examples of how the CSS <code>rotateY()</code> function works.</p>
<h4 id="heading-how-to-do-a-zero-degree-rotation-around-the-y-axis">How to do a zero-degree rotation around the Y-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotateY</span>(<span class="hljs-number">0deg</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-frg3ks?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotateY()</code> function to specify a zero-degree (0⁰) rotation for the image around the Y-axis.</p>
<h4 id="heading-how-to-do-a-70-degree-rotation-around-the-y-axis">How to do a 70-degree rotation around the Y-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotateY</span>(<span class="hljs-number">70deg</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-yvydga?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotateY()</code> function to specify a seventy-degree (70⁰) rotation for the image around the Y-axis.</p>
<h2 id="heading-what-is-the-css-rotatez-function">What is the CSS <code>rotateZ()</code> Function?</h2>
<p><code>rotateZ()</code> transforms an element by rotating it three-dimensionally around the Z-axis.</p>
<h3 id="heading-syntax-of-the-css-rotatez-function">Syntax of the CSS <code>rotateZ()</code> function</h3>
<p><code>rotateZ()</code> accepts a single argument. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">element</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotateZ</span>(angle);
}
</code></pre>
<p><strong>Note the following:</strong></p>
<ul>
<li><p>The <code>rotateZ(angle)</code> function is equivalent to <code>rotate3d(0, 0, 1, angle)</code> or <code>rotate(angle)</code>.</p>
</li>
<li><p>The <code>angle</code> argument specifies the element's angle of rotation.</p>
</li>
<li><p><code>angle</code> can be in degrees, gradians, radians, or turns.</p>
</li>
<li><p>An <code>angle</code> argument consists of a number followed by the unit you wish to use—for instance, <code>45deg</code>.</p>
</li>
</ul>
<h3 id="heading-examples-of-the-css-rotatez-function">Examples of the CSS <code>rotateZ()</code> function</h3>
<p>Below are some examples of how the CSS <code>rotateZ()</code> function works.</p>
<h4 id="heading-how-to-do-a-zero-degree-rotation-around-the-z-axis">How to do a zero-degree rotation around the Z-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotateZ</span>(<span class="hljs-number">0deg</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ozqupq?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotateZ()</code> function to specify a zero-degree (0⁰) rotation for the image around the Z-axis.</p>
<h4 id="heading-how-to-do-a-70-degree-rotation-around-the-z-axis">How to do a 70-degree rotation around the Z-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotateZ</span>(<span class="hljs-number">70deg</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-g6qrwc?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotateZ()</code> function to specify a seventy-degree (70⁰) rotation for the image around the Z-axis.</p>
<h2 id="heading-what-is-the-css-rotate3d-function">What is the CSS <code>rotate3d()</code> Function?</h2>
<p><code>rotate3d()</code> transforms an element by rotating it three-dimensionally around the x-, y-, and z-axis.</p>
<h3 id="heading-syntax-of-the-css-rotate3d-function">Syntax of the CSS <code>rotate3d()</code> function</h3>
<p><code>rotate3d()</code> accepts four arguments. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">element</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotate3d</span>(x, y, z, angle);
}
</code></pre>
<p><strong>Note the following:</strong></p>
<ul>
<li><p>The <code>x</code>, <code>y</code>, and <code>z</code> arguments are numbers specifying the x-, y-, and z-coordinates.</p>
</li>
<li><p>The coordinates are the axis around which the element will rotate.</p>
</li>
<li><p>The <code>angle</code> argument specifies the element's angle of rotation.</p>
</li>
<li><p><code>angle</code> can be in degrees, gradians, radians, or turns.</p>
</li>
<li><p>An <code>angle</code> argument consists of a number followed by the unit you wish to use—for instance, <code>45deg</code>.</p>
</li>
</ul>
<h3 id="heading-examples-of-the-css-rotate3d-function">Examples of the CSS <code>rotate3d()</code> function</h3>
<p>Below are some examples of how the CSS <code>rotate3d()</code> function works.</p>
<h4 id="heading-how-to-do-a-70-degree-rotation-around-the-z-axis-1">How to do a 70-degree rotation around the Z-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotate3d</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">70deg</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-i6f9pr?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotate3d()</code> function to specify a seventy-degree (70⁰) rotation for the image around the Z-axis.</p>
<h4 id="heading-how-to-do-a-70-degree-rotation-around-the-x-y-and-z-axis">How to do a 70-degree rotation around the X-, Y-, and Z-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">rotate3d</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">70deg</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ctws81?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotate3d()</code> function to specify a seventy-degree (70⁰) rotation for the image around the x-, y-, and z-axis.</p>
<h2 id="heading-css-rotate-functions-vs-rotate-property-whats-the-difference">CSS Rotate Functions vs. <code>rotate</code> Property: What's the Difference?</h2>
<p>CSS rotate functions and CSS <code>rotate</code> property provides two similar ways to specify rotation transformations.</p>
<p>The main differences between the two rotation techniques are as follows:</p>
<ul>
<li><p>The CSS <code>rotate</code> property allows rotating an element without using the CSS <code>transform</code> property.</p>
</li>
<li><p>The CSS <code>rotate</code> property's syntax is shorter than its function alternative.</p>
</li>
<li><p>The CSS <code>rotate</code> property saves you from remembering the specific order to position the <a target="_blank" href="https://codesweetly.com/web-tech-terms-c#css-transform-functions">transform functions</a>.</p>
</li>
<li><p>Browsers calculate the transform functions' matrix in the order you assigned them to the CSS <code>transform</code> property—from left to right.</p>
</li>
<li><p>Browsers calculate the transform properties' matrix in the following <a target="_blank" href="https://www.w3.org/TR/css-transforms-2/#ctm">transformation matrix order</a>:</p>
<ol>
<li><p><code>translate</code></p>
</li>
<li><p><code>rotate</code></p>
</li>
<li><p><code>scale</code></p>
</li>
</ol>
</li>
</ul>
<p>Below are some examples.</p>
<h3 id="heading-how-to-use-css-rotate-property-vs-function-to-do-a-45-degree-rotation">How to use CSS <code>rotate</code> property vs. function to do a 45-degree rotation</h3>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">rotate</span>: <span class="hljs-number">45deg</span>; <span class="hljs-comment">/* Equivalent to a transform: rotate(45deg) property */</span>
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-rdw9a5?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotate</code> property to specify a forty-five-degree (45⁰) rotation for the image element.</p>
<h3 id="heading-how-to-use-css-rotate-property-vs-function-to-do-a-70-degree-rotation-around-the-x-axis">How to use CSS <code>rotate</code> property vs. function to do a 70-degree rotation around the X-axis</h3>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">rotate</span>: x <span class="hljs-number">70deg</span>; <span class="hljs-comment">/* Equal to a transform: rotateX(70deg) property */</span>
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-pal1am?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotate</code> property to specify a seventy-degree (70⁰) rotation for the image around the X-axis.</p>
<h3 id="heading-how-to-use-css-rotate-property-vs-function-to-do-a-70-degree-rotation-around-the-y-axis">How to use CSS <code>rotate</code> property vs. function to do a 70-degree rotation around the Y-axis</h3>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">rotate</span>: y <span class="hljs-number">70deg</span>; <span class="hljs-comment">/* Equal to a transform: rotateY(70deg) property */</span>
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ldnmfd?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotate</code> property to specify a seventy-degree (70⁰) rotation for the image around the Y-axis.</p>
<h3 id="heading-how-to-use-css-rotate-property-vs-function-to-do-a-70-degree-rotation-around-the-z-axis">How to use CSS <code>rotate</code> property vs. function to do a 70-degree rotation around the Z-axis</h3>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">rotate</span>: z <span class="hljs-number">70deg</span>; <span class="hljs-comment">/* Equal to a transform: rotateZ(70deg) property */</span>
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-stf9ty?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotate</code> property to specify a seventy-degree (70⁰) rotation for the image around the Z-axis.</p>
<h3 id="heading-how-to-use-css-rotate-property-vs-function-to-do-a-70-degree-rotation-around-the-x-y-and-z-axis">How to use CSS <code>rotate</code> property vs. function to do a 70-degree rotation around the X-, Y-, and Z-axis</h3>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">rotate</span>: <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">1</span> <span class="hljs-number">70deg</span>; <span class="hljs-comment">/* Equal to a transform: rotate3d(1, 1, 1, 70deg) property */</span>
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-qfflxq?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>rotate</code> property to specify a seventy-degree (70⁰) rotation for the image around the x-, y-, and z-axis.</p>
<p><strong>Note:</strong> A <code>none</code> value tells browsers <em>not</em> to rotate the selected element.</p>
<h2 id="heading-what-is-the-css-scale-function">What is the CSS <code>scale()</code> Function?</h2>
<p><code>scale()</code> transforms an element by resizing (scaling) it two-dimensionally from a fixed point.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>"Transform origin" is the fixed point from which the computer scales an element.</p>
</li>
<li><p>You can define your element's fixed point using the CSS <code>transform-origin</code> property. But the default is <code>center</code>.</p>
</li>
</ul>
<h3 id="heading-syntax-of-the-css-scale-function">Syntax of the CSS <code>scale()</code> function</h3>
<p><code>scale()</code> accepts two arguments. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">element</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scale</span>(x, y);
}
</code></pre>
<p><strong>Note the following:</strong></p>
<ul>
<li><p>The <code>x</code> argument can be a number or percentage. It specifies the element's scaling factor along the x-axis.</p>
</li>
<li><p>The <code>y</code> argument can also be a number or percentage. It defines the element's scaling factor along the y-axis.</p>
</li>
<li><p>Y-axis' default value is <code>x</code>. Therefore, if you do not provide a <code>y</code> argument, the browser automatically uses <code>x</code>'s value.</p>
</li>
<li><p>Suppose <code>x</code> and <code>y</code> are equal. In that case, browsers will scale your element uniformly and preserve its aspect ratio.</p>
</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/cartesian-coordinate-system-two-dimensional-diagram-codesweetly.png" alt="Illustration of the 2D Cartesian coordinate system" width="600" height="400" loading="lazy"></p>
<p><em>A two-dimensional Cartesian coordinate system showing the X- and Y-axis</em></p>
<h3 id="heading-examples-of-the-css-scale-function">Examples of the CSS <code>scale()</code> function</h3>
<p>Below are some examples of how the CSS <code>scale()</code> function works.</p>
<h4 id="heading-how-to-scale-an-element-uniformly-along-the-x-and-y-axis-in-css">How to scale an element uniformly along the X- and Y-axis in CSS:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scale</span>(<span class="hljs-number">0.3</span>);
  <span class="hljs-attribute">transform-origin</span>: left;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-k3d6nm?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>scale()</code> function to specify a <code>0.3</code> scaling factor for the image element along the X- and Y-axis.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p><code>scale(0.3)</code> is equivalent to <code>scale(0.3, 0.3)</code>.</p>
</li>
<li><p>The percentage equivalence of <code>scale(0.3)</code> is <code>scale(30%)</code>.</p>
</li>
</ul>
<h4 id="heading-how-to-scale-an-element-non-uniformly-along-the-x-and-y-axis-in-css">How to scale an element non-uniformly along the X- and Y-axis in CSS:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scale</span>(<span class="hljs-number">0.3</span>, <span class="hljs-number">65%</span>);
  <span class="hljs-attribute">transform-origin</span>: top left;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-fxjhwb?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>scale()</code> function to specify a <code>0.3</code> scaling factor for the image along the X-axis and <code>65%</code> along the Y-axis.</p>
<h4 id="heading-how-to-scale-an-element-along-only-the-x-axis">How to scale an element along only the X-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scale</span>(<span class="hljs-number">0.3</span>, <span class="hljs-number">1</span>);
  <span class="hljs-attribute">transform-origin</span>: top left;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-7mwvto?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>scale()</code> function to specify a <code>0.3</code> scaling factor for the image along only the X-axis.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>A scale factor of <code>1</code> or <code>100%</code> tells browsers <em>not</em> to apply any scaling effect on the selected element.</p>
</li>
<li><p><code>scale(0.3, 1)</code> is equivalent to <code>scaleX(0.3)</code>.</p>
</li>
</ul>
<h4 id="heading-how-to-scale-an-element-along-only-the-y-axis">How to scale an element along only the Y-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scale</span>(<span class="hljs-number">100%</span>, <span class="hljs-number">0.2</span>);
  <span class="hljs-attribute">transform-origin</span>: top left;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-i5yrt4?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>scale()</code> function to specify a <code>0.2</code> scaling factor for the image along only the Y-axis.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>A <code>100%</code> or <code>1</code> scale factor tells browsers <em>not</em> to apply any scaling effect on the selected element.</p>
</li>
<li><p><code>scale(100%, 0.2)</code> is equivalent to <code>scaleY(0.2)</code>.</p>
</li>
</ul>
<h2 id="heading-css-scale-function-vs-scale-property-whats-the-difference">CSS <code>scale()</code> Function vs. <code>scale</code> Property: What's the Difference?</h2>
<p>The CSS <code>scale()</code> function and the CSS <code>scale</code> property provide two similar ways to specify a scale transformation.</p>
<p>The main differences between the two scaling techniques are as follows:</p>
<ul>
<li><p>The CSS <code>scale</code> property allows scaling an element without using the CSS <code>transform</code> property.</p>
</li>
<li><p>The CSS <code>scale</code> property's syntax is shorter than its function alternative.</p>
</li>
<li><p>The CSS <code>scale</code> property saves you from remembering the specific order to position the transform functions.</p>
</li>
<li><p>Browsers calculate the transform functions' matrix in the order you assigned them to the CSS <code>transform</code> property—from left to right.</p>
</li>
<li><p>Browsers calculate the transform properties' matrix in the following order:</p>
<ol>
<li><p><code>translate</code></p>
</li>
<li><p><code>rotate</code></p>
</li>
<li><p><code>scale</code></p>
</li>
</ol>
</li>
</ul>
<p><strong>Here's an example:</strong></p>
<p>Use the CSS <code>scale</code> property to scale an element nonuniformly along the X- and Y-axis.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">scale</span>: <span class="hljs-number">0.3</span> <span class="hljs-number">65%</span>; <span class="hljs-comment">/* Equal to a transform: scale(0.3, 65%) property */</span>
  <span class="hljs-attribute">transform-origin</span>: top left;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-exkib5?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>scale</code> property to specify a <code>0.3</code> scaling factor for the image along the X-axis and <code>65%</code> along the Y-axis.</p>
<p><strong>Note:</strong> A <code>none</code> value tells browsers <em>not</em> to scale the selected element.</p>
<h2 id="heading-what-is-the-css-scalez-function">What is the CSS <code>scaleZ()</code> Function?</h2>
<p><code>scaleZ()</code> transforms an element by resizing (scaling) it three-dimensionally from a fixed point along the z-axis.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>"Transform origin" is the fixed point from which the computer scales an element.</p>
</li>
<li><p>You can define your element's fixed point using the CSS <code>transform-origin</code> property. But the default is <code>center</code>.</p>
</li>
</ul>
<h3 id="heading-syntax-of-the-css-scalez-function">Syntax of the CSS <code>scaleZ()</code> function</h3>
<p><code>scaleZ()</code> accepts a single argument. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">element</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scaleZ</span>(number);
}
</code></pre>
<p><strong>Note:</strong></p>
<ul>
<li><p>The <code>scaleZ(number)</code> function is equivalent to <code>scale3d(1, 1, number)</code>.</p>
</li>
<li><p>The <code>number</code> argument specifies the element's scaling factor along the z-axis.</p>
</li>
</ul>
<h3 id="heading-examples-of-the-css-scalez-function">Examples of the CSS <code>scaleZ()</code> function</h3>
<p>We often use <code>scaleZ()</code> with other CSS functions such as <code>perspective()</code>, <code>translateZ()</code>, and <code>rotateX()</code>. Below are some examples.</p>
<h4 id="heading-how-to-use-scalez-with-css-perspective-and-rotatex-functions">How to use <code>scaleZ()</code> with CSS <code>perspective()</code> and <code>rotateX()</code> functions:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">perspective</span>(<span class="hljs-number">370px</span>) <span class="hljs-built_in">scaleZ</span>(<span class="hljs-number">5</span>) <span class="hljs-built_in">rotateX</span>(<span class="hljs-number">17deg</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-kqmccz?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li><p>We used the <code>perspective()</code> function to define a <code>370px</code> distance between the user and the <a target="_blank" href="https://codesweetly.com/css-perspective-function#what-is-the-z0-plane">z=0 plane</a>.</p>
</li>
<li><p>The <code>scaleZ()</code> function specifies a scale factor of <code>5</code> for the image along the z-axis.</p>
</li>
<li><p>We used the <code>rotateX()</code> function to rotate the image seventeen-degree (17⁰) around the x-axis.</p>
</li>
</ol>
<p><strong>Note:</strong></p>
<ul>
<li><p>List <code>perspective()</code> first whenever you chain it with other <a target="_blank" href="https://codesweetly.com/web-tech-terms-c#css-transform-functions">CSS transform functions</a>. Otherwise, browsers might transform the selected element incorrectly.</p>
</li>
<li><p>List the <code>scaleZ()</code> function before <code>rotateX()</code>. Otherwise, the browser will <em>not</em> scale the element.</p>
</li>
</ul>
<h4 id="heading-how-to-use-scalez-with-css-perspective-and-translatez-functions">How to use <code>scaleZ()</code> with CSS <code>perspective()</code> and <code>translateZ()</code> functions:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
}

<span class="hljs-selector-class">.second-image</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">perspective</span>(<span class="hljs-number">370px</span>) <span class="hljs-built_in">scaleZ</span>(<span class="hljs-number">5</span>) <span class="hljs-built_in">translateZ</span>(<span class="hljs-number">30px</span>);
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-uyw767?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li><p>We used the <code>perspective()</code> function to define a <code>370px</code> distance between the user and the z=0 plane.</p>
</li>
<li><p>The <code>scaleZ()</code> function specifies a scale factor of <code>5</code> for the image along the z-axis.</p>
</li>
<li><p>We used the <code>translateZ()</code> function to reposition the <code>second-image</code> thirty pixels (<code>30px</code>) away from its original position along the z-axis.</p>
</li>
</ol>
<h2 id="heading-what-is-the-css-scale3d-function">What is the CSS <code>scale3d()</code> Function?</h2>
<p><code>scale3d()</code> transforms an element by resizing (scaling) it three-dimensionally from a fixed point along the x-, y-, and z-axis.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>"Transform origin" is the fixed point from which the computer scales an element.</p>
</li>
<li><p>You can define your element's fixed point using the CSS <code>transform-origin</code> property. But the default is <code>center</code>.</p>
</li>
</ul>
<h3 id="heading-syntax-of-the-css-scale3d-function">Syntax of the CSS <code>scale3d()</code> function</h3>
<p><code>scale3d()</code> accepts three arguments. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">element</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scale3d</span>(x, y, z);
}
</code></pre>
<p>The <code>x</code>, <code>y</code>, and <code>z</code> arguments are numbers specifying the x-, y-, and z-coordinates. The coordinates are the axis along which browsers will scale the element.</p>
<h3 id="heading-examples-of-the-css-scale3d-function">Examples of the CSS <code>scale3d()</code> function</h3>
<p>Below are some examples of how the CSS <code>scale3d()</code> function works.</p>
<h4 id="heading-how-to-use-scale3d-with-css-perspective-and-rotatex-functions">How to use <code>scale3d()</code> with CSS <code>perspective()</code> and <code>rotateX()</code> functions:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">perspective</span>(<span class="hljs-number">370px</span>) <span class="hljs-built_in">scale3d</span>(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">5</span>) <span class="hljs-built_in">rotateX</span>(<span class="hljs-number">17deg</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-inndft?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li><p>We used the <code>perspective()</code> function to define a <code>370px</code> distance between the user and the z=0 plane.</p>
</li>
<li><p>The <code>scale3d()</code> function specifies a scale factor of <code>1</code>, <code>1</code>, and <code>5</code> for the image along the x-, y-, and z-axis.</p>
</li>
<li><p>We used the <code>rotateX()</code> function to rotate the image seventeen-degrees (17⁰) around the x-axis.</p>
</li>
</ol>
<p><strong>Note:</strong></p>
<ul>
<li><p>A scale factor of <code>1</code> will apply <em>no</em> scaling effect on the element.</p>
</li>
<li><p>List <code>perspective()</code> first whenever you chain it with other CSS transform functions. Otherwise, browsers might transform the selected element incorrectly.</p>
</li>
<li><p>List the <code>scale3d()</code> function before <code>rotateX()</code>. Otherwise, the browser will <em>not</em> scale the element.</p>
</li>
</ul>
<h4 id="heading-how-to-scale-elements-three-dimensionally">How to scale elements three-dimensionally:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
}

<span class="hljs-selector-class">.second-image</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scale3d</span>(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>, <span class="hljs-number">0.05</span>);
  <span class="hljs-attribute">transform-origin</span>: top left;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-hq8kbr?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>scale3d()</code> function to specify a scale factor of <code>5</code>, <code>3</code>, and <code>0.05</code> for the image along the x-, y-, and z-axis.</p>
<h2 id="heading-what-is-the-css-skew-function">What is the CSS <code>skew()</code> Function?</h2>
<p><code>skew()</code> transforms an element by slanting (skewing) it two-dimensionally around a fixed point.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>"Transform origin" is the fixed point from which the computer skews an element.</p>
</li>
<li><p>You can define your element's fixed point using the CSS <code>transform-origin</code> property. But the default is <code>center</code>.</p>
</li>
</ul>
<h3 id="heading-syntax-of-the-css-skew-function">Syntax of the CSS <code>skew()</code> function</h3>
<p><code>skew()</code> accepts two arguments. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">element</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">skew</span>(aX, aY);
}
</code></pre>
<p><strong>Note the following:</strong></p>
<ul>
<li><p>The <code>aX</code> argument specifies the element's skewing angle along the x-axis.</p>
</li>
<li><p>The <code>aY</code> argument specifies the element's skewing angle along the y-axis.</p>
</li>
<li><p><code>aX</code> and <code>aY</code> can be in degrees, gradians, radians, or turns.</p>
</li>
<li><p>An <code>angle</code> argument consists of a number followed by the unit you wish to use—for instance, <code>45deg</code>.</p>
</li>
<li><p><code>aY</code> is an optional argument.</p>
</li>
</ul>
<h3 id="heading-examples-of-the-css-skew-function">Examples of the CSS <code>skew()</code> function</h3>
<p>Below are some examples of how the CSS <code>skew()</code> function works.</p>
<h4 id="heading-how-to-skew-an-element-along-only-the-x-axis">How to skew an element along only the X-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">skew</span>(<span class="hljs-number">30deg</span>);
  <span class="hljs-attribute">transform-origin</span>: top;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-gx5dy4?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>skew()</code> function to apply a thirty-degree (30⁰) slant on the image along only the x-axis.</p>
<p><strong>Note:</strong> <code>skew(30deg)</code> is equivalent to <code>skewX(30deg)</code>.</p>
<h4 id="heading-how-to-skew-an-element-along-only-the-y-axis">How to skew an element along only the Y-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">skew</span>(<span class="hljs-number">0</span>, <span class="hljs-number">40deg</span>);
  <span class="hljs-attribute">transform-origin</span>: top left;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-nbkjfj?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>skew()</code> function to apply a forty-degree (40⁰) slant on the image along only the y-axis.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>A zero (<code>0</code>) skew degree tells browsers <em>not</em> to apply any skewing effect on the selected element.</p>
</li>
<li><p><code>skew(0, 40deg)</code> is equivalent to <code>skewY(40deg)</code>.</p>
</li>
</ul>
<h4 id="heading-how-to-skew-an-element-along-the-x-and-y-axis">How to skew an element along the X- and Y-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">skew</span>(<span class="hljs-number">30deg</span>, <span class="hljs-number">40deg</span>);
  <span class="hljs-attribute">transform-origin</span>: top left;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ofrk9v?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>skew()</code> function to apply a thirty-degree (30⁰) slant on the image along the x-axis. And forty-degree (40⁰) along the y-axis.</p>
<h2 id="heading-what-is-the-css-translate-function">What is the CSS <code>translate()</code> Function?</h2>
<p><code>translate()</code> transforms an element by repositioning (translating) it two-dimensionally.</p>
<h3 id="heading-syntax-of-the-css-translate-function">Syntax of the CSS <code>translate()</code> function</h3>
<p><code>translate()</code> accepts two arguments. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">element</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translate</span>(x, y);
}
</code></pre>
<p><strong>Note the following:</strong></p>
<ul>
<li><p>The <code>x</code> argument can be a length or percentage value. It specifies the distance you wish to move the element from its original x-axis position.</p>
</li>
<li><p>The <code>y</code> argument can be a length or percentage value. It defines the distance you wish to move the element from its original y-axis position.</p>
</li>
<li><p><code>y</code> is an optional argument.</p>
</li>
</ul>
<h3 id="heading-examples-of-the-css-translate-function">Examples of the CSS <code>translate()</code> function</h3>
<p>Below are some examples of how the CSS <code>translate()</code> function works.</p>
<h4 id="heading-how-to-translate-an-element-along-only-the-x-axis">How to translate an element along only the X-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translate</span>(<span class="hljs-number">150px</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-kuaqzz?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>translate()</code> function to reposition the image <code>150px</code> away from its original position along the x-axis.</p>
<p>You can also write it like this, specifying the <code>X</code>:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translateX</span>(<span class="hljs-number">150px</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>
</code></pre>
<p><strong>Note:</strong> <code>translate(150px)</code> is equivalent to <code>translateX(150px)</code>.</p>
<h4 id="heading-how-to-translate-an-element-along-only-the-y-axis">How to translate an element along only the Y-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translate</span>(<span class="hljs-number">0</span>, <span class="hljs-number">55%</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-2bchbd?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>translate()</code> function to reposition the image <code>55%</code> away from its original position along the y-axis.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>A zero (<code>0</code>) translate distance tells browsers <em>not</em> to apply any translating effect on the selected element.</p>
</li>
<li><p><code>translate(0, 55%)</code> is equivalent to <code>translateY(55%)</code>.</p>
</li>
</ul>
<h4 id="heading-how-to-translate-an-element-along-the-x-and-y-axis">How to translate an element along the X- and Y-axis:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translate</span>(<span class="hljs-number">60%</span>, <span class="hljs-number">300px</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-uwpvu4?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>translate()</code> function to reposition the image <code>60%</code> away from its original position along the x-axis and <code>300px</code> from its y-axis.</p>
<h2 id="heading-what-is-the-css-translatez-function">What is the CSS <code>translateZ()</code> Function?</h2>
<p><code>translateZ()</code> transforms an element by repositioning (translating) it three-dimensionally along the z-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/cartesian-coordinate-system-three-dimensional-diagram-codesweetly-1.png" alt="Illustration of the 3D Cartesian coordinate system" width="600" height="400" loading="lazy"></p>
<p><em>A three-dimensional Cartesian coordinate system showing the X-, Y-, and Z-axis</em></p>
<h3 id="heading-syntax-of-the-css-translatez-function">Syntax of the CSS <code>translateZ()</code> function</h3>
<p><code>translateZ()</code> accepts a single argument. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">element</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translateZ</span>(length);
}
</code></pre>
<p>The <code>length</code> argument specifies the distance you wish to move the element from its original z-axis position.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/cartesian-coordinate-system-three-dimensional-length-diagram-codesweetly.png" alt="Illustration of the CSS translateZ's length argument" width="600" height="400" loading="lazy"></p>
<p><em>A three-dimensional Cartesian coordinate system with a red arrow defining the green plane's translateZ length</em></p>
<h3 id="heading-examples-of-the-css-translatez-function">Examples of the CSS <code>translateZ()</code> function</h3>
<p>We often use <code>translateZ()</code> with the <code>perspective()</code> function. Below are some examples.</p>
<h4 id="heading-how-to-use-translatez-with-the-css-perspective-function">How to use <code>translateZ()</code> with the CSS <code>perspective()</code> function:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
}

<span class="hljs-selector-class">.second-image</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">perspective</span>(<span class="hljs-number">33px</span>) <span class="hljs-built_in">translateZ</span>(<span class="hljs-number">10px</span>);
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-hvf8bb?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li><p>We used the <code>perspective()</code> function to define a <code>33px</code> distance between the user and the <a target="_blank" href="https://codesweetly.com/css-perspective-function#what-is-the-z0-plane">z=0 plane</a>.</p>
</li>
<li><p>We used the <code>translateZ()</code> function to reposition the <code>second-image</code> ten pixels (<code>10px</code>) away from its original position along the z-axis.</p>
</li>
</ol>
<p><strong>Note:</strong></p>
<ul>
<li><p>Suppose the <code>second-image</code>'s z-axis position is larger than or equal to the <code>perspective()</code> function's <a target="_blank" href="https://codesweetly.com/javascript-arguments-vs-parameters">argument</a>. In that case, the image will disappear as though it is behind the user. In other words, the selected item disappears when the user is in the same position as the element (or when the element is behind the user).</p>
</li>
<li><p>The larger the user's distance to the element's z-axis position, the less intensive the perspective effect will be, and vice-versa.</p>
</li>
</ul>
<h4 id="heading-how-to-use-translatez-with-a-70px-perspective">How to use <code>translateZ()</code> with a <code>70px</code> perspective:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
}

<span class="hljs-selector-class">.second-image</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">perspective</span>(<span class="hljs-number">70px</span>) <span class="hljs-built_in">translateZ</span>(<span class="hljs-number">10px</span>);
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-vqd7mm?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li><p>We used the <code>perspective()</code> function to define a <code>70px</code> distance between the user and the z=0 plane.</p>
</li>
<li><p>We used the <code>translateZ()</code> function to reposition the <code>second-image</code> ten pixels (<code>10px</code>) away from its original position along the z-axis.</p>
</li>
</ol>
<h2 id="heading-what-is-the-css-translate3d-function">What is the CSS <code>translate3d()</code> Function?</h2>
<p><code>translate3d()</code> transforms an element by repositioning (translating) it three-dimensionally along the x-, y-, and z-axis.</p>
<h3 id="heading-syntax-of-the-css-translate3d-function">Syntax of the CSS <code>translate3d()</code> function</h3>
<p><code>translate3d()</code> accepts three arguments. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">element</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translate3d</span>(x, y, z);
}
</code></pre>
<p><strong>Note the following:</strong></p>
<ul>
<li><p>The <code>x</code> argument can be a length or percentage value. It specifies the distance you wish to move the element from its original x-axis position.</p>
</li>
<li><p>The <code>y</code> argument can be a length or percentage value. It defines the distance you wish to move the element from its original y-axis position.</p>
</li>
<li><p><code>z</code> can only be a length—not a percentage. It defines the distance you wish to move the element from its original z-axis position.</p>
</li>
</ul>
<h3 id="heading-examples-of-the-css-translate3d-function">Examples of the CSS <code>translate3d()</code> function</h3>
<p>Below are some examples of how the CSS <code>translate3d()</code> function works.</p>
<h4 id="heading-how-to-translate-an-element-along-only-the-x-axis-1">How to translate an element along only the X-axis</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translate3d</span>(<span class="hljs-number">150px</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-qrxxmx?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>translate3d()</code> function to reposition the image <code>150px</code> away from its original position along the x-axis.</p>
<p><strong>Note:</strong> <code>translate3d(150px, 0, 0)</code> is equivalent to <code>translateX(150px)</code>.</p>
<h4 id="heading-how-to-translate-elements-three-dimensionally">How to translate elements three-dimensionally:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
}

<span class="hljs-selector-class">.second-image</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">perspective</span>(<span class="hljs-number">300px</span>) <span class="hljs-built_in">translate3d</span>(<span class="hljs-number">15%</span>, <span class="hljs-number">45%</span>, <span class="hljs-number">200px</span>);
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-rksery?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>translate3d()</code> function to reposition the image <code>15%</code> away from its original position along the x-axis, <code>45%</code> from its y-axis, and <code>200px</code> from its z-axis.</p>
<h2 id="heading-css-translate-functions-vs-translate-property-whats-the-difference">CSS Translate Functions vs. <code>translate</code> Property: What's the Difference?</h2>
<p>The CSS translate functions and the CSS <code>translate</code> property provide two similar ways to specify a translation transformation.</p>
<p>The main differences between the two translation techniques are as follows:</p>
<ul>
<li><p>The CSS <code>translate</code> property allows translating an element without using the CSS <code>transform</code> property.</p>
</li>
<li><p>The CSS <code>translate</code> property's syntax is shorter than its function alternative.</p>
</li>
<li><p>The CSS <code>translate</code> property saves you from remembering the specific order to position the transform functions.</p>
</li>
<li><p>Browsers calculate the transform functions' matrix in the order you assigned them to the CSS <code>transform</code> property—from left to right.</p>
</li>
<li><p>Browsers calculate the transform properties' matrix in the following order:</p>
<ol>
<li><p><code>translate</code></p>
</li>
<li><p><code>rotate</code></p>
</li>
<li><p><code>scale</code></p>
</li>
</ol>
</li>
</ul>
<p>Below are some examples.</p>
<h3 id="heading-how-to-use-css-translate-property-vs-function-to-translate-an-element-along-the-x-and-y-axis">How to use CSS <code>translate</code> property vs. function to translate an element along the X- and Y-axis</h3>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">translate</span>: <span class="hljs-number">60%</span> <span class="hljs-number">300px</span>; <span class="hljs-comment">/* Equal to a transform: translate(60%, 300px) property */</span>
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-mhrmbj?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>translate</code> property to reposition the image <code>60%</code> away from its original position along the x-axis. And <code>300px</code> from its y-axis.</p>
<p><strong>Note:</strong> Suppose you wish to translate an element along the z-axis. In that case, set a <code>perspective</code> property on the "parent element" of the element you want to translate. Otherwise, the element will not move along its z-axis.</p>
<h3 id="heading-how-to-use-css-translate-property-vs-function-to-translate-an-element-along-the-z-axis">How to use CSS <code>translate</code> property vs. function to translate an element along the Z-axis</h3>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
}

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

<span class="hljs-selector-class">.second-image</span> {
  <span class="hljs-attribute">translate</span>: <span class="hljs-number">0px</span> <span class="hljs-number">0px</span> <span class="hljs-number">17px</span>; <span class="hljs-comment">/* Equal to a transform: translateZ(17px) property */</span>
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-gjr5sl?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li><p>We used the <code>perspective</code> property to define a <code>35px</code> distance between the user and the z=0 plane.</p>
</li>
<li><p>We used the <code>translate</code> property to reposition the <code>second-image</code> seventeen pixels (<code>17px</code>) away from its original position along the z-axis.</p>
</li>
</ol>
<h3 id="heading-how-to-use-css-translate-property-vs-function-to-translate-an-element-three-dimensionally">How to use CSS <code>translate</code> property vs. function to translate an element three-dimensionally</h3>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
}

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

<span class="hljs-selector-class">.second-image</span> {
  <span class="hljs-attribute">translate</span>: <span class="hljs-number">50%</span> <span class="hljs-number">25%</span> <span class="hljs-number">200px</span>; <span class="hljs-comment">/* Equal to a transform: translate3d(50%, 25%, 200px) property */</span>
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-pgqrgc?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>translate</code> property to reposition the image <code>50%</code> away from its original position along the x-axis, <code>25%</code> from its y-axis, and <code>200px</code> from its z-axis.</p>
<p><strong>Note:</strong> A <code>none</code> value tells browsers <em>not</em> to translate the selected element.</p>
<h2 id="heading-what-is-the-css-perspective-function">What is the CSS <code>perspective()</code> Function?</h2>
<p><code>perspective()</code> transforms an element by adding some perspective effects to it.</p>
<h3 id="heading-syntax-of-the-css-perspective-function">Syntax of the CSS <code>perspective()</code> function</h3>
<p><code>perspective()</code> accepts only one argument. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">element</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">perspective</span>(length);
}
</code></pre>
<p>The <code>length</code> argument specifies the user's distance to the <a target="_blank" href="https://codesweetly.com/css-perspective-function#what-is-the-z0-plane">z=0 plane</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/cartesian-coordinate-system-perspective-method-illustration-codesweetly.png" alt="Illustration of the CSS perspective() method" width="600" height="400" loading="lazy"></p>
<p><em>A three dimensional Cartesian coordinate system with a red arrow defining the distance between the user and the z=0 plane</em></p>
<h3 id="heading-examples-of-the-css-perspective-function">Examples of the CSS <code>perspective()</code> function</h3>
<p>We often use <code>perspective()</code> with other CSS functions such as <code>translateZ()</code>, <code>rotateX()</code>, and <code>rotateY()</code>. Below are some examples.</p>
<h4 id="heading-how-to-use-perspective-with-the-css-translatez-function">How to use <code>perspective()</code> with the CSS <code>translateZ()</code> function:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
}

<span class="hljs-selector-class">.second-image</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">perspective</span>(<span class="hljs-number">33px</span>) <span class="hljs-built_in">translateZ</span>(<span class="hljs-number">10px</span>);
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-hvf8bb?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li><p>We used the <code>perspective()</code> function to define a <code>33px</code> distance between the user and the z=0 plane.</p>
</li>
<li><p>We used the <code>translateZ()</code> function to reposition the <code>second-image</code> ten pixels (<code>10px</code>) away from its original position along the z-axis.</p>
</li>
</ol>
<p><strong>Note the following:</strong></p>
<ul>
<li><p>Suppose the <code>second-image</code>'s z-axis position is larger than or equal to the <code>perspective()</code> function's argument. In that case, the image will disappear as though it is behind the user. In other words, the selected item disappears when the user is in the same position as the element (or when the element is behind the user).</p>
</li>
<li><p>The larger the user's distance to the element's z-axis position, the less intensive the perspective effect will be, and vice-versa.</p>
</li>
</ul>
<h4 id="heading-how-to-use-perspective-with-the-css-rotatey-function">How to use <code>perspective()</code> with the CSS <code>rotateY()</code> function:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
}

<span class="hljs-selector-class">.second-image</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">perspective</span>(<span class="hljs-number">33px</span>) <span class="hljs-built_in">rotateY</span>(-<span class="hljs-number">10deg</span>);
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-tptutx?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li><p>We used the <code>perspective()</code> function to define a <code>33px</code> distance between the user and the z=0 plane.</p>
</li>
<li><p>We used the <code>rotateY()</code> function to rotate the <code>second-image</code> negative ten-degree (-10⁰) around the y-axis.</p>
</li>
</ol>
<h4 id="heading-how-to-use-perspective-with-the-css-rotatex-function">How to use <code>perspective()</code> with the CSS <code>rotateX()</code> function:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
}

<span class="hljs-selector-class">.second-image</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">perspective</span>(<span class="hljs-number">33px</span>) <span class="hljs-built_in">rotateX</span>(<span class="hljs-number">17deg</span>);
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-8ddydv?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li><p>We used the <code>perspective()</code> function to define a <code>33px</code> distance between the user and the z=0 plane.</p>
</li>
<li><p>We used the <code>rotateX()</code> function to rotate the <code>second-image</code> seventeen-degree (17⁰) around the x-axis.</p>
</li>
</ol>
<h2 id="heading-css-perspective-function-vs-perspective-property-whats-the-difference">CSS <code>perspective()</code> Function vs. <code>perspective</code> Property: What's the Difference?</h2>
<p>The CSS <code>perspective()</code> function and the <code>perspective</code> property provide two similar ways to add perspective effects to HTML elements.</p>
<p>The main differences between the two perspective techniques are as follows:</p>
<ul>
<li><p>We apply the <code>perspective()</code> function "directly on the element" we want to add some perspective effects to.</p>
</li>
<li><p>We apply the <code>perspective</code> property "on the parent element" of the element we want to add some perspective effects to.</p>
</li>
<li><p>The <code>perspective()</code> function works as a <code>transform</code> property's value.</p>
</li>
<li><p>The CSS <code>perspective</code> property allows you to create perspective effects without using the CSS <code>transform</code> property.</p>
</li>
</ul>
<p><strong>Here's an example:</strong></p>
<p>Use CSS <code>perspective</code> property to add perspective effect to a child element:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40%</span>;
}

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

<span class="hljs-selector-class">.second-image</span> {
  <span class="hljs-attribute">rotate</span>: x <span class="hljs-number">17deg</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-psssbh?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Here's what we did in the snippet above:</p>
<ol>
<li><p>We used the <code>perspective</code> property to define a <code>33px</code> distance between the user and the z=0 plane.</p>
</li>
<li><p>We used the <code>rotate</code> property to rotate the <code>second-image</code> seventeen-degree (17⁰) around the x-axis.</p>
</li>
</ol>
<p><strong>Note:</strong></p>
<ul>
<li><p>The CSS <code>perspective</code> property saves you from remembering the specific order to position the transform functions.</p>
</li>
<li><p>A <code>none</code> value tells browsers <em>not</em> to add any perspective effect to the selected element's children.</p>
</li>
</ul>
<h2 id="heading-what-is-the-css-matrix-function">What is the CSS <code>matrix()</code> Function?</h2>
<p>The CSS <code>matrix()</code> function is a shorthand for the following 2D transform functions:</p>
<ul>
<li><p><code>scaleX()</code></p>
</li>
<li><p><code>skewY()</code></p>
</li>
<li><p><code>skewX()</code></p>
</li>
<li><p><code>scaleY()</code></p>
</li>
<li><p><code>translateX()</code></p>
</li>
<li><p><code>translateY()</code></p>
</li>
</ul>
<p>In other words, instead of writing:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform-origin</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translateX</span>(<span class="hljs-number">100px</span>) <span class="hljs-built_in">translateY</span>(<span class="hljs-number">250px</span>) <span class="hljs-built_in">scaleX</span>(<span class="hljs-number">2</span>) <span class="hljs-built_in">scaleY</span>(<span class="hljs-number">0.9</span>)
    <span class="hljs-built_in">skewX</span>(<span class="hljs-number">10deg</span>) <span class="hljs-built_in">skewY</span>(<span class="hljs-number">35deg</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-jquhyy?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>You can alternatively use the <code>matrix()</code> function to shorten your code like so:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform-origin</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">matrix</span>(<span class="hljs-number">2.24693</span>, <span class="hljs-number">0.630187</span>, <span class="hljs-number">0.352654</span>, <span class="hljs-number">0.9</span>, <span class="hljs-number">100</span>, <span class="hljs-number">250</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-zzlwhn?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<h3 id="heading-the-css-matrix-functions-syntax">The CSS <code>matrix()</code> function's syntax</h3>
<p>The <code>matrix()</code> function accepts six values. Here's the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">matrix</span>(<span class="hljs-selector-tag">scaleX</span>(), <span class="hljs-selector-tag">skewY</span>(), <span class="hljs-selector-tag">skewX</span>(), <span class="hljs-selector-tag">scaleY</span>(), <span class="hljs-selector-tag">translateX</span>(), <span class="hljs-selector-tag">translateY</span>())
</code></pre>
<p>You can represent the CSS matrix's values as <a target="_blank" href="https://en.wikipedia.org/wiki/Homogeneous_coordinates">homogeneous coordinates</a> on <a target="_blank" href="https://en.wikipedia.org/wiki/Real_projective_space">ℝℙ<sup>2</sup></a> like so:</p>
<pre><code class="lang-txt">| scX skX tX | ← x-axis
| skY scY tY | ← y-axis
|  0   0   1 | ← constants
</code></pre>
<p><strong>Note the following:</strong></p>
<ul>
<li><p><code>scX</code> and <code>skX</code> are numbers describing an element's scale and skew linear transformation on the x-axis.</p>
</li>
<li><p><code>tX</code> is a number representing an element's translation on the x-axis.</p>
</li>
<li><p><code>skY</code> and <code>scY</code> are numbers describing an element's skew and scale linear transformation on the y-axis.</p>
</li>
<li><p><code>tY</code> is a number representing an element's translation on the y-axis.</p>
</li>
<li><p><code>0</code>, <code>0</code>, <code>1</code> are constants.</p>
</li>
<li><p>We do not pass the constants as <a target="_blank" href="https://codesweetly.com/javascript-arguments-vs-parameters">arguments</a> to the <code>matrix()</code> function because the computer implies them automatically.</p>
</li>
</ul>
<h3 id="heading-examples-of-the-css-matrix-function">Examples of the CSS <code>matrix()</code> function</h3>
<p>Below are some examples of the CSS <code>matrix()</code> function.</p>
<h4 id="heading-how-to-convert-scalex-to-matrix-function">How to convert <code>scaleX()</code> to <code>matrix()</code> function:</h4>
<p>Consider the following <code>transform</code> property:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform-origin</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scaleX</span>(<span class="hljs-number">2</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-9r2euo?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Here is the <code>matrix()</code> equivalent of the above <code>scaleX()</code> function:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform-origin</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">matrix</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>); <span class="hljs-comment">/* scX, skY, skX, scY, tX, tY */</span>
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-bypfbf?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Let's also represent the matrix's values as homogeneous coordinates on ℝℙ<sup>2</sup>:</p>
<pre><code class="lang-txt">| 2 0 0 | ← x-axis
| 0 1 0 | ← y-axis
| 0 0 1 | ← constants
</code></pre>
<p>Below is another example.</p>
<h4 id="heading-how-to-convert-translatey-to-matrix-function">How to convert <code>translateY()</code> to <code>matrix()</code> function:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform-origin</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translateY</span>(<span class="hljs-number">250px</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-w25f3w?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Here is the <code>matrix()</code> equivalent of the above <code>translateY()</code> function:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform-origin</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">matrix</span>(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">250</span>); <span class="hljs-comment">/* scX, skY, skX, scY, tX, tY */</span>
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-1coxrt?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Let's also represent the matrix's values as homogeneous coordinates on ℝℙ<sup>2</sup>:</p>
<pre><code class="lang-txt">| 1 0 0   | ← x-axis
| 0 1 250 | ← y-axis
| 0 0 1   | ← constants
</code></pre>
<p>Below is a third example.</p>
<h4 id="heading-how-to-convert-translatex-and-scale-to-matrix-function">How to convert <code>translateX()</code> and <code>scale()</code> to <code>matrix()</code> function:</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform-origin</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translateX</span>(<span class="hljs-number">100px</span>) <span class="hljs-built_in">scale</span>(<span class="hljs-number">2</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-wje2fa?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Here is the syntax for converting the above <code>transform</code> property's value to <code>matrix()</code>:</p>
<pre><code class="lang-txt">matrix = (translateX's homogeneous coordinates) x (scale's homogeneous coordinates)
</code></pre>
<p>Let's begin the conversion by defining <code>translateX(100px)</code>'s homogeneous coordinates:</p>
<pre><code class="lang-txt">| 1 0 100 | ← x-axis
| 0 1 0   | ← y-axis
| 0 0 1   | ← constants
</code></pre>
<p>Let's also define <code>scale(2)</code>'s homogeneous coordinates:</p>
<pre><code class="lang-txt">| 2 0 0 | ← x-axis
| 0 2 0 | ← y-axis
| 0 0 1 | ← constants
</code></pre>
<p>It's now time to multiply the two homogeneous coordinates by using the following syntax:</p>
<pre><code class="lang-txt">| a d g |   | j m p |   | aj + dk + gl   am + dn + go   ap +dq  + gr |
| b e h | x | k n q | = | bj + ek + hl   bm + en + ho   bp + eq + hr |
| c f i |   | l o r |   | cj + fk + il   cm + fn + io   cp + fq + ir |
</code></pre>
<p>Let's implement the above syntax like so:</p>
<pre><code class="lang-txt">| 1 0 100 |   | 2 0 0 |   | 2 + 0 + 0   0 + 0 + 0   0 + 0 + 100 |
| 0 1  0  | x | 0 2 0 | = | 0 + 0 + 0   0 + 2 + 0   0 + 0 +  0  |
| 0 0  1  |   | 0 0 1 |   | 0 + 0 + 0   0 + 0 + 0   0 + 0 +  1  |
</code></pre>
<p>The next step is to resolve the addition. So, let's do that now.</p>
<pre><code class="lang-txt">| 1 0 100 |   | 2 0 0 |   | 2 0 100 |
| 0 1  0  | x | 0 2 0 | = | 0 2  0  |
| 0 0  1  |   | 0 0 1 |   | 0 0  1  |
</code></pre>
<p>The addition's result above gives us the homogeneous coordinates of the <code>transform: translateX(100px) scale(2)</code> property.</p>
<p>In other words, the product of <code>(translateX's homogeneous coordinates)</code> and <code>(scale's homogeneous coordinates)</code> equal:</p>
<pre><code class="lang-txt">| 2 0 100 | ← x-axis
| 0 2  0  | ← y-axis
| 0 0  1  | ← constants
</code></pre>
<p>Therefore, the matrix equivalence of <code>transform: translateX(100px) scale(2)</code> is <code>transform: matrix(2, 0, 0, 2, 100, 0)</code>.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform-origin</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">matrix</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">100</span>, <span class="hljs-number">0</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-njrg4k?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Please note that <code>transform: translateX(100px) scale(2)</code> and <code>transform: scale(2) translateX(100px)</code> return different matrixes. Let's see an example of the second arrangement below.</p>
<h4 id="heading-how-to-convert-scale-and-translatex-to-matrix-function">How to convert <code>scale()</code> and <code>translateX()</code> to <code>matrix()</code> function:</h4>
<p>Consider the following <code>transform</code> property:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform-origin</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scale</span>(<span class="hljs-number">2</span>) <span class="hljs-built_in">translateX</span>(<span class="hljs-number">100px</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-39trog?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Here is the syntax for converting the above <code>transform</code> property's value to <code>matrix()</code>:</p>
<pre><code class="lang-txt">matrix = (scale's homogeneous coordinates) x (translateX's homogeneous coordinates)
</code></pre>
<p>Let's begin the conversion by defining <code>scale(2)</code>'s homogeneous coordinates:</p>
<pre><code class="lang-txt">| 2 0 0 | ← x-axis
| 0 2 0 | ← y-axis
| 0 0 1 | ← constants
</code></pre>
<p>Let's also define <code>translateX(100px)</code>'s homogeneous coordinates:</p>
<pre><code class="lang-txt">| 1 0 100 | ← x-axis
| 0 1  0  | ← y-axis
| 0 0  1  | ← constants
</code></pre>
<p>It's now time to multiply the two homogeneous coordinates by using the following syntax:</p>
<pre><code class="lang-txt">| a d g |   | j m p |   | aj + dk + gl   am + dn + go   ap +dq  + gr |
| b e h | x | k n q | = | bj + ek + hl   bm + en + ho   bp + eq + hr |
| c f i |   | l o r |   | cj + fk + il   cm + fn + io   cp + fq + ir |
</code></pre>
<p>Let's implement the above syntax like so:</p>
<pre><code class="lang-txt">| 2 0 0 |   | 1 0 100 |   | 2 + 0 + 0   0 + 0 + 0   200 + 0 + 0 |
| 0 2 0 | x | 0 1  0  | = | 0 + 0 + 0   0 + 2 + 0    0 + 0 + 0  |
| 0 0 1 |   | 0 0  1  |   | 0 + 0 + 0   0 + 0 + 0    0 + 0 + 1  |
</code></pre>
<p>The next step is to resolve the addition. So, let's do that now.</p>
<pre><code class="lang-txt">| 2 0 0 |   | 1 0 100 |   | 2 0 200 |
| 0 2 0 | x | 0 1  0  | = | 0 2  0  |
| 0 0 1 |   | 0 0  1  |   | 0 0  1  |
</code></pre>
<p>The addition's result above gives us the homogeneous coordinates of the <code>transform: scale(2) translateX(100px)</code> property.</p>
<p>In other words, the product of <code>(scale's homogeneous coordinates)</code> and <code>(translateX's homogeneous coordinates)</code> equal:</p>
<pre><code class="lang-txt">| 2 0 200 | ← x-axis
| 0 2  0  | ← y-axis
| 0 0  1  | ← constants
</code></pre>
<p>Therefore, the matrix equivalence of <code>transform: scale(2) translateX(100px)</code> is <code>transform: matrix(2, 0, 0, 2, 200, 0)</code>.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform-origin</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">matrix</span>(<span class="hljs-number">2</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">200</span>, <span class="hljs-number">0</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-3m4vgk?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>Notice that <code>transform: scale(2) translateX(100px)</code> equals <code>transform: matrix(2, 0, 0, 2, 200, 0)</code>. And <code>transform: translateX(100px) scale(2)</code> is equivalent to <code>transform: matrix(2, 0, 0, 2, 100, 0)</code>.</p>
<p>In other words, the order in which you write the transform functions matters. Let's discuss more on this below.</p>
<h2 id="heading-why-does-the-css-transform-functions-order-matter">Why Does the CSS Transform Functions' Order Matter?</h2>
<p>The order in which you write <a target="_blank" href="https://codesweetly.com/web-tech-terms-c#css-transform-functions">CSS transform functions</a> matters because of the way browsers calculate the matrix's values.</p>
<p>For instance, consider the following snippet:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">position</span>: absolute;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100px</span>;
  <span class="hljs-attribute">transform-origin</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
}

<span class="hljs-selector-class">.red</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">3px</span> solid red;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgba</span>(<span class="hljs-number">255</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.5</span>);
}

<span class="hljs-selector-class">.green</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">3px</span> solid green;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">128</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.5</span>);
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">translateX</span>(<span class="hljs-number">100px</span>) <span class="hljs-built_in">scale</span>(<span class="hljs-number">2</span>);
}

<span class="hljs-selector-class">.blue</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">3px</span> solid blue;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">255</span>, <span class="hljs-number">0.5</span>);
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scale</span>(<span class="hljs-number">2</span>) <span class="hljs-built_in">translateX</span>(<span class="hljs-number">100px</span>);
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-rvkagy?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The only difference between the green and the blue <code>div</code>s is the order in which we wrote their transform functions.</p>
<p>However, the computer translated the two containers using different values (<code>100px</code> for the green <code>div</code> and <code>200px</code> for the blue one).</p>
<p>So, why did the transform functions' order affect the <code>div</code>s' translation values? Here's the reason:</p>
<ul>
<li>Browsers multiply each transform function's homogeneous coordinates in order—from left to right.</li>
</ul>
<p>In other words, the computer used the following syntax to compute the green <code>div</code>'s matrix:</p>
<ul>
<li><a class="post-section-overview" href="#how-to-convert-translatex-and-scale-to-matrix-function">Green <code>div</code>'s matrix</a> = (translateX's homogeneous coordinates) x (scale's homogeneous coordinates)</li>
</ul>
<p>And it used the following syntax to calculate the blue <code>div</code>'s matrix:</p>
<ul>
<li><a class="post-section-overview" href="#how-to-convert-scale-and-translatex-to-matrix-function">Blue <code>div</code>'s matrix</a> = (scale's homogeneous coordinates) x (translateX's homogeneous coordinates)</li>
</ul>
<p>Therefore, the position of the transform functions determined the matrix's <a target="_blank" href="https://codesweetly.com/javascript-arguments-vs-parameters">arguments</a> because browsers began the calculation in order from the leftmost function to the right.</p>
<p>Knowing how to convert transform functions to <code>matrix()</code> is beneficial. And having some conversion tools can come in handy. So, let's discuss some helpful tools you can use.</p>
<h2 id="heading-tools-for-converting-transform-functions-to-matrix">Tools for Converting Transform Functions to <code>matrix()</code></h2>
<p>The two tools you can use to do a quick conversion of transform functions to <code>matrix()</code> are:</p>
<ul>
<li><p>JavaScript's <code>window.getComputedStyle()</code> method</p>
</li>
<li><p>Eric Meyer and Aaron Gustafson's matrix resolution tool</p>
</li>
</ul>
<h3 id="heading-how-to-use-windowgetcomputedstyle-to-convert-transform-functions-to-matrix">How to use <code>window.getComputedStyle()</code> to convert transform functions to <code>matrix()</code></h3>
<p>Suppose you want to convert the following transform functions to matrix:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform-origin</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scale</span>(<span class="hljs-number">2</span>) <span class="hljs-built_in">translateX</span>(<span class="hljs-number">100px</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p>You will add an <code>id</code> attribute to the image element:</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">"https://cdn.pixabay.com/photo/2022/09/26/23/26/african-american-7481724_960_720.jpg"</span>
  <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span>
  <span class="hljs-attr">id</span>=<span class="hljs-string">"image"</span>
/&gt;</span>
</code></pre>
<p>Then, in JavaScript, you will:</p>
<ol>
<li><p>Use the <code>id</code> attribute to get the image element.</p>
</li>
<li><p>Use the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle"><code>window.getComputedStyle()</code></a> method to get the image's <code>transform</code> property's value.</p>
</li>
</ol>
<p><strong>Here's the code:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Get the image element by its id name:</span>
<span class="hljs-keyword">const</span> image = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"image"</span>);

<span class="hljs-comment">// Get the image element's transform property's value:</span>
<span class="hljs-keyword">const</span> matrix = <span class="hljs-built_in">window</span>.getComputedStyle(image).getPropertyValue(<span class="hljs-string">"transform"</span>);

<span class="hljs-comment">// Log the matrix variable's value to the console:</span>
<span class="hljs-built_in">console</span>.log(matrix);
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-39trog?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Browsers, by default, convert a CSS <code>transform</code> property's value to its matrix equivalent. So, the snippet above returned the image's computed value.</p>
<p>Let's now discuss the second conversion tool.</p>
<h3 id="heading-how-to-use-the-matrix-resolutions-tool-to-convert-transform-functions-to-matrix">How to use the matrix resolutions tool to convert transform functions to <code>matrix()</code></h3>
<p>Suppose you want to convert the following transform functions to a <code>matrix()</code>:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">transform-origin</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scale</span>(<span class="hljs-number">2</span>) <span class="hljs-built_in">translateX</span>(<span class="hljs-number">100px</span>);
  <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
}
</code></pre>
<p>You will do the following:</p>
<ol>
<li><p>Go to The Matrix Resolutions website: <a target="_blank" href="https://meyerweb.com/eric/tools/matrix/">https://meyerweb.com/eric/tools/matrix/</a>.</p>
</li>
<li><p>Paste your transform functions (<code>scale(2) translateX(100px)</code>) into the first text field.</p>
</li>
<li><p>Click "The Red Pill" button to generate the transform functions' matrix equivalence.</p>
</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/06/how-to-use-the-matrix-resolutions-tool-codesweetly.jpg" alt="The matrix resolutions tool's screenshot" width="600" height="400" loading="lazy"></p>
<p><em>Click the red pill button to convert CSS transform functions to a matrix() function</em></p>
<p><strong>Tip:</strong> Use <a target="_blank" href="https://codesweetly.com/css-matrix3d-function">matrix3d()</a> to create a 3D transformation matrix.</p>
<h2 id="heading-important-stuff-to-know-about-transforming-elements-in-css">Important Stuff to Know about Transforming Elements in CSS</h2>
<p>Here are three essential facts to remember when you transform elements in CSS.</p>
<h3 id="heading-1-transform-creates-a-stacking-context">1. Transform creates a stacking context</h3>
<p>Suppose you set the <code>transform</code> property to any value other than <code>none</code>. In that case, the browser will create a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context">stacking context</a>. And the transformed element will serve as a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block">containing block</a> to any <a target="_blank" href="https://codesweetly.com/css-position-property#what-is-position-absolute-in-css">absolute</a> or <a target="_blank" href="https://codesweetly.com/css-position-property#what-is-position-fixed-in-css">fixed</a> positioned elements it contains.</p>
<h3 id="heading-2-scaling-and-zooming-animations-cause-accessibility-issues">2. Scaling and zooming animations cause accessibility issues</h3>
<p>Whenever you include scaling or zooming animations in your app, provide users an option to turn off animations. This option is necessary because scaling and zooming animations cause <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/transform#accessibility_concerns">accessibility issues</a>.</p>
<h3 id="heading-3-not-all-elements-are-transformable">3. Not all elements are transformable</h3>
<p>You cannot transform the following <a target="_blank" href="https://codesweetly.com/css-box-model">box models</a>:</p>
<ul>
<li><p><a target="_blank" href="https://codesweetly.com/css-transform-property#non-replaced-vs-replaced-elements-whats-the-difference">Non-replaced</a> inline elements</p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/col">table-column</a> boxes</p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/colgroup">table-column-group</a></p>
</li>
</ul>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this article, we discussed all the CSS transform tools you need to translate, rotate, skew, scale, or add perspective effects to HTML elements.</p>
<p>I hope you've found this article helpful.</p>
<h3 id="heading-thanks-for-reading">Thanks for reading!</h3>
<p>If you like this tutorial, you will enjoy my <a target="_blank" href="https://amzn.to/3N3XUws">CSS Flexbox book</a>. It is a handy quick reference guide that uses images and live examples to explain Flexbox.</p>
<p><a target="_blank" href="https://amzn.to/3N3XUws"><img src="https://www.freecodecamp.org/news/content/images/2023/06/css-flexbox-book-get-banner-codesweetly.png" alt="Get CodeSweetly's CSS Flexbox book at Amazon" width="600" height="400" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ CSS Grid Handbook – Complete Guide to Grid Containers and Grid Items ]]>
                </title>
                <description>
                    <![CDATA[ CSS Grid gives you the tools to create basic and advanced website layouts in responsive ways that look great on mobile, tablet, and desktop devices. This tutorial discusses everything you need to know to use CSS Grid like a pro. Table of Contents Wh... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/complete-guide-to-css-grid/</link>
                <guid isPermaLink="false">66ba0ddfc003a1736007f49a</guid>
                
                    <category>
                        <![CDATA[ CSS Grid ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ responsive design ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Thu, 16 Mar 2023 18:19:27 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738338779416/5e58d695-6840-40da-84bc-c2b2428c16db.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>CSS Grid gives you the tools to create basic and advanced website layouts in responsive ways that look great on mobile, tablet, and desktop devices.</p>
<p>This tutorial discusses everything you need to know to use CSS Grid like a pro.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grid">What Is CSS Grid?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-grid-container-vs-grid-item-whats-the-difference">Grid Container vs. Grid Item: What's the Difference?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-grid-value-in-css">What Is a <code>grid</code> Value in CSS?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-an-inline-grid-value-in-css">What Is an <code>inline-grid</code> Value in CSS?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-properties-for-specifying-a-grids-layout">Properties for Specifying a Grid's Layout</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-the-grid-containers-properties">What Are the Grid Container's Properties?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-grid-template-columns-property">What Is CSS Grid's <code>grid-template-columns</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-grid-template-rows-property">What Is CSS Grid's <code>grid-template-rows</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-justify-content-property">What Is CSS Grid's <code>justify-content</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-justify-items-property">What Is CSS Grid's <code>justify-items</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-align-content-property">What Is CSS Grid's <code>align-content</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-align-items-property">What Is CSS Grid's <code>align-items</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-are-the-grid-items-properties">What Are the Grid Item's Properties?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-justify-self-property">What Is CSS Grid's <code>justify-self</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-align-self-property">What Is CSS Grid's <code>align-self</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-grid-column-start-property">What Is CSS Grid's <code>grid-column-start</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-grid-column-end-property">What Is CSS Grid's <code>grid-column-end</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-grid-column-property">What Is CSS Grid's <code>grid-column</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-grid-row-start-property">What Is CSS Grid's <code>grid-row-start</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-grid-row-end-property">What Is CSS Grid's <code>grid-row-end</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-grid-row-property">What Is CSS Grid's <code>grid-row</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-grid-area-property">What Is CSS Grid's <code>grid-area</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-css-grids-grid-template-areas-property">What Is CSS Grid's <code>grid-template-areas</code> Property?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-the-css-minmax-function-to-define-minimum-and-maximum-grid-sizes">How to Use the CSS <code>minmax()</code> function to Define Minimum and Maximum Grid Sizes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-the-css-repeat-function-to-define-grid-tracks-with-repeated-patterns">How to Use the CSS <code>repeat()</code> Function to Define Grid Tracks with Repeated Patterns</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-overview">Overview</a></p>
</li>
</ol>
<p>So, without any further ado, let's understand what CSS Grid is.</p>
<h2 id="heading-what-is-css-grid">What is CSS Grid?</h2>
<p>The CSS Grid Layout Module makes browsers display the selected HTML elements as grid <a target="_blank" href="https://codesweetly.com/css-box-model">box models</a>.</p>
<p>Grid allows you to easily resize and reposition a grid container and its items two-dimensionally.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>"Two-dimensionally" means grid modules allow simultaneous laying out of box models in rows and columns.</p>
</li>
<li><p>Use <a target="_blank" href="https://codesweetly.com/css-flexbox-explained">Flexbox</a> if you only need to resize and reposition elements one-dimensionally.</p>
</li>
</ul>
<h2 id="heading-grid-container-vs-grid-item-whats-the-difference">Grid Container vs. Grid Item: What's the Difference?</h2>
<p>A <strong>grid container</strong> is an <a target="_blank" href="https://codesweetly.com/web-tech-terms-h#html-element">HTML element</a> whose <a target="_blank" href="https://codesweetly.com/css-display-property"><code>display</code></a> property's value is <code>grid</code> or <code>inline-grid</code>.</p>
<p>A <strong>grid item</strong> is any of the direct children of a grid container.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-container-grid-item-illustration-codesweetly.png" alt="Illustration of a grid container and a grid item" width="600" height="400" loading="lazy"></p>
<p><em>A grid container (the large yellow area in the image) is an HTML element whose display property's value is grid or inline-grid. Grid items (the smaller boxes within the yellow container) are the direct children of a grid container.</em></p>
<h2 id="heading-what-is-a-grid-value-in-css">What Is a <code>grid</code> Value in CSS?</h2>
<p><code>grid</code> tells browsers to display the selected HTML element as a block-level grid box model.</p>
<p>In other words, setting an element's <code>display</code> property's value to <code>grid</code> turns the box model into a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements">block-level</a> grid layout module.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-5ggr6k?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>grid</code> value to convert the HTML document's <code>&lt;section&gt;</code> elements from regular <code>&lt;section&gt;</code> nodes to block-level grid box models.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>The <code>display: grid</code> directive creates only a single-column grid container. Therefore, the grid items will display in the normal layout flow (one item below another).</p>
</li>
<li><p>Converting a node to a grid box model makes the element's direct children become grid items.</p>
</li>
<li><p>The <code>display: grid</code> directive only affects a box model and its direct children. It does not affect grandchildren nodes.</p>
</li>
</ul>
<p>Let's now discuss the <code>inline-grid</code> value.</p>
<h2 id="heading-what-is-an-inline-grid-value-in-css">What Is an <code>inline-grid</code> Value in CSS?</h2>
<p><code>inline-grid</code> tells browsers to display the selected HTML element as an inline-level grid box model.</p>
<p>In other words, setting an element's <code>display</code> property's value to <code>inline-grid</code> turns the box model into an <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements">inline-level</a> grid layout module.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: inline-grid;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ekpbac?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>inline-grid</code> value to convert the HTML document's <code>&lt;section&gt;</code> elements from regular <code>&lt;section&gt;</code> nodes to inline-level grid box models.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>Converting a node to a grid box model makes the element's direct children become grid items.</p>
</li>
<li><p>The <code>display: inline-grid</code> directive only affects a box model and its direct children. It does not affect grandchildren nodes.</p>
</li>
</ul>
<h2 id="heading-properties-for-specifying-a-grids-layout">Properties for Specifying a Grid's Layout</h2>
<p>On converting a regular HTML element to a grid (or inline-grid) box model, the grid layout module provides two categories of properties for positioning the grid box and its direct children:</p>
<ul>
<li><p>Grid container's properties</p>
</li>
<li><p>Grid item's properties</p>
</li>
</ul>
<h2 id="heading-what-are-the-grid-containers-properties">What Are the Grid Container's Properties?</h2>
<p>A grid container's properties specify how browsers should layout items within the grid box model.</p>
<p><strong>Note:</strong> We define a grid container's property on the container, not its items.</p>
<p>The eight (8) types of grid container properties are:</p>
<ul>
<li><p><code>grid-template-columns</code></p>
</li>
<li><p><code>grid-template-rows</code></p>
</li>
<li><p><code>grid-auto-columns</code></p>
</li>
<li><p><code>grid-auto-rows</code></p>
</li>
<li><p><code>justify-content</code></p>
</li>
<li><p><code>justify-items</code></p>
</li>
<li><p><code>align-content</code></p>
</li>
<li><p><code>align-items</code></p>
</li>
</ul>
<p>Let's discuss the eight types now.</p>
<h2 id="heading-what-is-css-grids-grid-template-columns-property">What Is CSS Grid's <code>grid-template-columns</code> Property?</h2>
<p><strong>grid-template-columns</strong> specifies the number and widths of columns browsers should display in the selected grid container.</p>
<h3 id="heading-example-1-how-to-create-a-two-column-grid-container">Example 1: How to create a two-column grid container</h3>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">95px</span> <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-uwtgsf?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>grid-template-columns</code> property to display two columns of different widths in the selected <code>&lt;section&gt;</code> grid container.</p>
<p><strong>Note:</strong> We used the <a target="_blank" href="https://codesweetly.com/css-unit#fraction-fr"><code>fr</code> (fraction) unit</a> to scale the second column relative to the fraction of available space in the grid container.</p>
<h3 id="heading-example-2-how-to-create-a-three-column-grid-container">Example 2: How to create a three-column grid container</h3>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">15%</span> <span class="hljs-number">60%</span> <span class="hljs-number">25%</span>;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-xaop69?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>grid-template-columns</code> property to display three columns of different widths in the selected <code>&lt;section&gt;</code> grid container.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>You can use the <code>grid-auto-columns</code> property to specify default column widths for all the grid container's columns. For instance, <code>grid-auto-columns: 150px</code> will set default widths of <code>150px</code> for all columns. But a <code>grid-template-columns</code> declaration will override it.</p>
</li>
<li><p>Explicit grid columns are the columns you explicitly define with the <code>grid-template-columns</code> property.</p>
</li>
<li><p>Implicit grid columns are the columns browsers create automatically. We use the <code>grid-auto-columns</code> properties to specify <a target="_blank" href="https://codesweetly.com/css-grid-lines-explained">track</a> sizes for implicit columns.</p>
</li>
</ul>
<p><strong>Tip:</strong></p>
<ul>
<li><p>Use the CSS <code>repeat()</code> function to specify <code>grid-template-columns</code> values with repeated patterns. We will discuss the <code>repeat()</code> function later in this tutorial.</p>
</li>
<li><p>Use the <a target="_blank" href="https://codesweetly.com/css-column-gap-property">CSS <code>column-gap</code> property</a> to create gaps between grid columns.</p>
</li>
</ul>
<h2 id="heading-what-is-css-grids-grid-template-rows-property">What Is CSS Grid's <code>grid-template-rows</code> Property?</h2>
<p><strong>grid-template-rows</strong> specifies the number and heights of rows browsers should display in the selected grid container.</p>
<h3 id="heading-example-1-how-to-create-a-three-row-grid-container">Example 1: How to create a three-row grid container</h3>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-rows</span>: <span class="hljs-number">95px</span> <span class="hljs-number">1</span>fr <span class="hljs-number">70px</span>;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-tbisxm?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>grid-template-rows</code> property to display three rows of different heights in the selected <code>&lt;section&gt;</code> grid container.</p>
<p><strong>Note:</strong> We used the <a target="_blank" href="https://codesweetly.com/css-unit#fraction-fr"><code>fr</code> (fraction) unit</a> to scale the second row relative to the fraction of available space in the grid container.</p>
<h3 id="heading-example-2-how-to-create-a-three-row-and-four-column-grid-container">Example 2: How to create a three-row and four-column grid container</h3>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-rows</span>: <span class="hljs-number">90px</span> <span class="hljs-number">300px</span> <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">grid-template-columns</span>: auto auto auto auto;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-e5vtot?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>grid-template-rows</code> property to display three columns of different heights in the selected <code>&lt;section&gt;</code> grid container.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>You can use the <code>grid-auto-rows</code> property to specify default row heights for all the grid container's rows. For instance, <code>grid-auto-rows: 100px</code> will set default heights of <code>100px</code> for all rows. But a <code>grid-template-rows</code> declaration will override it.</p>
</li>
<li><p>Explicit grid rows are the rows you explicitly define with the <code>grid-template-rows</code> property.</p>
</li>
<li><p>Implicit grid rows are the rows browsers create automatically. We use the <code>grid-auto-rows</code> properties to specify <a target="_blank" href="https://codesweetly.com/css-grid-lines-explained">track</a> sizes for implicit rows.</p>
</li>
</ul>
<p><strong>Tip:</strong></p>
<ul>
<li><p>Use the CSS <code>repeat()</code> function to specify <code>grid-template-rows</code> values with repeated patterns. We will discuss the <code>repeat()</code> function later in this tutorial.</p>
</li>
<li><p>Use the <a target="_blank" href="https://codesweetly.com/css-row-gap-property">CSS <code>row-gap</code> property</a> to create gaps between grid rows.</p>
</li>
</ul>
<h2 id="heading-what-is-css-grids-justify-content-property">What Is CSS Grid's <code>justify-content</code> Property?</h2>
<p><strong>justify-content</strong> specifies how browsers should position a grid container's columns along its row axis.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>A row axis is sometimes called an inline axis.</p>
</li>
<li><p>The <code>justify-content</code> property works if the total column widths are less than the grid container's width. In other words, you need free space along the container's row axis to justify its columns left or right.</p>
</li>
</ul>
<p>The <code>justify-content</code> property accepts the following values:</p>
<ul>
<li><p><code>start</code></p>
</li>
<li><p><code>center</code></p>
</li>
<li><p><code>end</code></p>
</li>
<li><p><code>stretch</code></p>
</li>
<li><p><code>space-between</code></p>
</li>
<li><p><code>space-around</code></p>
</li>
<li><p><code>space-evenly</code></p>
</li>
</ul>
<p>Let's discuss these values.</p>
<h3 id="heading-what-is-justify-content-start-in-css-grid">What is <code>justify-content: start</code> in CSS Grid?</h3>
<p><code>start</code> positions the grid container's columns with its row-start edge.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-justify-content-start-illustration-codesweetly.png" alt="Illustration of justify-content's start value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>justify-content's start value positions columns to the grid container's row-start edge</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">justify-content</span>: start;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">repeat</span>(<span class="hljs-number">4</span>, <span class="hljs-number">40px</span>);
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-rkwg9r?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>start</code> value to position the <code>&lt;section&gt;</code>'s columns to the grid container's row-start edge.</p>
<h3 id="heading-what-is-justify-content-center-in-css-grid">What is <code>justify-content: center</code> in CSS Grid?</h3>
<p><code>center</code> positions the grid container's columns to the center of the grid's row axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-justify-content-center-illustration-codesweetly.png" alt="Illustration of justify-content's center value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>justify-content's center value positions columns to the center of the grid container</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">repeat</span>(<span class="hljs-number">4</span>, <span class="hljs-number">40px</span>);
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ft8n3n?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>center</code> value to position the <code>&lt;section&gt;</code>'s columns to the center of the grid container.</p>
<h3 id="heading-what-is-justify-content-end-in-css-grid">What is <code>justify-content: end</code> in CSS Grid?</h3>
<p><code>end</code> positions a grid container's columns with its row-end edge.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-justify-content-end-illustration-codesweetly.png" alt="Illustration of justify-content's end value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>justify-content's end value positions columns to the grid container's row-end edge</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">justify-content</span>: end;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">repeat</span>(<span class="hljs-number">4</span>, <span class="hljs-number">40px</span>);
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-zzaxjf?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>end</code> value to position the <code>&lt;section&gt;</code>'s columns to the grid container's row-end edge.</p>
<h3 id="heading-what-is-justify-content-space-between-in-css-grid">What is <code>justify-content: space-between</code> in CSS Grid?</h3>
<p><code>space-between</code> does the following:</p>
<ul>
<li><p>It positions a grid container's first column with its row-start edge.</p>
</li>
<li><p>It positions the container's last column with the row-end edge.</p>
</li>
<li><p>It creates even spacing between each pair of columns between the first and last columns.</p>
</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-justify-content-space-between-illustration-codesweetly.png" alt="Illustration of justify-content's space-between value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>justify-content's space-between value creates even spacing between each pair of columns between the first and last grid column</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">justify-content</span>: space-between;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">repeat</span>(<span class="hljs-number">4</span>, <span class="hljs-number">40px</span>);
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ajbrex?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>space-between</code> value to create even spacing between each pair of columns between the first and last grid column.</p>
<h3 id="heading-what-is-justify-content-space-around-in-css-grid">What is <code>justify-content: space-around</code> in CSS Grid?</h3>
<p><code>space-around</code> assigns equal spacing to each side of a grid container's columns.</p>
<p>Therefore, the space before the first column and after the last one is half the width of the space between each pair of columns.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-justify-content-space-around-illustration-codesweetly.png" alt="Illustration of justify-content's space-around value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>justify-content's space-around value assigns equal spacing to each side of the grid container's columns</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">justify-content</span>: space-around;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">repeat</span>(<span class="hljs-number">4</span>, <span class="hljs-number">40px</span>);
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-qnla5x?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>space-around</code> value to assign equal spacing to each side of the grid container's columns.</p>
<h3 id="heading-what-is-justify-content-space-evenly-in-css-grid">What is <code>justify-content: space-evenly</code> in CSS Grid?</h3>
<p><code>space-evenly</code> assigns even spacing to both ends of a grid container and between its columns.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-justify-content-space-evenly-illustration-codesweetly.png" alt="Illustration of justify-content's space-evenly value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>justify-content's space-evenly value assigns even spacing to both ends of the grid container and between its columns</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">justify-content</span>: space-evenly;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">repeat</span>(<span class="hljs-number">4</span>, <span class="hljs-number">40px</span>);
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-vnd1u3?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>space-evenly</code> value to assign even spacing to both ends of the grid container and between its columns.</p>
<h2 id="heading-what-is-css-grids-justify-items-property">What Is CSS Grid's <code>justify-items</code> Property?</h2>
<p><strong>justify-items</strong> specifies the default <a target="_blank" href="https://codesweetly.com/css-grid-justify-self-property"><code>justify-self</code></a> value for all the grid items.</p>
<p>The <code>justify-items</code> property accepts the following values:</p>
<ul>
<li><p><code>stretch</code></p>
</li>
<li><p><code>start</code></p>
</li>
<li><p><code>center</code></p>
</li>
<li><p><code>end</code></p>
</li>
</ul>
<p>Let's discuss the four values.</p>
<h3 id="heading-what-is-justify-items-stretch-in-css-grid">What is <code>justify-items: stretch</code> in CSS Grid?</h3>
<p><code>stretch</code> is <code>justify-items</code>' default value. It stretches the grid container's items to fill their individual cells' row (inline) axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-justify-items-stretch-illustration-codesweetly.png" alt="Illustration of justify-items' stretch value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>justify-items' stretch value stretches grid items to fill their individual cells' row axis</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">justify-items</span>: stretch;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-dedmgi?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>stretch</code> value to stretch the grid items to fill their individual cells' row axis.</p>
<h3 id="heading-what-is-justify-items-start-in-css-grid">What is <code>justify-items: start</code> in CSS Grid?</h3>
<p><code>start</code> positions a grid container's items with the row-start edge of their individual cells' row axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-justify-items-start-illustration-codesweetly.png" alt="Illustration of justify-items' start value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>justify-items' start value positions grid items to their individual cells' row-start edge</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">justify-items</span>: start;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-zdzwmb?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>start</code> value to position the grid items to their individual cells' row-start edge.</p>
<h3 id="heading-what-is-justify-items-center-in-css-grid">What is <code>justify-items: center</code> in CSS Grid?</h3>
<p><code>center</code> positions a grid container's items to the center of their individual cells' row axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-justify-items-center-illustration-codesweetly.png" alt="Illustration of justify-items' center value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>justify-items' center value positions grid items to their individual cells' center</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">justify-items</span>: center;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-dsgyni?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>center</code> value to position the grid items to the center of their individual cells' row axis.</p>
<h3 id="heading-what-is-justify-items-end-in-css-grid">What is <code>justify-items: end</code> in CSS Grid?</h3>
<p><code>end</code> positions a grid container's items with the row-end edge of their individual cells' row axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-justify-items-end-illustration-codesweetly.png" alt="Illustration of justify-items' end value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>justify-items' end value positions grid items to their individual cells' row-end edge</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">justify-items</span>: end;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-pcenzt?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>end</code> value to position the grid items to their individual cells' row-end edge.</p>
<h2 id="heading-what-is-css-grids-align-content-property">What Is CSS Grid's <code>align-content</code> Property?</h2>
<p><strong>align-content</strong> specifies how browsers should align a grid container's rows along the container's column axis.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>A column axis is sometimes called a block axis.</p>
</li>
<li><p>The <code>align-content</code> property works if the total row heights are less than the grid container's height. In other words, you need free space along the container's column axis to align its rows up or down.</p>
</li>
</ul>
<p>The <code>align-content</code> property accepts the following values:</p>
<ul>
<li><p><code>start</code></p>
</li>
<li><p><code>center</code></p>
</li>
<li><p><code>end</code></p>
</li>
<li><p><code>stretch</code></p>
</li>
<li><p><code>space-between</code></p>
</li>
<li><p><code>space-around</code></p>
</li>
<li><p><code>space-evenly</code></p>
</li>
</ul>
<p>Let's discuss these values.</p>
<h3 id="heading-what-is-align-content-start-in-css-grid">What is <code>align-content: start</code> in CSS Grid?</h3>
<p><code>start</code> aligns a grid container's rows with the column-start edge of the grid's column axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-align-content-start-illustration-codesweetly.png" alt="Illustration of align-content's start value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>align-content's start value aligns rows to the grid container's column-start edge</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">align-content</span>: start;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">300px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-cbmgr1?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>start</code> value to align the <code>&lt;section&gt;</code>'s rows to the grid container's column-start edge.</p>
<h3 id="heading-what-is-align-content-center-in-css-grid">What is <code>align-content: center</code> in CSS Grid?</h3>
<p><code>center</code> aligns a grid container's rows to the center of the grid's column axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-align-content-center-illustration-codesweetly.png" alt="Illustration of align-content's center value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>align-content's center value aligns rows to the center of the grid container</em></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">align-content</span>: center;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">300px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-83kj8v?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>center</code> value to align the <code>&lt;section&gt;</code>'s rows to the center of the grid container.</p>
<h3 id="heading-what-is-align-content-end-in-css-grid">What is <code>align-content: end</code> in CSS Grid?</h3>
<p><code>end</code> aligns a grid container's rows with the column-end edge of the grid's column axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-align-content-end-illustration-codesweetly.png" alt="Illustration of align-content's end value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>align-content's end value aligns rows to the grid container's column-end edge</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">align-content</span>: end;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">300px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-lc1lus?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>end</code> value to align the <code>&lt;section&gt;</code>'s rows to the grid container's column-end edge.</p>
<h3 id="heading-what-is-align-content-space-between-in-css-grid">What is <code>align-content: space-between</code> in CSS Grid?</h3>
<p><code>space-between</code> does the following:</p>
<ul>
<li><p>It aligns a grid container's first row with its column-start edge.</p>
</li>
<li><p>It aligns the container's last row with the column-end edge.</p>
</li>
<li><p>It creates even spacing between each pair of rows between the first and last row.</p>
</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-align-content-space-between-illustration-codesweetly.png" alt="Illustration of align-content's space-between value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>align-content's space-between value creates even spacing between each pair of rows between the first and last grid row</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">align-content</span>: space-between;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">300px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ieqvih?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>space-between</code> value to create even spacing between each pair of rows between the first and last grid row.</p>
<h3 id="heading-what-is-align-content-space-around-in-css-grid">What is <code>align-content: space-around</code> in CSS Grid?</h3>
<p><code>space-around</code> assigns equal spacing to each side of a grid container's rows.</p>
<p>Therefore, the space before the first row and after the last one is half the width of the space between each pair of rows.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-align-content-space-around-illustration-codesweetly.png" alt="Illustration of align-content's space-around value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>align-content's space-around value assigns equal spacing to each side of the grid container's rows</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">align-content</span>: space-around;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">300px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-eyzta5?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>space-around</code> value to assign equal spacing to each side of the grid container's rows.</p>
<h3 id="heading-what-is-align-content-space-evenly-in-css-grid">What is <code>align-content: space-evenly</code> in CSS Grid?</h3>
<p><code>space-evenly</code> assigns even spacing to both ends of a grid container and between its rows.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-align-content-space-evenly-illustration-codesweetly.png" alt="Illustration of align-content's space-evenly value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>align-content's space-evenly value assigns even spacing to both ends of the grid container and between its rows</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">align-content</span>: space-evenly;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">300px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-il5vu1?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>space-evenly</code> value to assign even spacing to both ends of the grid container and between its rows.</p>
<h2 id="heading-what-is-css-grids-align-items-property">What Is CSS Grid's <code>align-items</code> Property?</h2>
<p><strong>align-items</strong> specifies the default <a target="_blank" href="https://codesweetly.com/css-grid-align-self-property"><code>align-self</code></a> value for all the grid items.</p>
<p>The <code>align-items</code> property accepts the following values:</p>
<ul>
<li><p><code>stretch</code></p>
</li>
<li><p><code>start</code></p>
</li>
<li><p><code>center</code></p>
</li>
<li><p><code>end</code></p>
</li>
</ul>
<p>Let's discuss the four values below.</p>
<h3 id="heading-what-is-align-items-stretch-in-css-grid">What is <code>align-items: stretch</code> in CSS Grid?</h3>
<p><code>stretch</code> is the default value for <code>align-items</code>. It stretches the grid container's items to fill their individual cells' column (block) axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-align-items-stretch-illustration-codesweetly.png" alt="Illustration of align-items' stretch value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>align-items' stretch value stretches grid items to fill their individual cells' column axis</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">align-items</span>: stretch;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">400px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-fia3ra?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>stretch</code> value to stretch the grid items to fill their individual cells' column axis.</p>
<h3 id="heading-what-is-align-items-start-in-css-grid">What is <code>align-items: start</code> in CSS Grid?</h3>
<p><code>start</code> aligns a grid container's items with the column-start edge of their individual cells' column axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-align-items-start-illustration-codesweetly.png" alt="Illustration of align-items' start value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>align-items' start value aligns grid items to their individual cells' column-start edge</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">align-items</span>: start;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">400px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-achetg?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>start</code> value to align the grid items to their individual cells' column-start edge.</p>
<h3 id="heading-what-is-align-items-center-in-css-grid">What is <code>align-items: center</code> in CSS Grid?</h3>
<p><code>center</code> aligns a grid container's items to the center of their individual cells' column axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-align-items-center-illustration-codesweetly.png" alt="Illustration of align-items' center value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>align-items' center value aligns grid items to their individual cells' center</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">400px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-cmqydk?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>center</code> value to align the grid items to the center of their individual cells' column axis.</p>
<h3 id="heading-what-is-align-items-end-in-css-grid">What is <code>align-items: end</code> in CSS Grid?</h3>
<p><code>end</code> aligns a grid container's items with the column-end edge of their individual cells' column axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-align-items-end-illustration-codesweetly.png" alt="Illustration of align-items' end value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>align-items' end value aligns grid items to their individual cells' column-end edge</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">align-items</span>: end;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">400px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-jei1qv?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>end</code> value to align the grid items to their individual cells' column-end edge.</p>
<p>So, now that we know the types of CSS grid container properties, we can discuss the grid item properties.</p>
<h2 id="heading-what-are-the-grid-items-properties">What Are the Grid Item's Properties?</h2>
<p>A grid item's properties specify how browsers should layout a specified item within the grid box model.</p>
<p><strong>Note:</strong> We define a grid item's property on the item, not its container.</p>
<p>The ten (10) types of grid item properties are:</p>
<ul>
<li><p><code>justify-self</code></p>
</li>
<li><p><code>align-self</code></p>
</li>
<li><p><code>grid-column-start</code></p>
</li>
<li><p><code>grid-column-end</code></p>
</li>
<li><p><code>grid-column</code></p>
</li>
<li><p><code>grid-row-start</code></p>
</li>
<li><p><code>grid-row-end</code></p>
</li>
<li><p><code>grid-row</code></p>
</li>
<li><p><code>grid-area</code></p>
</li>
<li><p><code>grid-template-areas</code></p>
</li>
</ul>
<p>Let's discuss the ten types now.</p>
<h2 id="heading-what-is-css-grids-justify-self-property">What Is CSS Grid's <code>justify-self</code> Property?</h2>
<p><strong>justify-self</strong> specifies how browsers should position the selected grid item along its cell's row (inline) axis.</p>
<p>The <code>justify-self</code> property accepts the following values:</p>
<ul>
<li><p><code>stretch</code></p>
</li>
<li><p><code>start</code></p>
</li>
<li><p><code>center</code></p>
</li>
<li><p><code>end</code></p>
</li>
</ul>
<p>Let's discuss the four values.</p>
<h3 id="heading-what-is-justify-self-stretch-in-css-grid">What is <code>justify-self: stretch</code> in CSS Grid?</h3>
<p><code>stretch</code> is <code>justify-self</code>'s default value. It stretches the selected grid item to fill its cell's row (inline) axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-justify-self-stretch-illustration-codesweetly.png" alt="Illustration of justify-self's stretch value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>justify-self's stretch value stretches the selected grid item to fill its cell's row axis</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">justify-self</span>: stretch;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-82a3ep?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>stretch</code> value to stretch <code>grid-item1</code> to fill its cell's row axis.</p>
<h3 id="heading-what-is-justify-self-start-in-css-grid">What is <code>justify-self: start</code> in CSS Grid?</h3>
<p><code>start</code> positions the selected grid item with the row-start edge of its cell's row axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-justify-self-start-illustration-codesweetly.png" alt="Illustration of justify-self's start value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>justify-self's start value positions the selected grid item to its cell's row-start edge</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">justify-self</span>: start;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-cnz92l?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>start</code> value to position <code>grid-item1</code> to its cell's row-start edge.</p>
<h3 id="heading-what-is-justify-self-center-in-css-grid">What is <code>justify-self: center</code> in CSS Grid?</h3>
<p><code>center</code> positions the selected grid item to the center of its cell's row axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-justify-self-center-illustration-codesweetly.png" alt="Illustration of justify-self's center value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>justify-self's center value positions the selected grid item to its cell's center</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">justify-self</span>: center;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-9kspmx?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>center</code> value to position <code>grid-item1</code> to its cell's center.</p>
<h3 id="heading-what-is-justify-self-end-in-css-grid">What is <code>justify-self: end</code> in CSS Grid?</h3>
<p><code>end</code> positions the selected grid item with the row-end edge of its cell's row axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-justify-self-end-illustration-codesweetly.png" alt="Illustration of justify-self's end value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>justify-self's end value positions the selected grid item to its cell's row-end edge</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">justify-self</span>: end;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-xschhb?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>end</code> value to position <code>grid-item1</code> to its cell's row-end edge.</p>
<h2 id="heading-what-is-css-grids-align-self-property">What Is CSS Grid's <code>align-self</code> Property?</h2>
<p><strong>align-self</strong> specifies how browsers should align the selected grid item along its cell's column (block) axis.</p>
<p>The <code>align-self</code> property accepts the following values:</p>
<ul>
<li><p><code>stretch</code></p>
</li>
<li><p><code>start</code></p>
</li>
<li><p><code>center</code></p>
</li>
<li><p><code>end</code></p>
</li>
</ul>
<p>Let's discuss the four values below.</p>
<h3 id="heading-what-is-align-self-stretch-in-css-grid">What is <code>align-self: stretch</code> in CSS Grid?</h3>
<p><code>stretch</code> is <code>align-self</code>'s default value. It stretches the selected grid item to fill its cell's column (block) axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-align-self-stretch-illustration-codesweetly-1.png" alt="Illustration of align-self's stretch value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>align-self's stretch value stretches the selected grid item to fill its cell's column axis</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">align-self</span>: stretch;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-unnbb9?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>stretch</code> value to stretch <code>grid-item1</code> to fill its cell's column axis.</p>
<h3 id="heading-what-is-align-self-start-in-css-grid">What is <code>align-self: start</code> in CSS Grid?</h3>
<p><code>start</code> aligns the selected grid item with the column-start edge of its cell's column axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-align-self-start-illustration-codesweetly-1.png" alt="Illustration of align-self's start value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>align-self's start value aligns the selected grid item to its cell's column-start edge</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">align-self</span>: start;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ytttz4?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>start</code> value to align <code>grid-item1</code> to its cell's column-start edge.</p>
<h3 id="heading-what-is-align-self-center-in-css-grid">What is <code>align-self: center</code> in CSS Grid?</h3>
<p><code>center</code> aligns the selected grid item to the center of its cell's column axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-align-self-center-illustration-codesweetly.png" alt="Illustration of align-self's center value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>align-self's center value aligns the selected grid item to its cell's center</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">align-self</span>: center;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-fpv4ed?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>center</code> value to align <code>grid-item1</code> to its cell's center.</p>
<h3 id="heading-what-is-align-self-end-in-css-grid">What is <code>align-self: end</code> in CSS Grid?</h3>
<p><code>end</code> aligns the selected grid item with the column-end edge of its cell's column axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-align-self-end-illustration-codesweetly.png" alt="Illustration of align-self's end value in CSS Grid" width="600" height="400" loading="lazy"></p>
<p><em>align-self's end value aligns the selected grid item to its cell's column-end edge</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">align-self</span>: end;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-vvmwzv?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>end</code> value to align grid-item1 to its cell's column-end edge.</p>
<h2 id="heading-what-is-css-grids-grid-column-start-property">What Is CSS Grid's <code>grid-column-start</code> Property?</h2>
<p><strong>grid-column-start</strong> specifies where the selected grid item should start (or span) along the grid container's row (inline) axis.</p>
<p>The <code>grid-column-start</code> property accepts the following values:</p>
<ul>
<li><p><code>auto</code></p>
</li>
<li><p><code>&lt;column-line-number&gt;</code></p>
</li>
<li><p><code>span &lt;number-of-columns&gt;</code></p>
</li>
</ul>
<h3 id="heading-example-1-how-to-auto-start-the-selected-grid-item-following-the-normal-column-flow">Example 1: How to auto-start the selected grid item following the normal column flow</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-column-start</span>: auto;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-rvhhxh?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>auto</code> value to auto-start <code>grid-item1</code> according to the normal column layout flow.</p>
<h3 id="heading-example-2-how-to-start-the-selected-grid-item-at-column-line-3">Example 2: How to start the selected grid item at column line 3</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-column-start</span>: <span class="hljs-number">3</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ep6zgd?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>grid-column-start</code> property to start <code>grid-item1</code> at <a target="_blank" href="https://codesweetly.com/css-grid-lines-explained">column line</a> 3.</p>
<h3 id="heading-example-3-how-to-span-the-selected-grid-item-across-two-columns">Example 3: How to span the selected grid item across two columns</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-column-start</span>: span <span class="hljs-number">2</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-w1nw8k?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>span 2</code> value to span <code>grid-item1</code> across two columns.</p>
<h2 id="heading-what-is-css-grids-grid-column-end-property">What Is CSS Grid's <code>grid-column-end</code> Property?</h2>
<p><strong>grid-column-end</strong> specifies where the selected grid item should end (or span) along the grid container's row (inline) axis.</p>
<p>The <code>grid-column-end</code> property accepts the following values:</p>
<ul>
<li><p><code>auto</code></p>
</li>
<li><p><code>&lt;column-line-number&gt;</code></p>
</li>
<li><p><code>span &lt;number-of-columns&gt;</code></p>
</li>
</ul>
<h3 id="heading-example-1-how-to-auto-end-the-selected-grid-item-following-the-normal-column-flow">Example 1: How to auto-end the selected grid item following the normal column flow</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-column-end</span>: auto;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-1mmxhp?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>auto</code> value to auto-end <code>grid-item1</code> according to the normal layout flow.</p>
<h3 id="heading-example-2-how-to-end-the-selected-grid-item-at-column-line-3">Example 2: How to end the selected grid item at column line 3</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-column-start</span>: <span class="hljs-number">1</span>;
  <span class="hljs-attribute">grid-column-end</span>: <span class="hljs-number">3</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-hjcfhc?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>grid-column-end</code> property to end <code>grid-item1</code> at <a target="_blank" href="https://codesweetly.com/css-grid-lines-explained">column line</a> 3.</p>
<h3 id="heading-example-3-how-to-span-the-selected-grid-item-across-two-columns-1">Example 3: How to span the selected grid item across two columns</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-column-start</span>: <span class="hljs-number">2</span>;
  <span class="hljs-attribute">grid-column-end</span>: span <span class="hljs-number">2</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-yhe3ew?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>span 2</code> value to span <code>grid-item1</code> across two columns.</p>
<h2 id="heading-what-is-css-grids-grid-column-property">What Is CSS Grid's <code>grid-column</code> Property?</h2>
<p><strong>grid-column</strong> is a shorthand for the <code>grid-column-start</code> and <code>grid-column-end</code> properties.</p>
<p>In other words, instead of writing:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-column-start</span>: <span class="hljs-number">1</span>;
  <span class="hljs-attribute">grid-column-end</span>: <span class="hljs-number">3</span>;
}
</code></pre>
<p>You can alternatively use the <code>grid-column</code> property to shorten your code like so:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-column</span>: <span class="hljs-number">1</span> / <span class="hljs-number">3</span>;
}
</code></pre>
<p><strong>Here is grid-column's syntax:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">grid-column</span>: <span class="hljs-selector-tag">grid-column-start</span> / <span class="hljs-selector-tag">grid-column-end</span>;
</code></pre>
<h2 id="heading-what-is-css-grids-grid-row-start-property">What Is CSS Grid's <code>grid-row-start</code> Property?</h2>
<p><strong>grid-row-start</strong> specifies where the selected grid item should start (or span) along the grid container's column (block) axis.</p>
<p>The <code>grid-row-start</code> property accepts the following values:</p>
<ul>
<li><p><code>auto</code></p>
</li>
<li><p><code>&lt;row-line-number&gt;</code></p>
</li>
<li><p><code>span &lt;number-of-rows&gt;</code></p>
</li>
</ul>
<h3 id="heading-example-1-how-to-auto-start-the-selected-grid-item-following-the-normal-row-flow">Example 1: How to auto-start the selected grid item following the normal row flow</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-row-start</span>: auto;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-qthpn6?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>auto</code> value to auto-start <code>grid-item1</code> according to the normal row layout flow.</p>
<h3 id="heading-example-2-how-to-start-the-selected-grid-item-at-row-line-3">Example 2: How to start the selected grid item at row line 3</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-row-start</span>: <span class="hljs-number">3</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-phrjcb?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>grid-row-start</code> property to start <code>grid-item1</code> at <a target="_blank" href="https://codesweetly.com/css-grid-lines-explained">row line</a> 3.</p>
<h3 id="heading-example-3-how-to-span-the-selected-grid-item-across-two-rows">Example 3: How to span the selected grid item across two rows</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-row-start</span>: span <span class="hljs-number">2</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-5bchie?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>span 2</code> value to span <code>grid-item1</code> across two rows.</p>
<h2 id="heading-what-is-css-grids-grid-row-end-property">What Is CSS Grid's <code>grid-row-end</code> Property?</h2>
<p><strong>grid-row-end</strong> specifies where the selected grid item should end (or span) along the grid container's column (block) axis.</p>
<p>The <code>grid-row-end</code> property accepts the following values:</p>
<ul>
<li><p><code>auto</code></p>
</li>
<li><p><code>&lt;column-line-number&gt;</code></p>
</li>
<li><p><code>span &lt;number-of-columns&gt;</code></p>
</li>
</ul>
<h3 id="heading-example-1-how-to-auto-end-the-selected-grid-item-following-the-normal-row-flow">Example 1: How to auto-end the selected grid item following the normal row flow</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-row-end</span>: auto;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-w1rpy8?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>auto</code> value to auto-end <code>grid-item1</code> according to the normal row layout flow.</p>
<h3 id="heading-example-2-how-to-end-the-selected-grid-item-at-row-line-5">Example 2: How to end the selected grid item at row line 5</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-row-start</span>: <span class="hljs-number">1</span>;
  <span class="hljs-attribute">grid-row-end</span>: <span class="hljs-number">5</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-wps8a3?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>grid-row-end</code> property to end <code>grid-item1</code> at <a target="_blank" href="https://codesweetly.com/css-grid-lines-explained">row line</a> 5.</p>
<h3 id="heading-example-3-how-to-span-the-selected-grid-item-across-three-rows">Example 3: How to span the selected grid item across three rows</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-row-end</span>: span <span class="hljs-number">3</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-skcbxf?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>span 3</code> value to span <code>grid-item1</code> across three rows.</p>
<h2 id="heading-what-is-css-grids-grid-row-property">What Is CSS Grid's <code>grid-row</code> Property?</h2>
<p><strong>grid-row</strong> is a shorthand for the <code>grid-row-start</code> and <code>grid-row-end</code> properties.</p>
<p>In other words, instead of writing:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-row-start</span>: <span class="hljs-number">1</span>;
  <span class="hljs-attribute">grid-row-end</span>: <span class="hljs-number">5</span>;
}
</code></pre>
<p>You can alternatively use the <code>grid-row</code> property to shorten your code like so:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-row</span>: <span class="hljs-number">1</span> / <span class="hljs-number">5</span>;
}
</code></pre>
<p><strong>Here is grid-row's syntax:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">grid-row</span>: <span class="hljs-selector-tag">grid-row-start</span> / <span class="hljs-selector-tag">grid-row-end</span>;
</code></pre>
<h2 id="heading-what-is-css-grids-grid-area-property">What Is CSS Grid's <code>grid-area</code> Property?</h2>
<p>You can use the <strong>grid-area</strong> property for the following purposes:</p>
<ol>
<li><p>As a shorthand for the <code>grid-column-start</code>, <code>grid-column-end</code>, <code>grid-row-start</code>, and <code>grid-row-end</code> properties.</p>
</li>
<li><p>To specify a grid item's name.</p>
</li>
</ol>
<p>Let's discuss the two purposes below.</p>
<h3 id="heading-how-to-use-grid-area-as-a-shorthand">How to use <code>grid-area</code> as a shorthand</h3>
<p>Here is the syntax for using the <code>grid-area</code> property as a shorthand for the <code>grid-column-start</code>, <code>grid-column-end</code>, <code>grid-row-start</code>, and <code>grid-row-end</code> properties:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.your-grid-item</span> {
  <span class="hljs-attribute">grid-area</span>: grid-row-start / grid-column-start / grid-row-end / grid-column-end;
}
</code></pre>
<p>Therefore, instead of writing:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-row-start</span>: <span class="hljs-number">3</span>;
  <span class="hljs-attribute">grid-row-end</span>: <span class="hljs-number">5</span>;
  <span class="hljs-attribute">grid-column-start</span>: <span class="hljs-number">1</span>;
  <span class="hljs-attribute">grid-column-end</span>: span <span class="hljs-number">2</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-sqkxmk?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>You can alternatively use the <code>grid-area</code> property to shorten your code like so:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-area</span>: <span class="hljs-number">3</span> / <span class="hljs-number">1</span> / <span class="hljs-number">5</span> / span <span class="hljs-number">2</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-42swnh?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<h3 id="heading-how-to-use-grid-area-to-specify-a-grid-items-name">How to use <code>grid-area</code> to specify a grid item's name</h3>
<p>Here is the syntax for using the <code>grid-area</code> property to specify a grid item's name:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.your-grid-item</span> {
  <span class="hljs-attribute">grid-area</span>: item-name;
}
</code></pre>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-area</span>: firstDiv;
}

<span class="hljs-selector-class">.grid-item2</span> {
  <span class="hljs-attribute">grid-area</span>: middleDiv;
}

<span class="hljs-selector-class">.grid-item2</span> {
  <span class="hljs-attribute">grid-area</span>: lastDiv;
}
</code></pre>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"grid-item1"</span>&gt;</span>1<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"grid-item2"</span>&gt;</span>2<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"grid-item3"</span>&gt;</span>3<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span>
</code></pre>
<p>Using <code>grid-area</code> to define a named grid item allows your grid container's <code>grid-template-areas</code> property to use the name to set the item's size and location.</p>
<h2 id="heading-what-is-css-grids-grid-template-areas-property">What Is CSS Grid's <code>grid-template-areas</code> Property?</h2>
<p><strong>grid-template-areas</strong> specifies the area where you want to place <em>named grid items</em> within a grid container.</p>
<p><strong>Remember:</strong> We use the CSS <code>[grid-area](#heading-how-to-use-grid-area-to-specify-a-grid-items-name)</code> property to name grid items.</p>
<h3 id="heading-example-1-how-to-place-a-named-grid-item-across-three-columns">Example 1: How to place a named grid item across three columns</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-area</span>: firstDiv;
}

<span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-areas</span>: <span class="hljs-string">"firstDiv firstDiv firstDiv . ."</span>;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">50px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-1sw8ww?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>grid-template-areas</code> property to place <code>grid-item1</code> across the first three column areas.</p>
<p><strong>Note the following:</strong></p>
<ul>
<li><p>Quotation marks (<code>""</code>) define each grid row.</p>
</li>
<li><p>A period symbol (<code>.</code>) defines an unnamed grid item.</p>
</li>
<li><p>We used the whitespace character to separate grid columns.</p>
</li>
</ul>
<h3 id="heading-example-2-how-to-specify-multiple-named-grid-items-placements">Example 2: How to specify multiple named grid items' placements</h3>
<pre><code class="lang-css"><span class="hljs-selector-class">.grid-item1</span> {
  <span class="hljs-attribute">grid-area</span>: header;
}

<span class="hljs-selector-class">.grid-item2</span> {
  <span class="hljs-attribute">grid-area</span>: article;
}

<span class="hljs-selector-class">.grid-item3</span> {
  <span class="hljs-attribute">grid-area</span>: footer;
}

<span class="hljs-selector-class">.grid-item4</span> {
  <span class="hljs-attribute">grid-area</span>: sidebar;
}

<span class="hljs-selector-class">.grid-item5</span> {
  <span class="hljs-attribute">grid-area</span>: ads1;
}

<span class="hljs-selector-class">.grid-item6</span> {
  <span class="hljs-attribute">grid-area</span>: ads2;
}

<span class="hljs-selector-class">.grid-item7</span> {
  <span class="hljs-attribute">grid-area</span>: ads3;
}

<span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">repeat</span>(<span class="hljs-number">5</span>, <span class="hljs-number">1</span>fr);
  <span class="hljs-attribute">grid-template-rows</span>: <span class="hljs-built_in">repeat</span>(<span class="hljs-number">7</span>, <span class="hljs-number">1</span>fr);
  <span class="hljs-attribute">grid-template-areas</span>:
    <span class="hljs-string">"header header header header header"</span>
    <span class="hljs-string">"sidebar article article article ads1"</span>
    <span class="hljs-string">"sidebar article article article ads1"</span>
    <span class="hljs-string">"sidebar article article article ads1"</span>
    <span class="hljs-string">"sidebar article article article ads2"</span>
    <span class="hljs-string">"sidebar article article article ads3"</span>
    <span class="hljs-string">"sidebar footer footer footer footer"</span>;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">30px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-9b5emj?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>grid-template-areas</code> property to specify where browsers should place the grid items across the rows and columns of the grid container.</p>
<h3 id="heading-important-stuff-to-know-about-the-grid-template-areas-property">Important Stuff to Know about the <code>grid-template-areas</code> Property</h3>
<p>Here are four essential facts to remember when using the <code>grid-template-areas</code> property:</p>
<h4 id="heading-1-grid-template-areas-do-not-permit-empty-cells">1. <code>grid-template-areas</code> do not permit empty cells</h4>
<p>The <code>grid-template-areas</code> property requires you to provide an item for all grid cells.</p>
<p>For instance, consider this snippet:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">grid-template-areas</span>:
  "<span class="hljs-selector-tag">header</span> <span class="hljs-selector-tag">header</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads1</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads1</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads1</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads2</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads3</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">footer</span> <span class="hljs-selector-tag">footer</span> <span class="hljs-selector-tag">footer</span> <span class="hljs-selector-tag">footer</span>";
</code></pre>
<p>Above is an invalid <code>grid-template-areas</code> value because the first row is incomplete.</p>
<p>In other words, the first row is the only one with two columns. However, <code>grid-template-areas</code> expect all the rows in a grid container to have the same number of columns.</p>
<h4 id="heading-2-you-can-use-dots-to-specify-empty-cells">2. You can use dots to specify empty cells</h4>
<p>Suppose you wish to leave some cells empty. In that case, use a dot (<code>.</code>) or multiple unspaced dots (<code>....</code>).</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">grid-template-areas</span>:
  "<span class="hljs-selector-tag">header</span> <span class="hljs-selector-tag">header</span> . . ."
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads1</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads1</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads1</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads2</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads3</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">footer</span> <span class="hljs-selector-tag">footer</span> <span class="hljs-selector-tag">footer</span> <span class="hljs-selector-tag">footer</span>";
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-yfhx4g?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the three <em>spaced</em> dot (<code>.</code>) symbols to indicate three empty cells.</p>
<h4 id="heading-3-grid-template-areas-do-not-permit-placing-an-item-in-multiple-locations">3. <code>grid-template-areas</code> do not permit placing an item in multiple locations</h4>
<p>The <code>grid-template-areas</code> property cannot place items twice within a grid container.</p>
<p>For instance, consider this snippet:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">grid-template-areas</span>:
  "<span class="hljs-selector-tag">header</span> <span class="hljs-selector-tag">header</span> <span class="hljs-selector-tag">header</span> <span class="hljs-selector-tag">header</span> <span class="hljs-selector-tag">header</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads1</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads1</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads1</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads2</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads3</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">footer</span> <span class="hljs-selector-tag">header</span> <span class="hljs-selector-tag">header</span> <span class="hljs-selector-tag">header</span>";
</code></pre>
<p>Above is an invalid <code>grid-template-areas</code> value because the <code>header</code> item occupies two grid areas.</p>
<h4 id="heading-4-grid-template-areas-allows-rectangular-areas-only">4. <code>grid-template-areas</code> allows rectangular areas only</h4>
<p>The <code>grid-template-areas</code> property cannot create non-rectangular areas (such as T-shaped or L-shaped).</p>
<p>For instance, consider this snippet:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">grid-template-areas</span>:
  "<span class="hljs-selector-tag">header</span> <span class="hljs-selector-tag">header</span> <span class="hljs-selector-tag">header</span> <span class="hljs-selector-tag">header</span> <span class="hljs-selector-tag">header</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">ads1</span> <span class="hljs-selector-tag">ads1</span> <span class="hljs-selector-tag">ads1</span> <span class="hljs-selector-tag">ads1</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads1</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads1</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads2</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">article</span> <span class="hljs-selector-tag">ads3</span>"
  "<span class="hljs-selector-tag">sidebar</span> <span class="hljs-selector-tag">footer</span> <span class="hljs-selector-tag">footer</span> <span class="hljs-selector-tag">footer</span> <span class="hljs-selector-tag">footer</span>";
</code></pre>
<p>Above is an invalid <code>grid-template-areas</code> value because the <code>ads1</code> item creates a non-rectangular grid area.</p>
<p>So, now that we know the types of CSS grid item properties, we can discuss how to define minimum and maximum grid sizes.</p>
<h2 id="heading-how-to-use-the-css-minmax-function-to-define-minimum-and-maximum-grid-sizes">How to Use the CSS <code>minmax()</code> function to Define Minimum and Maximum Grid Sizes</h2>
<p><strong>minmax()</strong> is a CSS Grid function for defining minimum and maximum grid sizes.</p>
<h3 id="heading-syntax-of-the-css-minmax-function">Syntax of the CSS <code>minmax()</code> function</h3>
<p><code>minmax()</code> accepts two arguments. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">minmax</span>(<span class="hljs-selector-tag">minimum-size</span>, <span class="hljs-selector-tag">maximum-size</span>)
</code></pre>
<p><strong>Note the following:</strong></p>
<ul>
<li><p>The <code>minimum-size</code> argument specifies the smallest size for a specific length.</p>
</li>
<li><p>The <code>maximum-size</code> argument specifies the largest size for a specific length.</p>
</li>
<li><p><code>minmax()</code>'s arguments can be any of the non-negative <a target="_blank" href="https://codesweetly.com/css-unit">CSS lengths</a>, or any one of the keywords <code>auto</code>, <code>min-content</code>, or <code>max-content</code>.</p>
</li>
<li><p>Suppose the <code>maximum-size</code> argument is less than the <code>minimum-size</code>. In that case, browsers will ignore the <code>maximum-size</code> and treat the <code>minmax()</code> function as <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/min"><code>min()</code></a>.</p>
</li>
<li><p>An <a target="_blank" href="https://codesweetly.com/css-unit#fraction-fr"><code>fr</code> unit</a> is an _in_valid unit for the <code>minimum-size</code> argument.</p>
</li>
</ul>
<h3 id="heading-how-to-use-the-css-minmax-function">How to use the CSS <code>minmax()</code> function</h3>
<p>You can use the <code>minmax()</code> function as a value for the following CSS properties:</p>
<ul>
<li><p><code>grid-template-columns</code></p>
</li>
<li><p><code>grid-template-rows</code></p>
</li>
<li><p><code>grid-auto-columns</code></p>
</li>
<li><p><code>grid-auto-rows</code></p>
</li>
</ul>
<h3 id="heading-examples-of-the-css-minmax-function">Examples of the CSS <code>minmax()</code> function</h3>
<p>Below are examples of how the CSS <code>minmax()</code> function works.</p>
<h4 id="heading-how-to-define-a-70px-minimum-and-a-250px-maximum-row-grid-size">How to define a <code>70px</code> minimum and a <code>250px</code> maximum row grid size</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-rows</span>: <span class="hljs-number">50px</span> <span class="hljs-number">100px</span> <span class="hljs-built_in">minmax</span>(<span class="hljs-number">70px</span>, <span class="hljs-number">250px</span>);
  <span class="hljs-attribute">grid-template-columns</span>: auto auto auto;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-giarya?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the CSS <code>minmax()</code> function to set the <code>&lt;section&gt;</code>'s third row's height to a minimum of <code>70px</code> and a maximum of <code>250px</code>.</p>
<h4 id="heading-how-to-define-a-30-minimum-and-a-70-maximum-column-grid-size">How to define a <code>30%</code> minimum and a <code>70%</code> maximum column grid size</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-rows</span>: auto auto auto;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr <span class="hljs-built_in">minmax</span>(<span class="hljs-number">30%</span>, <span class="hljs-number">70%</span>) <span class="hljs-number">1</span>fr;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ekn23p?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the CSS <code>minmax()</code> function to set the <code>&lt;section&gt;</code>'s second column's width to a minimum of <code>30%</code> and a maximum of <code>70%</code>.</p>
<p><strong>Note:</strong> You can use the CSS <code>repeat()</code> function to specify <code>grid-template-rows</code> or <code>grid-template-columns</code> values with repeated patterns. Let's discuss the <code>repeat()</code> function now.</p>
<h2 id="heading-how-to-use-the-css-repeat-function-to-define-grid-tracks-with-repeated-patterns">How to Use the CSS <code>repeat()</code> Function to Define Grid Tracks with Repeated Patterns</h2>
<p>The <strong>repeat()</strong> CSS function allows you to write more concise and readable values when specifying multiple <a target="_blank" href="https://codesweetly.com/css-grid-lines-explained">grid tracks</a> with repeated patterns.</p>
<p><strong>Note:</strong></p>
<ul>
<li><p>A track refers to a grid container's column (or row).</p>
</li>
<li><p>You can use <code>repeat()</code> as a value for the CSS <code>grid-template-columns</code> or <code>grid-template-rows</code> properties.</p>
</li>
</ul>
<h3 id="heading-syntax-of-the-css-repeat-function">Syntax of the CSS <code>repeat()</code> function</h3>
<p><code>repeat()</code> accepts two arguments. Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">repeat</span>(<span class="hljs-selector-tag">number-of-repetition</span>, <span class="hljs-selector-tag">track-list-to-repeat</span>)
</code></pre>
<h3 id="heading-argument-1-number-of-repetition">Argument 1: <code>number-of-repetition</code></h3>
<p>The <code>number-of-repetition</code> argument specifies the number of times browsers should repeat the specified track list (the second argument).</p>
<p>The <code>number-of-repetition</code> argument can be any of the following values:</p>
<ul>
<li><p>Number <code>1</code> or its multiple</p>
</li>
<li><p><code>auto-fill</code></p>
</li>
<li><p><code>auto-fit</code></p>
</li>
</ul>
<h4 id="heading-auto-fill-vs-auto-fit-whats-the-difference"><code>auto-fill</code> vs. <code>auto-fit</code>: What's the difference?</h4>
<p>The <code>auto-fill</code> and <code>auto-fit</code> values automatically create as many tracks as needed to fill a grid container without causing an overflow.</p>
<p>The difference between the two values is that <code>auto-fit</code> collapses empty tracks to zero-pixel (<code>0px</code>). But <code>auto-fill</code> displays both empty and filled tracks.</p>
<p><strong>Note:</strong> Empty tracks are columns or rows with no grid item.</p>
<h3 id="heading-argument-2-track-list-to-repeat">Argument 2: <code>track-list-to-repeat</code></h3>
<p>The <code>track-list-to-repeat</code> argument specifies the track pattern you wish to repeat across a grid container's horizontal or vertical axis.</p>
<p>In other words, <code>track-list-to-repeat</code> consists of one or more values specifying the sizes of tracks browsers should repeat within a grid container.</p>
<p><strong>Note:</strong> Suppose your <code>number-of-repetition</code> is <code>auto-fill</code> or <code>auto-fit</code>. In that case, you can use only <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/repeat#fixed-size">fixed sizes</a> as the <code>track-list-to-repeat</code> argument.</p>
<h3 id="heading-examples-of-the-css-repeat-function">Examples of the CSS <code>repeat()</code> function</h3>
<p>Below are examples of how the CSS <code>repeat()</code> function works.</p>
<h4 id="heading-how-to-create-a-three-column-grid-container-with-70px-column-widths">How to create a three-column grid container with <code>70px</code> column-widths</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">repeat</span>(<span class="hljs-number">3</span>, <span class="hljs-number">70px</span>);
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-imfqcm?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the CSS <code>repeat()</code> function to create three <code>70px</code>-wide columns.</p>
<p>Below is the non-<code>repeat()</code> equivalent of the above <code>grid-template-columns</code> property:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">grid-template-columns</span>: 70<span class="hljs-selector-tag">px</span> 70<span class="hljs-selector-tag">px</span> 70<span class="hljs-selector-tag">px</span>;
</code></pre>
<h4 id="heading-how-to-create-a-four-column-grid-container-with-one-50px-and-three-90px-column-widths">How to create a four-column grid container with one <code>50px</code> and three <code>90px</code> column-widths</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">50px</span> <span class="hljs-built_in">repeat</span>(<span class="hljs-number">3</span>, <span class="hljs-number">90px</span>);
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-bgdk3a?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the CSS <code>repeat()</code> function to create three <code>90px</code>-wide columns.</p>
<p>Below is the non-<code>repeat()</code> equivalent of the above <code>grid-template-columns</code> property:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">grid-template-columns</span>: 50<span class="hljs-selector-tag">px</span> 90<span class="hljs-selector-tag">px</span> 90<span class="hljs-selector-tag">px</span> 90<span class="hljs-selector-tag">px</span>;
</code></pre>
<h4 id="heading-how-to-create-a-five-column-grid-container-with-one-40px-and-two-60px-1fr-column-widths">How to create a five-column grid container with one <code>40px</code> and two <code>60px 1fr</code> column-widths</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">40px</span> <span class="hljs-built_in">repeat</span>(<span class="hljs-number">2</span>, <span class="hljs-number">60px</span> <span class="hljs-number">1</span>fr);
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-wjgjym?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the CSS <code>repeat()</code> function to create two <code>60px 1fr</code>-wide columns.</p>
<p>Below is the non-<code>repeat()</code> equivalent of the above <code>grid-template-columns</code> property:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">grid-template-columns</span>: 40<span class="hljs-selector-tag">px</span> 60<span class="hljs-selector-tag">px</span> 1<span class="hljs-selector-tag">fr</span> 60<span class="hljs-selector-tag">px</span> 1<span class="hljs-selector-tag">fr</span>;
</code></pre>
<p><strong>Note:</strong> We used the <a target="_blank" href="https://codesweetly.com/css-unit#fraction-fr"><code>fr</code> (fraction) unit</a> to scale the third and fifth columns relative to the fraction of available space in the grid container.</p>
<h4 id="heading-how-to-auto-fill-the-grid-container-with-70px-wide-columns">How to auto-fill the grid container with <code>70px</code>-wide columns</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">repeat</span>(auto-fill, <span class="hljs-number">70px</span>);
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-bwdeeb?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the CSS <code>repeat()</code> function to automatically fill the grid container with <code>70px</code>-wide columns.</p>
<h4 id="heading-how-to-auto-fill-the-grid-container-with-a-minimum-of-50px-and-a-maximum-of-1fr-wide-columns">How to auto-fill the grid container with a minimum of <code>50px</code> and a maximum of <code>1fr</code> wide columns</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">repeat</span>(auto-fill, minmax(<span class="hljs-number">50px</span>, <span class="hljs-number">1</span>fr));
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-hrof4i?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the CSS <code>repeat()</code> and <code>minmax()</code> functions to automatically fill the grid container with a minimum of <code>50px</code>-wide columns and a maximum of <code>1fr</code>.</p>
<p><strong>Note:</strong> <code>1fr</code> means one <a target="_blank" href="https://codesweetly.com/css-unit#fraction-fr">fraction unit</a>.</p>
<h4 id="heading-how-to-auto-fit-the-grid-container-with-a-minimum-of-50px-and-a-maximum-of-1fr-wide-columns">How to auto-fit the grid container with a minimum of <code>50px</code> and a maximum of <code>1fr</code> wide columns</h4>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">repeat</span>(auto-fit, minmax(<span class="hljs-number">50px</span>, <span class="hljs-number">1</span>fr));
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-pveewm?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>CSS repeat()</code> and <code>minmax()</code> functions to automatically fit the grid container with a minimum of <code>50px</code>-wide columns and a maximum of <code>1fr</code>.</p>
<h2 id="heading-overview">Overview</h2>
<p>In this article, we discussed all the CSS Grid tools you need to create basic and advanced website layouts in responsive ways that look great on all devices.</p>
<p>I hope you've found this article helpful.</p>
<h3 id="heading-thanks-for-reading">Thanks for reading!</h3>
<p>If you like this tutorial, you can <a target="_blank" href="https://amzn.to/42s5KXZ">get the guidebook version at Amazon</a>. It is a handy quick reference guide to CSS Grid.</p>
<p><a target="_blank" href="https://amzn.to/42s5KXZ"><img src="https://www.freecodecamp.org/news/content/images/2023/03/css-grid-book-codesweetly.png" alt="Buy the CSS Grid Guidebook at Amazon" width="600" height="400" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ CSS Flexbox Explained – Complete Guide to Flexible Containers and Flex Items ]]>
                </title>
                <description>
                    <![CDATA[ CSS Flexbox gives you the tools to create basic and advanced website layouts in flexible and responsive ways. This tutorial discusses everything you need to know to use Flexbox like a pro. Table of Contents What Is Flexbox? Flex Container vs. Flex I... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/css-flexbox-complete-guide/</link>
                <guid isPermaLink="false">66ba0de6256f04965e2bd0c0</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ flexbox ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Fri, 28 Oct 2022 14:28:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/css-flexbox-complete-guide-codesweetly-pexels-chris-f-6664375.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>CSS Flexbox gives you the tools to create basic and advanced website layouts in flexible and responsive ways.</p>
<p>This tutorial discusses everything you need to know to use Flexbox like a pro.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-flexbox">What Is Flexbox?</a></li>
<li><a class="post-section-overview" href="#heading-flex-container-vs-flex-item-whats-the-difference">Flex Container vs. Flex Item: What's the Difference?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-flex-value-in-css">What Is a <code>flex</code> Value in CSS?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-an-inline-flex-value-in-css">What Is an <code>inline-flex</code> Value in CSS?</a></li>
<li><a class="post-section-overview" href="#heading-properties-for-specifying-flexboxs-layout">Properties for Specifying Flexbox's Layout</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-flexible-containers-properties">What Are the Flexible Containers Properties?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-flexboxs-flex-direction-property">What Is Flexbox's <code>flex-direction</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-flexboxs-flex-wrap-property">What Is Flexbox's <code>flex-wrap</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-flexboxs-flex-flow-property">What Is Flexbox's <code>flex-flow</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-flexboxs-justify-content-property">What Is Flexbox's <code>justify-content</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-flexboxs-align-items-property">What Is Flexbox's <code>align-items</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-flexboxs-align-content-property">What Is Flexbox's <code>align-content</code> Property?</a></li>
<li><a class="post-section-overview" href="#what-are-the-flexible-items-properties">What Are the Flexible Items Properties?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-flexboxs-align-self-property">What Is Flexbox's <code>align-self</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-flexboxs-order-property">What Is Flexbox's <code>order</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-flexboxs-flex-grow-property">What Is Flexbox's <code>flex-grow</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-flexboxs-flex-shrink-property">What Is Flexbox's <code>flex-shrink</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-flexboxs-flex-basis-property">What Is Flexbox's <code>flex-basis</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-flexboxs-flex-property">What Is Flexbox's <code>flex</code> Property?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-center-elements-horizontally-with-flexbox">How to Center Elements Horizontally with Flexbox</a></li>
<li><a class="post-section-overview" href="#heading-how-to-center-elements-vertically-with-flexbox">How to Center Elements Vertically with Flexbox</a></li>
<li><a class="post-section-overview" href="#heading-how-to-center-elements-horizontally-and-vertically-with-flexbox">How to Center Elements Horizontally and Vertically with Flexbox</a></li>
<li><a class="post-section-overview" href="#heading-overview">Overview</a></li>
</ol>
<p>So, without any further ado, let's understand what Flexbox is.</p>
<h2 id="heading-what-is-flexbox">What Is Flexbox?</h2>
<p><strong>Flexbox</strong> makes browsers display selected HTML elements as flexible <a target="_blank" href="https://codesweetly.com/css-box-model">box models</a>.</p>
<p>Flexbox allows easy resizing and repositioning of a flexible container and its items one-dimensionally.</p>
<p><strong>Note:</strong></p>
<ul>
<li>"One-dimensionally" means Flexbox allows laying out box models in a row or column at a time. In other words, Flexbox cannot lay out box models in a row and column at the same time.</li>
<li>Flexbox is sometimes called a flexible box layout module.</li>
<li>Use the <a target="_blank" href="https://codesweetly.com/css-grid-explained">grid layout module</a> if you need to resize and reposition elements two-dimensionally.</li>
</ul>
<h2 id="heading-flex-container-vs-flex-item-whats-the-difference">Flex Container vs. Flex Item: What's the Difference?</h2>
<p>A <strong>flex container</strong> is an <a target="_blank" href="https://codesweetly.com/web-tech-terms-h#html-element">HTML element</a> whose <a target="_blank" href="https://codesweetly.com/css-display-property"><code>display</code></a> property's value is <code>flex</code> or <code>inline-flex</code>.</p>
<p><strong>Flex items</strong> are the direct children of a flex container.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-flex-container-flex-item-illustration-codesweetly.png" alt="Illustration of a flex container and a flex item" width="600" height="400" loading="lazy">
<em>A flex container (the large yellow area in the image) is an HTML element whose display property's value is flex or inline-flex. Flex items (the smaller boxes within the yellow container) are the direct children of a flex container.</em></p>
<h2 id="heading-what-is-a-flex-value-in-css">What Is a <code>flex</code> Value in CSS?</h2>
<p><code>flex</code> tells browsers to display the selected HTML element as a block-level flexible box model.</p>
<p>In other words, setting an element's <code>display</code> property's value to <code>flex</code> turns the box model into a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Block-level_elements">block-level</a> flexbox.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-gctvuc?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>flex</code> value to convert the HTML document's <code>&lt;section&gt;</code> elements from regular <code>&lt;section&gt;</code> nodes to block-level flexible box models.</p>
<p><strong>Note:</strong></p>
<ul>
<li>Converting an HTML node to a flexible box model makes the element's direct children become flexible items.</li>
<li>The <code>display: flex</code> directive only affects a box model and its direct children. It does not affect grandchildren nodes.</li>
</ul>
<p>Let's now discuss <code>inline-flex</code>.</p>
<h2 id="heading-what-is-an-inline-flex-value-in-css">What Is an <code>inline-flex</code> Value in CSS?</h2>
<p><code>inline-flex</code> tells browsers to display the selected HTML element as an inline-level flexible box model.</p>
<p>In other words, setting an element's <code>display</code> property's value to <code>inline-flex</code> turns the box model into an <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Inline_elements">inline-level</a> flexbox.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: inline-flex;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ksagv8?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>inline-flex</code> value to convert the HTML document's <code>&lt;section&gt;</code> elements from regular <code>&lt;section&gt;</code> nodes to inline-level flexible box models.</p>
<p><strong>Note:</strong></p>
<ul>
<li>Converting an HTML node to a flexible box model makes the element's direct children become flexible items.</li>
<li>The <code>display: inline-flex</code> directive only affects a box model and its direct children. It does not affect grandchildren nodes.</li>
</ul>
<h2 id="heading-properties-for-specifying-flexboxs-layout">Properties for Specifying Flexbox's Layout</h2>
<p>On converting a regular HTML element to a <code>flex</code> (or <code>inline-flex</code>) box model, Flexbox provides two categories of properties for positioning the flexible box and its direct children:</p>
<ul>
<li>Flexible containers properties</li>
<li>Flexible items properties</li>
</ul>
<h2 id="heading-what-are-the-flexible-containers-properties">What Are the Flexible Containers Properties?</h2>
<p>A flexible container's properties specify how browsers should layout items within the flexible box model.</p>
<p><strong>Note:</strong> We define a flexible container's property on the flex container, not its items.</p>
<p>The six (6) types of flex container properties are:</p>
<ul>
<li><code>flex-direction</code></li>
<li><code>flex-wrap</code></li>
<li><code>flex-flow</code></li>
<li><code>justify-content</code></li>
<li><code>align-items</code></li>
<li><code>align-content</code></li>
</ul>
<p>Let's discuss the six types now.</p>
<h2 id="heading-what-is-flexboxs-flex-direction-property">What Is Flexbox's <code>flex-direction</code> Property?</h2>
<p><strong>flex-direction</strong> tells browsers the specific direction (row or column) they should lay out a flexible container's direct children.</p>
<p>In other words, <code>flex-direction</code> defines a flexbox's <a target="_blank" href="https://codesweetly.com/css-flex-direction-property#main-axis-vs-cross-axis-whats-the-difference">main axis</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-flexbox-main-axis-cross-axis-illustration-codesweetly.png" alt="Illustration of a flexbox's main and cross-axis" width="600" height="400" loading="lazy">
<em>A Flexbox's main axis is the layout orientation defined by a flex-direction property. Its cross axis is the perpendicular orientation to the main axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-jtpqir?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above organized the flexible <code>&lt;section&gt;</code> containers' items in the column direction of your browser's default language.</p>
<p><strong>Tip:</strong> Use <code>flex-direction: column-reverse</code> (or <code>flex-direction: row-reverse</code>) to reverse the browser's layout direction.</p>
<h2 id="heading-what-is-flexboxs-flex-wrap-property">What Is Flexbox's <code>flex-wrap</code> Property?</h2>
<p><strong>flex-wrap</strong> specifies whether browsers should wrap overflown flexible items onto multiple lines.</p>
<p>The <code>flex-wrap</code> property accepts the following values:</p>
<ul>
<li><code>nowrap</code></li>
<li><code>wrap</code></li>
<li><code>wrap-reverse</code></li>
</ul>
<p>Let's discuss the three values.</p>
<h3 id="heading-what-is-flex-wrap-nowrap-in-css-flexbox">What is <code>flex-wrap: nowrap</code> in CSS flexbox?</h3>
<p><code>nowrap</code> is <code>flex-wrap</code>'s default value. It forces all items within a flexible container into a single line (that is, row-wise or column-wise direction).</p>
<p>In other words, <code>nowrap</code> tells browsers <em>not</em> to wrap a flexible container's items.</p>
<p><strong>Note:</strong> Suppose the total width (or height) of all the items in a flexible container is greater than the flexbox's width (or height). In such a case, <code>nowrap</code> will cause the elements to overflow out of the container.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">130px</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: nowrap;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-yn6yw8?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used <code>nowrap</code> to force browsers to lay out the flexible containers' items in a single line.</p>
<h3 id="heading-what-is-flex-wrap-wrap-in-css-flexbox">What is <code>flex-wrap: wrap</code> in CSS flexbox?</h3>
<p><code>wrap</code> moves all overflow items within a flexible container to the next line.</p>
<p>In other words, <code>wrap</code> tells browsers to wrap a flexible container's overflow items.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">130px</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-78ez1m?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used <code>wrap</code> to wrap the flexible containers' overflow items to the next line.</p>
<h3 id="heading-what-is-flex-wrap-wrap-reverse-in-css-flexbox">What is <code>flex-wrap: wrap-reverse</code> in CSS flexbox?</h3>
<p><code>wrap-reverse</code> moves all overflow items within a flexible container to the next line in reverse order.</p>
<p><strong>Note:</strong> <code>wrap-reverse</code> does the same thing as <code>wrap</code>—but in reverse order.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">130px</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: wrap-reverse;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">7px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-eyqxtf?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used <code>wrap-reverse</code> to wrap the flexible containers' overflow items to the next line in reverse order.</p>
<h2 id="heading-what-is-flexboxs-flex-flow-property">What Is Flexbox's <code>flex-flow</code> Property?</h2>
<p><strong>flex-flow</strong> is a shorthand for the <code>flex-direction</code> and <code>flex-wrap</code> properties.</p>
<p>In other words, instead of writing:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
}
</code></pre>
<p>You can alternatively use the <code>flex-flow</code> property to shorten your code like so:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-flow</span>: column wrap;
}
</code></pre>
<h2 id="heading-what-is-flexboxs-justify-content-property">What Is Flexbox's <code>justify-content</code> Property?</h2>
<p><strong>justify-content</strong> specifies how browsers should position a flexible container's items along the flexbox's <a target="_blank" href="https://codesweetly.com/css-flex-direction-property#main-axis-vs-cross-axis-whats-the-difference">main axis</a>.</p>
<p>The <code>justify-content</code> property accepts the following values:</p>
<ul>
<li><code>flex-start</code></li>
<li><code>center</code></li>
<li><code>flex-end</code></li>
<li><code>space-between</code></li>
<li><code>space-around</code></li>
<li><code>space-evenly</code></li>
</ul>
<p>Let's discuss these six values.</p>
<h3 id="heading-what-is-justify-content-flex-start-in-css-flexbox">What is <code>justify-content: flex-start</code> in CSS Flexbox?</h3>
<p><code>flex-start</code> is <code>justify-content</code>'s default value. It aligns a flexible container's items with the main-start edge of the flexbox's main axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-justify-content-flex-start-illustration-codesweetly.png" alt="Illustration of justify-content's flex-start value" width="600" height="400" loading="lazy">
<em>flex-start aligns a flexible container's items with the main-start side of the flexbox's main axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: flex-start;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ma7svj?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>flex-start</code> value to align the flexible container's items to the flexbox's main-start edge.</p>
<h3 id="heading-what-is-justify-content-center-in-css-flexbox">What is <code>justify-content: center</code> in CSS Flexbox?</h3>
<p><code>center</code> aligns a flexible container's items to the center of the flexbox's main axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-justify-content-center-illustration-codesweetly.png" alt="Illustration of justify-content's center value" width="600" height="400" loading="lazy">
<em>center aligns a flexible container's items to the center of the flexbox's main axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-jfzcwc?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>center</code> value to align the flexible container's items to the center of the flexbox.</p>
<h3 id="heading-what-is-justify-content-flex-end-in-css-flexbox">What is <code>justify-content: flex-end</code> in CSS Flexbox?</h3>
<p><code>flex-end</code> aligns a flexible container's items with the main-end side of the flexbox's main axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-justify-content-flex-end-illustration-codesweetly.png" alt="Illustration of justify-content's flex-end value" width="600" height="400" loading="lazy">
<em>flex-end aligns a flexible container's items with the main-end side of the flexbox's main axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: flex-end;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-iyhlbr?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>flex-end</code> value to align the flexible container's items to the flexbox's main-end side.</p>
<h3 id="heading-what-is-justify-content-space-between-in-css-flexbox">What is <code>justify-content: space-between</code> in CSS Flexbox?</h3>
<p><code>space-between</code> does the following:</p>
<ul>
<li>It aligns a flexible container's first item with the main-start edge of the flexbox's main axis.</li>
<li>It aligns the container's last item with the main-end edge of the flexbox's main axis.</li>
<li>It creates even spacing between each pair of items between the first and last item.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-justify-content-space-between-illustration-codesweetly.png" alt="Illustration of justify-content's space-between value" width="600" height="400" loading="lazy">
<em>space-between creates even spacing between each pair of items between the first and last item.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: space-between;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-dylovp?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>space-between</code> value to create even spacing between each pair of items between the first and last flex item.</p>
<h3 id="heading-what-is-justify-content-space-around-in-css-flexbox">What is <code>justify-content: space-around</code> in CSS Flexbox?</h3>
<p><code>space-around</code> assigns equal spacing to each side of a flexible container's items.</p>
<p>Therefore, the space before the first item and after the last element is half the width of the space between each pair of elements.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-justify-content-space-around-illustration-codesweetly.png" alt="Illustration of justify-content's space-around value" width="600" height="400" loading="lazy">
<em>space-around assigns equal spacing to each side of a flexible container's items.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: space-around;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-t6wpcj?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>space-around</code> value to assign equal spacing to each side of the flexible container's items.</p>
<h3 id="heading-what-is-justify-content-space-evenly-in-css-flexbox">What is <code>justify-content: space-evenly</code> in CSS Flexbox?</h3>
<p><code>space-evenly</code> assigns even spacing to both ends of a flexible container and between its items.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-justify-content-space-evenly-illustration-codesweetly.png" alt="Illustration of justify-content's space-evenly value" width="600" height="400" loading="lazy">
<em>space-evenly assigns even spacing to both ends of a flexible container and between its items.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: space-evenly;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-p67eh8?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>space-evenly</code> value to assign even spacing to both ends of the flexbox and between its items.</p>
<p>Let's now discuss the fifth type of flexible container property.</p>
<h2 id="heading-what-is-flexboxs-align-items-property">What Is Flexbox's <code>align-items</code> Property?</h2>
<p><strong>align-items</strong> specifies how browsers should position a flexible container's items along the <a target="_blank" href="https://codesweetly.com/css-flex-direction-property#main-axis-vs-cross-axis-whats-the-difference">cross-axis</a> of the flexbox.</p>
<p>The <code>align-items</code> property accepts the following values:</p>
<ul>
<li><code>stretch</code></li>
<li><code>flex-start</code></li>
<li><code>center</code></li>
<li><code>flex-end</code></li>
<li><code>baseline</code></li>
</ul>
<p>Let's discuss the five values.</p>
<h3 id="heading-what-is-align-items-stretch-in-css-flexbox">What is <code>align-items: stretch</code> in CSS Flexbox?</h3>
<p><code>stretch</code> is <code>align-items</code>' default value. It stretches a flexible container's items to fill the flexbox's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-items-stretch-illustration-codesweetly.png" alt="Illustration of align-items' stretch value" width="600" height="400" loading="lazy">
<em>stretch stretches a flexible container's items to fill the flexbox's cross-axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-items</span>: stretch;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">300px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ezugee?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>stretch</code> value to stretch the flexible items to fill the <code>&lt;section&gt;</code>'s cross-axis.</p>
<h3 id="heading-what-is-align-items-flex-start-in-css-flexbox">What is <code>align-items: flex-start</code> in CSS Flexbox?</h3>
<p><code>flex-start</code> aligns a flexible container's items with the cross-start edge of the flexbox's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-items-flex-start-illustration-codesweetly.png" alt="Illustration of align-items' flex-start value" width="600" height="400" loading="lazy">
<em>flex-start aligns a flexible container's items with the cross-start edge of the flexbox's cross-axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-items</span>: flex-start;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">300px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-cjzhj2?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>flex-start</code> value to align the flexible items to the cross-start edge of the <code>&lt;section&gt;</code>'s cross-axis.</p>
<h3 id="heading-what-is-align-items-center-in-css-flexbox">What is <code>align-items: center</code> in CSS Flexbox?</h3>
<p><code>center</code> aligns a flexible container's items to the center of the flexbox's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-items-center-illustration-codesweetly.png" alt="Illustration of align-items' center value" width="600" height="400" loading="lazy">
<em>center aligns a flexible container's items to the center of the flexbox's cross-axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">300px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ywexqr?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>center</code> value to align the flexible items to the center of the <code>&lt;section&gt;</code>'s cross-axis.</p>
<h3 id="heading-what-is-align-items-flex-end-in-css-flexbox">What is <code>align-items: flex-end</code> in CSS Flexbox?</h3>
<p><code>flex-end</code> aligns a flexible container's items with the cross-end edge of the flexbox's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-items-flex-end-illustration-codesweetly.png" alt="Illustration of align-items' flex-end value" width="600" height="400" loading="lazy">
<em>flex-end aligns a flexible container's items with the cross-end edge of the flexbox's cross-axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-items</span>: flex-end;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">300px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-bwdeyz?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>flex-end</code> value to align the flexible items to the cross-end edge of the <code>&lt;section&gt;</code>'s cross-axis.</p>
<h3 id="heading-what-is-align-items-baseline-in-css-flexbox">What is <code>align-items: baseline</code> in CSS Flexbox?</h3>
<p><code>baseline</code> aligns a flexible container's items with the <a target="_blank" href="https://stackoverflow.com/a/34611670/11841906">baseline</a> of the flexbox's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-items-baseline-illustration-codesweetly.png" alt="Illustration of align-items' baseline value" width="600" height="400" loading="lazy">
<em>baseline aligns a flexible container's items with the baseline of the flexbox's cross-axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-items</span>: baseline;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-xxvj57?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>baseline</code> value to align the flexible items to the <code>&lt;section&gt;</code>'s baseline.</p>
<p>Now, let's talk about the sixth CSS flexible container property type.</p>
<h2 id="heading-what-is-flexboxs-align-content-property">What Is Flexbox's <code>align-content</code> Property?</h2>
<p><strong>align-content</strong> specifies how browsers should position a flexible container's lines along the flexbox's <a target="_blank" href="https://codesweetly.com/css-flex-direction-property#main-axis-vs-cross-axis-whats-the-difference">cross-axis</a>.</p>
<p><strong>Note:</strong> The <code>align-content</code> property does not affect a flexbox with only one line—for instance, a flexible container with <code>flex-wrap: nowrap</code>. In other words, <code>align-content</code> works only on flexboxes with multiple lines.</p>
<p>The <code>align-content</code> property accepts the following values:</p>
<ul>
<li><code>stretch</code></li>
<li><code>flex-start</code></li>
<li><code>center</code></li>
<li><code>flex-end</code></li>
<li><code>space-between</code></li>
<li><code>space-around</code></li>
<li><code>space-evenly</code></li>
</ul>
<p>Let's discuss the seven values.</p>
<h3 id="heading-what-is-align-content-stretch-in-css-flexbox">What is <code>align-content: stretch</code> in CSS Flexbox?</h3>
<p><code>stretch</code> is <code>align-content</code>'s default value. It stretches the flexible container's lines to fill the flexbox's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-content-stretch-illustration-codesweetly.png" alt="Illustration of align-content's stretch value" width="600" height="400" loading="lazy">
<em>stretch stretches the flexible container's lines to fill the flexbox's cross-axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
  <span class="hljs-attribute">align-content</span>: stretch;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">90px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">500px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-dway6n?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>stretch</code> value to stretch the flexbox's lines to fill the <code>&lt;section&gt;</code>'s cross-axis.</p>
<h3 id="heading-what-is-align-content-flex-start-in-css-flexbox">What is <code>align-content: flex-start</code> in CSS Flexbox?</h3>
<p><code>flex-start</code> aligns a flexible container's lines with the cross-start edge of the flexbox's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-content-flex-start-illustration-codesweetly.png" alt="Illustration of align-content's flex-start value" width="600" height="400" loading="lazy">
<em>flex-start aligns a flexible container's lines with the cross-start edge of the flexbox's cross-axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
  <span class="hljs-attribute">align-content</span>: flex-start;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">90px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">500px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-c9pzbc?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>flex-start</code> value to align the flexbox's lines to the cross-start edge of the <code>&lt;section&gt;</code>'s cross-axis.</p>
<h3 id="heading-what-is-align-content-center-in-css-flexbox">What is <code>align-content: center</code> in CSS Flexbox?</h3>
<p><code>center</code> aligns a flexible container's lines to the center of the flexbox's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-content-center-illustration-codesweetly.png" alt="Illustration of align-content's center value" width="600" height="400" loading="lazy">
<em>center aligns a flexible container's lines to the center of the flexbox's cross-axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
  <span class="hljs-attribute">align-content</span>: center;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">90px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">500px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-j3poyu?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>center</code> value to align the flexbox's lines to the center of the <code>&lt;section&gt;</code>'s cross-axis.</p>
<h3 id="heading-what-is-align-content-flex-end-in-css-flexbox">What is <code>align-content: flex-end</code> in CSS Flexbox?</h3>
<p><code>flex-end</code> aligns a flexible container's lines with the cross-end edge of the flexbox's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-content-flex-end-illustration-codesweetly.png" alt="Illustration of align-content's flex-end value" width="600" height="400" loading="lazy">
<em>flex-end aligns a flexible container's lines with the cross-end edge of the flexbox's cross-axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
  <span class="hljs-attribute">align-content</span>: flex-end;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">90px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">500px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-cmaz6z?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>flex-end</code> value to align the flexbox's lines to the cross-end edge of the <code>&lt;section&gt;</code>'s cross-axis.</p>
<h3 id="heading-what-is-align-content-space-between-in-css-flexbox">What is <code>align-content: space-between</code> in CSS Flexbox?</h3>
<p><code>space-between</code> does the following:</p>
<ul>
<li>It aligns the flexbox's first line with the main-start edge of the flexible container's main axis.</li>
<li>It aligns the flexbox's last line with the main-end side of the flexible container's main axis.</li>
<li>It creates equal spacing between each pair of lines between the first and last line.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-content-space-between-illustration-codesweetly.png" alt="Illustration of align-content's space-between value" width="600" height="400" loading="lazy">
<em>space-between creates equal spacing between each pair of lines between the first and last line</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
  <span class="hljs-attribute">align-content</span>: space-between;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">90px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">500px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-kltdwx?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>space-between</code> value to create equal spacing between each pair of lines between the first and last line.</p>
<h3 id="heading-what-is-align-content-space-around-in-css-flexbox">What is <code>align-content: space-around</code> in CSS Flexbox?</h3>
<p><code>space-around</code> assigns equal spacing to each side of a flexible container's lines.</p>
<p>Therefore, the space before the first line and after the last one is half the width of the space between each pair of lines.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-content-space-around-illustration-codesweetly.png" alt="Illustration of align-content's space-around value" width="600" height="400" loading="lazy">
<em>space-around assigns equal spacing to each side of a flexible container's lines.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
  <span class="hljs-attribute">align-content</span>: space-around;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">90px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">500px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-kx9gdy?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>space-around</code> value to assign equal spacing to each side of the flexible container's lines.</p>
<h3 id="heading-what-is-align-content-space-evenly-in-css-flexbox">What is <code>align-content: space-evenly</code> in CSS Flexbox?</h3>
<p><code>space-evenly</code> assigns even spacing to both ends of a flexible container and between its lines.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-content-space-evenly-illustration-codesweetly.png" alt="Illustration of align-content's space-evenly value" width="600" height="400" loading="lazy">
<em>space-evenly assigns even spacing to both ends of a flexible container and between its lines.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
  <span class="hljs-attribute">align-content</span>: space-evenly;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">90px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">500px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-eevqoj?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>space-evenly</code> value to assign even spacing to both ends of the flexbox and between its lines.</p>
<p>So, now that we know the types of CSS flexible container properties, we can discuss the flex item properties.</p>
<h2 id="heading-what-are-the-flexible-items-properties">What Are the Flexible Item's Properties?</h2>
<p>A flexible item's properties specify how browsers should layout a specified item within the flexible box model.</p>
<p><strong>Note:</strong> We define a flexible item's property on the flex item, not its container.</p>
<p>The six (6) types of flex item properties are:</p>
<ul>
<li><code>align-self</code></li>
<li><code>order</code></li>
<li><code>flex-grow</code></li>
<li><code>flex-shrink</code></li>
<li><code>flex-basis</code></li>
<li><code>flex</code></li>
</ul>
<p>Let's discuss the six types now.</p>
<h2 id="heading-what-is-flexboxs-align-self-property">What Is Flexbox's <code>align-self</code> Property?</h2>
<p><strong>align-self</strong> specifies how browsers should position selected flexible items along the flexbox's <a target="_blank" href="https://codesweetly.com/css-flex-direction-property#main-axis-vs-cross-axis-whats-the-difference">cross-axis</a>.</p>
<p><strong>Note:</strong></p>
<ul>
<li><code>align-self</code> affects only the selected flexible item—not all the flexbox's items.</li>
<li><code>align-self</code> overrides the <code>align-items</code> property.</li>
</ul>
<p>The <code>align-self</code> property accepts the following values:</p>
<ul>
<li><code>stretch</code></li>
<li><code>flex-start</code></li>
<li><code>center</code></li>
<li><code>flex-end</code></li>
<li><code>baseline</code></li>
</ul>
<p>Let's discuss the five values.</p>
<h3 id="heading-what-is-align-self-stretch-in-css-flexbox">What is <code>align-self: stretch</code> in CSS Flexbox?</h3>
<p><code>stretch</code> stretches the selected flexible items to fill the flexbox's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-self-stretch-illustration-codesweetly.png" alt="Illustration of align-self's stretch value" width="600" height="400" loading="lazy">
<em>stretch stretches the selected flexible item(s) to fill the flexbox's cross-axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item2</span> {
  <span class="hljs-attribute">align-self</span>: stretch;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-o5qr62?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>stretch</code> value to stretch <code>flex-item2</code> to fill its container's cross-axis.</p>
<h3 id="heading-what-is-align-self-flex-start-in-css-flexbox">What is <code>align-self: flex-start</code> in CSS Flexbox?</h3>
<p><code>flex-start</code> aligns the selected flexible items with the cross-start edge of the flexbox's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-self-flex-start-illustration-codesweetly.png" alt="Illustration of align-self's flex-start value" width="600" height="400" loading="lazy">
<em>flex-start aligns the selected flexible item(s) with the cross-start edge of the flexbox's cross-axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item2</span> {
  <span class="hljs-attribute">align-self</span>: flex-start;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-6uianm?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>flex-start</code> value to align <code>flex-item2</code> to the cross-start edge of its container's cross-axis.</p>
<h3 id="heading-what-is-align-self-center-in-css-flexbox">What is <code>align-self: center</code> in CSS Flexbox?</h3>
<p><code>center</code> aligns the selected flexible items to the center of the flexbox's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-self-center-illustration-codesweetly.png" alt="Illustration of align-self's center value" width="600" height="400" loading="lazy">
<em>center aligns the selected flexible item(s) to the center of the flexbox's cross-axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item2</span> {
  <span class="hljs-attribute">align-self</span>: center;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-tazf2p?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>center</code> value to align <code>flex-item2</code> to the center of its container's cross-axis.</p>
<h3 id="heading-what-is-align-self-flex-end-in-css-flexbox">What is <code>align-self: flex-end</code> in CSS Flexbox?</h3>
<p><code>flex-end</code> aligns the selected flexible items with the cross-end edge of the flexbox's cross-axis.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/css-align-self-flex-end-illustration-codesweetly.png" alt="Illustration of align-self's flex-end value" width="600" height="400" loading="lazy">
<em>flex-end aligns the selected flexible item(s) with the cross-end edge of the flexbox's cross-axis.</em></p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item2</span> {
  <span class="hljs-attribute">align-self</span>: flex-end;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-7bec4q?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the <code>flex-end</code> value to align <code>flex-item2</code> to the cross-end edge of its container's cross-axis.</p>
<h3 id="heading-what-is-align-self-baseline-in-css-flexbox">What is <code>align-self: baseline</code> in CSS Flexbox?</h3>
<p><code>baseline</code> aligns the selected flexible items with the <a target="_blank" href="https://stackoverflow.com/a/34611670/11841906">baseline</a> of the flexbox's cross-axis.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item2</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">3rem</span>;
  <span class="hljs-attribute">align-self</span>: baseline;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-wmawek?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>baseline</code> value to align <code>flex-item2</code> to its container's baseline.</p>
<p>Let's now discuss the second type of flexible item property.</p>
<h2 id="heading-what-is-flexboxs-order-property">What Is Flexbox's <code>order</code> Property?</h2>
<p><strong>order</strong> changes a flexible item's default order (arrangement).</p>
<p>In other words, <code>order</code> allows you to reposition a flexbox's item without altering your HTML code's layout.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"display: flex; flex-direction: column"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"order: 6"</span>&gt;</span>1<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"order: 4"</span>&gt;</span>2<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"order: 1"</span>&gt;</span>3<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"order: 7"</span>&gt;</span>4<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"order: 2"</span>&gt;</span>5<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"order: 5"</span>&gt;</span>6<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"order: 3"</span>&gt;</span>7<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-hmz9my?file=index.html"><strong>Try it on StackBlitz</strong></a></p>
<p>The HTML snippet above used the <code>order</code> property to change the unordered list's arrangement.</p>
<p>So, instead of the following order:</p>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>
<p>The browser will display this:</p>
<ul>
<li>3</li>
<li>5</li>
<li>7</li>
<li>2</li>
<li>6</li>
<li>1</li>
<li>4</li>
</ul>
<p>Use the <code>order</code> property with caution, as it prevents screen readers from accessing the correct reading order of an HTML document. Only use it if it is super important to use CSS to change the HTML code's layout.</p>
<p>But in most cases, it is best to rearrange the HTML code directly rather than using CSS.</p>
<p><strong>Note:</strong> The <code>style="value"</code> syntax, in the HTML snippet above, is the <a target="_blank" href="https://codesweetly.com/inline-vs-internal-vs-external-css#what-is-an-inline-css">inline CSS</a> technique for styling HTML elements.</p>
<h2 id="heading-what-is-flexboxs-flex-grow-property">What Is Flexbox's <code>flex-grow</code> Property?</h2>
<p><strong>flex-grow</strong> tells browsers how much of the flexbox's left-over space they should add to the selected flexible item's size.</p>
<p><strong>Note:</strong> A left-over space refers to the space remaining after browsers have deducted the sum of all flexible items' sizes from the flexbox's size.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item3</span> {
  <span class="hljs-attribute">flex-grow</span>: <span class="hljs-number">0.5</span>;
}
</code></pre>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">section</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flex-item1"</span>&gt;</span>1<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flex-item2"</span>&gt;</span>2<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flex-item3"</span>&gt;</span>3<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flex-item4"</span>&gt;</span>4<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">section</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-grtdo1?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>flex-grow</code> property to make browsers add half of <code>&lt;section&gt;</code>'s left-over space to <code>flex-item3</code>'s size.</p>
<p><strong>Note:</strong> <code>flex-grow</code>'s default value is <code>0</code>.</p>
<h2 id="heading-what-is-flexboxs-flex-shrink-property">What Is Flexbox's <code>flex-shrink</code> Property?</h2>
<p><strong>flex-shrink</strong> tells browsers how much the specified flexible item should shrink when the sum of all items' sizes exceeds the flexbox's size.</p>
<p>In other words, suppose the flexbox's size is insufficient to fit the flexible items. In that case, browsers will shrink the items to fit the container.</p>
<p>Therefore, <code>flex-shrink</code> allows you to specify the shrinking factor of a flexible item.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item3</span> {
  <span class="hljs-attribute">flex-shrink</span>: <span class="hljs-number">0</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-h2numw?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>flex-shrink</code> property to prevent browsers from shrinking <code>flex-item3</code>.</p>
<p><strong>Note:</strong></p>
<ul>
<li>Browsers will not shrink flexible items with a <code>flex-shrink</code> value of <code>0</code>.</li>
<li><code>flex-shrink</code>'s default value is <code>1</code>.</li>
</ul>
<h2 id="heading-what-is-flexboxs-flex-basis-property">What Is Flexbox's <code>flex-basis</code> Property?</h2>
<p><strong>flex-basis</strong> sets the initial length of a flexible item.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item3</span> {
  <span class="hljs-attribute">flex-basis</span>: <span class="hljs-number">100px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-kwcche?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<p>We used the <code>flex-basis</code> property to set <code>flex-item3</code>'s initial length to <code>100px</code>.</p>
<p><strong>Note the following:</strong></p>
<ul>
<li><code>auto</code> is <code>flex-basis</code>' default value.</li>
<li>A <code>flex-basis</code>' value (other than <code>auto</code>) has higher specificity than <code>width</code> (or <code>height</code>). Therefore, suppose you define both for a flexible item. In that case, browsers will use <code>flex-basis</code>.</li>
<li>The <code>flex-basis</code> property sets the <a target="_blank" href="https://codesweetly.com/css-box-model#what-is-a-content-box">content box</a>'s initial width. But you can use the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing">box-sizing</a> property to make it set the <a target="_blank" href="https://codesweetly.com/css-box-model#what-is-a-border-box">border box</a>'s width instead.</li>
</ul>
<h2 id="heading-what-is-flexboxs-flex-property">What Is Flexbox's <code>flex</code> Property?</h2>
<p><strong>flex</strong> is a shorthand for the <code>flex-grow</code>, <code>flex-shrink</code>, and <code>flex-basis</code> properties.</p>
<p>In other words, instead of writing:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item3</span> {
  <span class="hljs-attribute">flex-grow</span>: <span class="hljs-number">0.5</span>;
  <span class="hljs-attribute">flex-shrink</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">flex-basis</span>: <span class="hljs-number">100px</span>;
}
</code></pre>
<p>You can alternatively use the <code>flex</code> property to shorten your code like so:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item3</span> {
  <span class="hljs-attribute">flex</span>: <span class="hljs-number">0.5</span> <span class="hljs-number">0</span> <span class="hljs-number">100px</span>;
}
</code></pre>
<p><strong>Note the following:</strong></p>
<ul>
<li><code>flex: auto</code> is equivalent to <code>flex: 1 1 auto</code>.</li>
<li><code>flex: none</code> is equivalent to <code>flex: 0 0 auto</code>.</li>
<li><code>flex: initial</code> sets the <code>flex</code> property to its default value. It is equivalent to <code>flex: 0 1 auto</code>.</li>
<li><code>flex: inherit</code> inherits its parent element's <code>flex</code> property's values.</li>
</ul>
<p>So, now that we know the flexbox properties developers use to layout flexible boxes and their direct children, we can discuss how to center elements with flexbox.</p>
<h2 id="heading-how-to-center-elements-horizontally-with-flexbox">How to Center Elements Horizontally with Flexbox</h2>
<p>You can center any element horizontally within its container by:</p>
<ul>
<li>Setting its container's <code>display</code> property to <code>flex</code></li>
<li>Setting the flexible container's <code>justify-content</code> property to <code>center</code></li>
</ul>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">400px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-trl46e?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<h2 id="heading-how-to-center-elements-vertically-with-flexbox">How to Center Elements Vertically with Flexbox</h2>
<p>You can center any element vertically within its container by:</p>
<ul>
<li>Setting its container's <code>display</code> property to <code>flex</code></li>
<li>Setting the flexible container's <code>align-items</code> property to <code>center</code></li>
</ul>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">400px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-tm1don?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<h2 id="heading-how-to-center-elements-horizontally-and-vertically-with-flexbox">How to Center Elements Horizontally and Vertically with Flexbox</h2>
<p>You can center any HTML element horizontally and vertically within its container by:</p>
<ul>
<li>Setting its container's <code>display</code> property to <code>flex</code></li>
<li>Setting the flexible container's <code>justify-content</code> and <code>align-items</code> properties to <code>center</code></li>
</ul>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-tag">section</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">background-color</span>: orange;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">400px</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ryzwmq?file=style.css"><strong>Try it on StackBlitz</strong></a></p>
<h2 id="heading-overview">Overview</h2>
<p>In this article, we discussed all the Flexbox tools you need to create basic and advanced website layouts in flexible and responsive ways.</p>
<h3 id="heading-thanks-for-reading">Thanks for reading!</h3>
<p>If you like the images I used in this tutorial, you can get them all in <a target="_blank" href="https://store.codesweetly.com/l/css-flexbox-explained-visually">this booklet</a>.</p>
<h3 id="heading-and-heres-a-useful-reactjs-resource">And here's a useful ReactJS resource:</h3>
<p>I wrote a book about React!</p>
<ul>
<li>It's beginner friendly ✔</li>
<li>It has live code snippets ✔</li>
<li>It contains scalable projects ✔</li>
<li>It has plenty of easy-to-grasp examples ✔</li>
</ul>
<p>The <a target="_blank" href="https://www.amazon.com/dp/B09KYGDQYW">React Explained Clearly</a> book is all you need to understand ReactJS.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B09KYGDQYW"><img src="https://www.freecodecamp.org/news/content/images/2022/01/Twitter-React_Explained_Clearly-CodeSweetly-Oluwatobi_Sofela.jpg" alt="React Explained Clearly Book Now Available at Amazon" width="600" height="400" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Functions Tutorial – IIFE, Function Parameters, and Code Blocks Explained ]]>
                </title>
                <description>
                    <![CDATA[ Functions are one of the most widely-used features in programming. So, it helps to have a solid understanding of how they work. This tutorial discusses everything you need to know to use JavaScript functions like a pro. Table of Contents What Is a F... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-function-iife-parameters-code-blocks-explained/</link>
                <guid isPermaLink="false">66ba0df8d14c87384322b680</guid>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Functional Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Wed, 05 Oct 2022 16:06:29 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/programming-image-by-mohamed-hassan-from-pixabay-javascript-function-iffe-parameters-blocks-explained-codesweetly.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Functions are one of the most widely-used features in programming. So, it helps to have a solid understanding of how they work.</p>
<p>This tutorial discusses everything you need to know to use JavaScript functions like a pro.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-a-function">What Is a Function?</a></li>
<li><a class="post-section-overview" href="#heading-why-functions">Why Functions?</a></li>
<li><a class="post-section-overview" href="#heading-syntax-of-a-javascript-function-1">Syntax of a JavaScript Function</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-function-keyword">What Is a <code>function</code> Keyword?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-function-name">What Is a Function Name?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-parameter">What Is a Parameter?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-code-block">What Is a Code Block?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-function-body">What Is a Function Body?</a></li>
<li><a class="post-section-overview" href="#heading-types-of-javascript-functions">Types of JavaScript Functions</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-javascript-function-declaration">What Is a JavaScript Function Declaration?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-javascript-function-expression">What Is a JavaScript Function Expression?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-javascript-arrow-function-expression">What Is a JavaScript Arrow Function Expression?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-javascript-immediately-invoked-function-expression">What Is a JavaScript Immediately Invoked Function Expression?</a></li>
<li><a class="post-section-overview" href="#heading-overview">Overview</a></li>
</ol>
<p>So, let's get started from the basics.</p>
<h2 id="heading-what-is-a-function">What Is a Function?</h2>
<p>A <strong>JavaScript function</strong> is an executable piece of code developers use to bundle a block of zero or more statements.</p>
<p>In other words, a function is an executable subprogram (mini-program).</p>
<p>A JavaScript function is a subprogram because its body consists of a series of statements (instructions) to computers—just like a regular program.</p>
<p>The instructions in a function's body can be a <a target="_blank" href="https://codesweetly.com/javascript-variable#example-3-javascript-variable">variable</a> declaration, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return">return</a> call, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/console/log">console.log()</a> invocation, <a class="post-section-overview" href="#heading-syntax-of-a-javascript-function-1">function</a> definition, or any other JavaScript <a target="_blank" href="https://codesweetly.com/javascript-statement">statements</a>.</p>
<p><strong>Note:</strong></p>
<ul>
<li>A program is a list of instructions written for computers to execute.</li>
<li>Unlike other <a target="_blank" href="https://codesweetly.com/javascript-non-primitive-data-type#types-of-javascript-objects">object types</a>, you can invoke a function without storing it in a variable.</li>
<li>A JavaScript function is similar to other programming languages' procedures or subroutines.</li>
</ul>
<h2 id="heading-why-functions">Why Functions?</h2>
<p>Functions provide a way to bundle pieces of code together and reuse them anytime, anywhere, for an unlimited period. This helps you eliminate the burden of writing the same set of code repeatedly.</p>
<p>For instance, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window/alert">alert()</a> is a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window">built-in window function</a> that someone wrote once for all developers to use anytime, anywhere.</p>
<h2 id="heading-syntax-of-a-javascript-function">Syntax of a JavaScript Function</h2>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">nameOfFunction</span>(<span class="hljs-params">parameter1, parameter2, ..., parameterX</span>) </span>{
  <span class="hljs-comment">// function's body</span>
}
</code></pre>
<p>A function is composed of five elements:</p>
<ol>
<li>A <code>function</code> keyword</li>
<li>The function's name</li>
<li>A list of zero or more parameters</li>
<li>A code block (<code>{...}</code>)</li>
<li>The function's body</li>
</ol>
<p>Let's discuss each element.</p>
<h2 id="heading-what-is-a-function-keyword">What Is a <code>function</code> Keyword?</h2>
<p>We use the <code>function</code> keyword to declare to browsers that a specific piece of code is a JavaScript function—not a mathematical or other generic function.</p>
<h2 id="heading-what-is-a-function-name">What Is a Function Name?</h2>
<p>A <strong>function's name</strong> allows you to create an identifier for your function, which you can use to reference it.</p>
<h2 id="heading-what-is-a-parameter">What Is a Parameter?</h2>
<p>A <strong>parameter</strong> specifies the name you wish to call your function's <a target="_blank" href="https://codesweetly.com/javascript-arguments">argument</a>.</p>
<p>A parameter is an optional component of a function. In other words, you do not need to specify a parameter if your function does not accept any argument.</p>
<p>For instance, JavaScript's <a target="_blank" href="https://codesweetly.com/javascript-pop-method">pop()</a> method is a function without any parameter because it does not accept arguments.</p>
<p>On the other hand, <a target="_blank" href="https://codesweetly.com/javascript-foreach-method">forEach()</a> has two parameters that accept two arguments.</p>
<h3 id="heading-example-of-a-javascript-parameter">Example of a JavaScript parameter</h3>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function with two parameters:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myName</span>(<span class="hljs-params">firstName, lastName</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My full name is <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>.`</span>);
}

<span class="hljs-comment">// Invoke myName function while passing two arguments to its parameters:</span>
myName(<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"My full name is Oluwatobi Sofela."</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-edvj3g?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The <code>myName()</code> function in the snippet above has two parameters: <code>firstName</code> and <code>lastName</code>.</p>
<p>Suppose you wish to pre-define values for your parameters that browsers can use if users do not invoke the function with the required arguments. In that case, you can create default parameters.</p>
<h3 id="heading-what-is-a-default-parameter">What is a default parameter?</h3>
<p><strong>Default parameters</strong> allow you to initialize your function's parameters with default values.</p>
<p>For instance, suppose users invoke your function without providing a required argument. In such a case, browsers will set the parameter's value to <code>undefined</code>.</p>
<p>However, default parameters allow you to define the values browsers should use instead of <code>undefined</code>.</p>
<h3 id="heading-examples-of-default-parameters">Examples of default parameters</h3>
<p>Below are examples of how default parameters work in JavaScript.</p>
<h4 id="heading-how-to-define-a-function-with-no-default-parameters">How to define a function with no default parameters</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function with two parameters:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myName</span>(<span class="hljs-params">firstName, lastName</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My full name is <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>.`</span>);
}

<span class="hljs-comment">// Invoke myName function while passing one argument to its parameters:</span>
myName(<span class="hljs-string">"Oluwatobi"</span>);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"My full name is Oluwatobi undefined."</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-9ce3xt?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The computer automatically set the <code>lastName</code> parameter to <code>undefined</code> because we did not provide a default value.</p>
<h4 id="heading-how-to-define-a-function-with-an-undefined-argument-and-no-default-parameter">How to define a function with an <code>undefined</code> argument and no default parameter</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function with two parameters:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myName</span>(<span class="hljs-params">firstName, lastName</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My full name is <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>.`</span>);
}

<span class="hljs-comment">// Invoke myName function while passing two arguments to its parameters:</span>
myName(<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-literal">undefined</span>);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"My full name is Oluwatobi undefined."</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-csbxta?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The computer set the <code>lastName</code> parameter to <code>undefined</code> because we provided <code>undefined</code> as <code>myName()</code>'s second argument.</p>
<h4 id="heading-how-to-define-a-function-with-a-default-parameter">How to define a function with a default parameter</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function with two parameters:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myName</span>(<span class="hljs-params">firstName, lastName = <span class="hljs-string">"Sofela"</span></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My full name is <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>.`</span>);
}

<span class="hljs-comment">// Invoke myName function while passing one argument to its parameters:</span>
myName(<span class="hljs-string">"Oluwatobi"</span>);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"My full name is Oluwatobi Sofela."</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ghiyzm?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Instead of <code>undefined</code>, JavaScript used <code>"Sofela"</code> as the <code>lastName</code> parameter's default argument.</p>
<h4 id="heading-how-to-define-a-function-with-an-undefined-argument-and-a-default-parameter">How to define a function with an <code>undefined</code> argument and a default parameter</h4>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function with two parameters:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myName</span>(<span class="hljs-params">firstName, lastName = <span class="hljs-string">"Sofela"</span></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My full name is <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>.`</span>);
}

<span class="hljs-comment">// Invoke myName function while passing two arguments to its parameters:</span>
myName(<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-literal">undefined</span>);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"My full name is Oluwatobi Sofela."</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-umqgqp?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Instead of <code>undefined</code>, JavaScript used <code>"Sofela"</code> as the <code>lastName</code> parameter's default argument.</p>
<p>Let's now discuss the fourth element of a JavaScript function: a <strong>code block.</strong></p>
<h2 id="heading-what-is-a-code-block">What Is a Code Block?</h2>
<p>A <strong>block</strong> is a pair of braces (<code>{...}</code>) used to group multiple statements together.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js">{
  <span class="hljs-keyword">const</span> hourNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours();
}
</code></pre>
<p>The block in the snippet above encased one JavaScript <a target="_blank" href="https://codesweetly.com/javascript-statement">statement</a>.</p>
<p><strong>Here's another example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours() &lt; <span class="hljs-number">18</span>) {
  <span class="hljs-keyword">const</span> hourNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours();
  <span class="hljs-keyword">const</span> minutesNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getMinutes();
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The time is <span class="hljs-subst">${hourNow}</span>:<span class="hljs-subst">${minutesNow}</span>.`</span>);
}
</code></pre>
<p>The <code>if</code> condition's code block grouped three JavaScript statements together.</p>
<p><strong>Now, consider this snippet:</strong></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getTime</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> hourNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getHours();
  <span class="hljs-keyword">const</span> minutesNow = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getMinutes();
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The time is <span class="hljs-subst">${hourNow}</span>:<span class="hljs-subst">${minutesNow}</span>.`</span>);
}
</code></pre>
<p>The <code>getTime()</code> function's code block grouped three JavaScript statements. Note that the "function body" is the space inside the function's code block. Let's talk more about it now.</p>
<h2 id="heading-what-is-a-function-body">What Is a Function Body?</h2>
<p>A <strong>function body</strong> is where you place a sequence of statements you want to execute.</p>
<h3 id="heading-syntax-of-a-javascript-function-body">Syntax of a JavaScript function body</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">nameOfFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// function's body</span>
}
</code></pre>
<h3 id="heading-function-body-examples">Function body examples</h3>
<p>Below are examples of how we use the function body.</p>
<h4 id="heading-how-to-define-a-function-with-three-statements-in-its-body">How to define a function with three statements in its body</h4>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getName</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> firstName = <span class="hljs-string">"Oluwatobi"</span>;
  <span class="hljs-keyword">const</span> lastName = <span class="hljs-string">"Sofela"</span>;
  <span class="hljs-built_in">console</span>.log(firstName + <span class="hljs-string">" "</span> + lastName);
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-flz5tf?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, the function's body contains three statements that the computer will execute whenever the function gets invoked.</p>
<p><strong>Note:</strong> <code>console.log()</code> is a <a target="_blank" href="https://codesweetly.com/web-tech-terms-m#method">method</a> we use to log (write) messages to a web console.</p>
<h4 id="heading-how-to-define-a-function-with-two-statements-in-its-body">How to define a function with two statements in its body</h4>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bestColors = [<span class="hljs-string">"Coral"</span>, <span class="hljs-string">"Blue"</span>, <span class="hljs-string">"DeepPink"</span>];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateMyBestColors</span>(<span class="hljs-params">previousColors, newColor</span>) </span>{
   <span class="hljs-keyword">const</span> mybestColors = [...previousColors, newColor];
   <span class="hljs-keyword">return</span> mybestColors;
}

updateMyBestColors(bestColors, <span class="hljs-string">"GreenYellow"</span>);
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-nb9sr6?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, the function's body contains two statements that the computer will execute whenever the function gets invoked.</p>
<p><strong>Note:</strong></p>
<ul>
<li>The three dots we prepended to <code>previousColors</code> is called a <a target="_blank" href="https://codesweetly.com/spread-operator">spread operator</a>. We used it to expand the <a target="_blank" href="https://codesweetly.com/javascript-array-object">array</a> argument into individual elements.</li>
<li>You can also prepend the <code>newColor</code> parameter with a <a target="_blank" href="https://codesweetly.com/javascript-rest-operator">rest operator</a> if you wish to add two or more new colors.</li>
<li>The <code>return</code> keyword ends its function's execution and returns the specified <a target="_blank" href="https://codesweetly.com/javascript-statement#what-is-a-javascript-expression-statement">expression</a> (or <code>undefined</code> if you provide no expression).</li>
</ul>
<p>So, now that we know the components of a JavaScript function, we can discuss its types.</p>
<h2 id="heading-types-of-javascript-functions">Types of JavaScript Functions</h2>
<p>The four types of JavaScript functions are:</p>
<ul>
<li>Function declaration</li>
<li>Function expression</li>
<li>Arrow function expression</li>
<li>Immediately invoking function expression</li>
</ul>
<p>Let's discuss each type.</p>
<h2 id="heading-what-is-a-javascript-function-declaration">What Is a JavaScript Function Declaration?</h2>
<p>A <strong>function declaration</strong> is a function created without assigning it to a <a target="_blank" href="https://codesweetly.com/javascript-variable">variable</a>.</p>
<p><strong>Note:</strong> We sometimes call function declaration a "function definition" or "function statement."</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-number">100</span> + <span class="hljs-number">20</span>;
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-pwh2jr?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The function above is a function declaration because we defined it without storing it in a variable.</p>
<h2 id="heading-what-is-a-javascript-function-expression">What Is a JavaScript Function Expression?</h2>
<p>A <strong>function expression</strong> is a function you create and assign to a variable.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-number">100</span> + <span class="hljs-number">20</span>;
};
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-hjg1iq?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The function above is a <strong>named</strong> function expression that we assigned to the <code>myFuncExpr</code> variable.</p>
<p>You can also write the snippet above as an <strong>anonymous</strong> function expression like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-number">100</span> + <span class="hljs-number">20</span>;
};
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-pmeqy4?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The function above is an anonymous function expression that we assigned to the <code>myFuncExpr</code> variable.</p>
<p><strong>Note:</strong></p>
<ul>
<li>An <strong>anonymous function</strong> is a function with no name.</li>
<li>A <strong>named function</strong> is a function with a name.</li>
</ul>
<p>A named function's main advantage is that the name makes it easier to trace an error's origin.</p>
<p>In other words, suppose your function threw an error. In such a case, if the function is named, a debugger's <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack">stack trace</a> will contain the function's name. Therefore, you will find it easier to identify the error's origin.</p>
<h2 id="heading-what-is-a-javascript-arrow-function-expression">What Is a JavaScript Arrow Function Expression?</h2>
<p>An <strong>arrow function expression</strong> is a shorthand way to write a function expression.</p>
<h3 id="heading-syntax-of-an-arrow-function">Syntax of an arrow function</h3>
<p>We define an arrow function with the equality and the greater-than symbols (<code>=&gt;</code>). Here is the syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> variableName = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// function's body</span>
}
</code></pre>
<h3 id="heading-example-of-an-arrow-function">Example of an arrow function</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-number">100</span> + <span class="hljs-number">20</span>;
};
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-1euhch?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>You can see that we defined the function without a <code>function</code> keyword and a function name.</p>
<p>You have to omit the <code>function</code> keyword and function name while writing an arrow function expression. Otherwise, JavaScript will throw a <code>SyntaxError</code>.</p>
<h3 id="heading-important-stuff-to-know-about-the-javascript-arrow-function-expression">Important stuff to know about the JavaScript arrow function expression</h3>
<p>Here are three essential facts to remember when using an arrow function expression.</p>
<h4 id="heading-1-the-parameters-parentheses-are-optional">1. The parameters' parentheses are optional</h4>
<p>Suppose your arrow function contains only a single parameter. In such a case, you can omit its parentheses.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function"><span class="hljs-params">a</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> a + <span class="hljs-number">20</span>;
};
</code></pre>
<p><a target="_blank" href="https://codepen.io/oluwatobiss/pen/OJQJejr"><strong>Try it on CodePen</strong></a></p>
<h4 id="heading-2-the-curly-brackets-and-return-keyword-are-optional">2. The curly brackets and <code>return</code> keyword are optional</h4>
<p>Suppose your arrow function contains only a single statement. In that case, you can omit its curly brackets and the <code>return</code> keyword.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function">(<span class="hljs-params">x, y</span>) =&gt;</span> x + y;
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-8t2udu?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we implicitly returned the sum of parameters <code>x</code> and <code>y</code> by removing the curly brackets and the <code>return</code> keyword.</p>
<p><strong>Note:</strong> Whenever you choose to omit the curly brackets, also make sure that you remove the <code>return</code> keyword. Otherwise, the computer will throw a <code>SyntaxError</code>.</p>
<h4 id="heading-3-use-parentheses-to-wrap-any-implicit-object-return">3. Use parentheses to wrap any implicit object return</h4>
<p>Suppose you wish to return an object implicitly. In such a case, wrap the object in a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping">grouping operator</a> <code>(...)</code>.</p>
<p>For instance, consider the code below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-attr">carColor</span>: <span class="hljs-string">"White"</span>,
  <span class="hljs-attr">shoeColor</span>: <span class="hljs-string">"Yellow"</span>,
};
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/wrong-way-to-use-an-arrow-function-expression-to-return-an-object-implicitly-s8w132?file=/src/index.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above will throw a <code>SyntaxError</code> because JavaScript assumed the curly brackets (<code>{}</code>) to be the function body's code block—not an <a target="_blank" href="https://codesweetly.com/javascript-properties-object">object literal</a>.</p>
<p>Therefore, whenever you wish to return an object literal implicitly–without using the <code>return</code> keyword explicitly–make sure to encase the object literal in a grouping operator.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function">() =&gt;</span> ({
  <span class="hljs-attr">carColor</span>: <span class="hljs-string">"White"</span>,
  <span class="hljs-attr">shoeColor</span>: <span class="hljs-string">"Yellow"</span>,
});
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/correct-way-to-use-an-arrow-function-expression-to-return-an-object-implicitly-p61l5c?file=/src/index.js"><strong>Try it on CodeSandbox</strong></a></p>
<p>Note that you can use the grouping operator to return any single value. For instance, the snippet below grouped the sum of <code>x</code> and <code>56</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myFuncExpr = <span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> (x + <span class="hljs-number">56</span>);
</code></pre>
<p><a target="_blank" href="https://codepen.io/oluwatobiss/pen/rNJNXeG"><strong>Try it on CodePen</strong></a></p>
<p>Let's now discuss the fourth type of JavaScript function.</p>
<h2 id="heading-what-is-a-javascript-immediately-invoked-function-expression">What Is a JavaScript Immediately Invoked Function Expression?</h2>
<p>An <strong>immediately invoked function expression (IIFE)</strong> is a function expression that invokes itself automatically.</p>
<p><strong>Note:</strong> We sometimes call an IIFE a "Self-Invoking Function Expression" or "Self-Executing Anonymous Function Expression."</p>
<h3 id="heading-syntax-of-an-iife">Syntax of an IIFE</h3>
<pre><code class="lang-js">(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">/* ... */</span>
})();
</code></pre>
<p>An IIFE is composed of three main components:</p>
<ol>
<li><strong>A grouping operator:</strong> The first pair of parentheses <code>()</code></li>
<li><strong>A function:</strong> Enclosed within the grouping operator</li>
<li><strong>An invocator:</strong> The last pair of parentheses <code>()</code></li>
</ol>
<h3 id="heading-examples">Examples</h3>
<p>Below are examples of an IIFE.</p>
<h4 id="heading-how-to-define-a-named-iife">How to define a named IIFE</h4>
<pre><code class="lang-js">(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-number">100</span> + <span class="hljs-number">20</span>);
})();
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-nkjjnz?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The function in the snippet above is a named self-invoking function expression.</p>
<h4 id="heading-how-to-define-an-anonymous-iife">How to define an anonymous IIFE</h4>
<pre><code class="lang-js">(<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-number">100</span> + <span class="hljs-number">20</span>);
})();
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ywrmkt?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The function in the snippet above is an anonymous self-invoking function expression.</p>
<h4 id="heading-how-to-define-an-arrow-function-iife">How to define an arrow function IIFE</h4>
<pre><code class="lang-js">(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-number">100</span> + <span class="hljs-number">20</span>))();
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-xqlfgi?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The function in the snippet above is an arrow self-invoking function expression.</p>
<h4 id="heading-how-to-define-an-async-iife">How to define an async IIFE</h4>
<pre><code class="lang-js">(<span class="hljs-keyword">async</span> () =&gt; <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">await</span> <span class="hljs-number">100</span> + <span class="hljs-number">20</span>))();
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ryxftq?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The function in the snippet above is an <a target="_blank" href="https://codesweetly.com/asynchronous-javascript">asynchronous</a> self-invoking function expression.</p>
<p>So, now that we know what an Immediately Invoked Function Expression is, we can discuss how it works.</p>
<h3 id="heading-how-does-an-iife-work">How does an IIFE work?</h3>
<p>By default, the computer does not know what <a target="_blank" href="https://codesweetly.com/javascript-data-types">data type</a> <a target="_blank" href="https://codesweetly.com/document-vs-data-vs-code#what-exactly-is-code">code</a> is until it evaluates it.</p>
<p>For instance, suppose you ask the computer to process <code>4</code>. In such a case, the system won't know if <code>4</code> is a number type until it evaluates it.</p>
<p>Therefore, JavaScript will throw a <code>SyntaxError</code> if you use any number method directly on <code>4</code>.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Convert 4 to a string value:</span>
<span class="hljs-number">4.</span>toString();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Uncaught SyntaxError: Invalid or unexpected token"</span>
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/how-iife-works-example-1-kc8g5b"><strong>Try it on CodeSandbox</strong></a></p>
<p>The computer threw a <code>SyntaxError</code> because it does not recognize <code>4</code> as a number data type.</p>
<p>However, suppose you assign <code>4</code> to a variable. In such a case, the computer will first convert it to a number data type before storing it into the variable.</p>
<p>Afterward, JavaScript will allow you to use any number methods on the number variable.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Assign 4 to a variable:</span>
<span class="hljs-keyword">const</span> myNum = <span class="hljs-number">4</span>;

<span class="hljs-comment">// Convert myNum's content to a string value:</span>
myNum.toString();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"4"</span>
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/how-iife-works-example-2-jz4kwi"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above did not return any error because JavaScript evaluated <code>myNum</code> as a number data type.</p>
<p>But you don't have to assign <code>4</code> to a variable before the computer can evaluate its data type appropriately.</p>
<p>You can alternatively put your value in <a target="_blank" href="https://www.computerhope.com/jargon/p/parenthe.htm">parentheses</a> to force the computer to evaluate its data type before using it for other things.</p>
<p>For instance, consider this snippet:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Evaluate 4's data type and turn it into a string value:</span>
(<span class="hljs-number">4</span>).toString();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"4"</span>
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/how-iife-works-example-3-rz4j9b"><strong>Try it on CodeSandbox</strong></a></p>
<p>The snippet above enclosed <code>4</code> in parentheses to make the computer evaluate its data type before using the <a target="_blank" href="https://codesweetly.com/javascript-number-tostring-method"><code>toString()</code></a> method to convert it to a string value.</p>
<p>Using parentheses to make JavaScript evaluate your code's data type first is what happens in an Immediately Invoking Function Expression (IIFE).</p>
<p>For instance, consider this example:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Evaluate the function's data type and immediately invoke it:</span>
(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-number">100</span> + <span class="hljs-number">20</span>);
})();

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-number">120</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-nkjjnz?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above enclosed the <code>addNumbers</code> function in parentheses to make the computer evaluate its data type before invoking it immediately after the evaluation.</p>
<h2 id="heading-overview">Overview</h2>
<p>In this article, we discussed what a JavaScript function object is. We also used examples to see how it works.</p>
<p>Thanks for reading.</p>
<h3 id="heading-and-heres-a-useful-reactjs-resource"><strong>And here's a useful ReactJS resource:</strong></h3>
<p>I wrote a book about React!</p>
<ul>
<li>It's beginner friendly ✔</li>
<li>It has live code snippets ✔</li>
<li>It contains scalable projects ✔</li>
<li>It has plenty of easy-to-grasp examples ✔</li>
</ul>
<p>The <a target="_blank" href="https://www.amazon.com/dp/B09KYGDQYW">React Explained Clearly</a> book is all you need to understand ReactJS.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B09KYGDQYW"><img src="https://www.freecodecamp.org/news/content/images/2022/01/Twitter-React_Explained_Clearly-CodeSweetly-Oluwatobi_Sofela.jpg" alt="React Explained Clearly Book Now Available at Amazon" width="600" height="400" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Test-Driven Development Tutorial – How to Test Your JavaScript and ReactJS Applications ]]>
                </title>
                <description>
                    <![CDATA[ Understanding test-driven development is an essential part of being a prolific software developer. Testing provides a solid platform for building reliable programs. This tutorial will show you all you need to implement test-driven development in your... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/test-driven-development-tutorial-how-to-test-javascript-and-reactjs-app/</link>
                <guid isPermaLink="false">66ba0e0ed14c87384322b685</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Testing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ test driven development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Testing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Tue, 26 Jul 2022 17:51:22 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/07/test-driven-development-tutorial-how-to-test-javascript-and-reactjs-app-codesweetly-battlecreek-coffee-roasters-i22gbC3gFm4-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Understanding test-driven development is an essential part of being a prolific software developer. Testing provides a solid platform for building reliable programs.</p>
<p>This tutorial will show you all you need to implement test-driven development in your JavaScript and React applications.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-test-driven-development">What Is Test-Driven Development?</a></li>
<li><a class="post-section-overview" href="#heading-javascript-example-of-a-test-driven-development-workflow">JavaScript Example of a Test-Driven Development Workflow</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-jest-as-a-test-implementation-tool">How to Use Jest as a Test Implementation Tool</a></li>
<li><a class="post-section-overview" href="#heading-important-stuff-to-know-about-using-es6-modules-with-jest">Important Stuff to Know about Using ES6 Modules with Jest</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-advantages-of-test-driven-development">What Are the Advantages of Test-Driven Development?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-unit-test-in-test-driven-development">What is a Unit Test in Test-Driven Development</a>?</li>
<li><a class="post-section-overview" href="#heading-what-is-an-integration-test-in-test-driven-development">What is an Integration Test in Test-Driven Development</a>?</li>
<li><a class="post-section-overview" href="#heading-what-is-an-end-to-end-test-in-test-driven-development">What is an End-to-End Test in Test-Driven Development</a>?</li>
<li><a class="post-section-overview" href="#heading-what-are-test-doubles-in-test-driven-development">What are Test Doubles in Test-Driven Development</a>?</li>
<li><a class="post-section-overview" href="#heading-quick-overview-of-test-driven-development-so-far">Quick Overview of Test-Driven Development So Far</a></li>
<li><a class="post-section-overview" href="#heading-how-to-test-react-components">How to Test React Components</a></li>
<li><a class="post-section-overview" href="#heading-test-runner-vs-react-component-testing-tool-whats-the-difference">Test Runner vs. React Component Testing Tool: What's the Difference?</a></li>
<li><a class="post-section-overview" href="#heading-project-how-react-testing-works">Project: How React Testing Works</a></li>
<li><a class="post-section-overview" href="#heading-overview">Overview</a></li>
</ol>
<p>So, without any further ado, let's get started by discussing what test-driven development means.</p>
<h2 id="heading-what-is-test-driven-development">What Is Test-Driven Development?</h2>
<p><strong>Test-driven development (TDD)</strong> is a coding practice where you write the result you want your program to produce before creating the program.</p>
<p>In other words, TDD requires you to pre-specify the output your intended program must produce to pass the test of functioning the way you envisioned.</p>
<p>So, in an effective test-driven development practice, you would first write tests that express the result you expect from your intended program.</p>
<p>Afterward, you would develop the program to pass the prewritten test.</p>
<p>For instance, suppose you wish to create an addition calculator. In such a case, the TDD approach will be like so:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/07/test-driven-development-tdd-workflow-diagram-codesweetly.png" alt="Test-driven development workflow diagram" width="600" height="400" loading="lazy">
<em>Test-driven development workflow diagram</em></p>
<ol>
<li>Write a test specifying the result you expect the calculator to produce to pass the test of being the program you had in mind.</li>
<li>Develop the calculator to pass the prewritten test.</li>
<li>Run the test to check whether the calculator passes or fails the test.</li>
<li>Refactor your test code (if necessary).</li>
<li>Refactor your program (if necessary).</li>
<li>Continue the cycle until the calculator matches your vision.</li>
</ol>
<p>Let's now see a JavaScript example of a TDD workflow.</p>
<h2 id="heading-javascript-example-of-a-test-driven-development-workflow">JavaScript Example of a Test-Driven Development Workflow</h2>
<p>The steps below will use a simple JavaScript program to show you how to approach TDD.</p>
<h3 id="heading-1-write-your-test">1. Write your test</h3>
<p>Write a test that specifies the result you expect your calculator program to produce:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">additionCalculatorTester</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (additionCalculator(<span class="hljs-number">4</span>, <span class="hljs-number">6</span>) === <span class="hljs-number">10</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"✔ Test Passed"</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"❌ Test Failed"</span>);
  }
}
</code></pre>
<h3 id="heading-2-develop-your-program">2. Develop your program</h3>
<p>Develop the calculator program to pass the prewritten test:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">additionCalculator</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}
</code></pre>
<h3 id="heading-3-run-the-test">3. Run the test</h3>
<p>Run the test to check whether the calculator passes or fails the test:</p>
<pre><code class="lang-js">additionCalculatorTester();
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ciui1u?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<h3 id="heading-4-refactor-the-test">4. Refactor the test</h3>
<p>After you've confirmed that your program passed the prewritten test, it's time to check if there's any need to refactor it.</p>
<p>For instance, you could refactor <code>additionCalculatorTester()</code> to use a <a target="_blank" href="https://codesweetly.com/javascript-statement/#what-is-a-conditional-ternary-operator-in-javascript">conditional operator</a> like so:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">additionCalculatorTester</span>(<span class="hljs-params"></span>) </span>{
  additionCalculator(<span class="hljs-number">4</span>, <span class="hljs-number">6</span>) === <span class="hljs-number">10</span> 
    ? <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"✔ Test Passed"</span>) 
    : <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"❌ Test Failed"</span>);
}
</code></pre>
<h3 id="heading-5-refactor-the-program">5. Refactor the program</h3>
<p>Let's also refactor the program's code to use an <a target="_blank" href="https://codesweetly.com/javascript-function-object#arrow-function-expression-in-javascript">arrow function</a>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> additionCalculator = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b;
</code></pre>
<h3 id="heading-6-run-the-test">6. Run the test</h3>
<p>Rerun the test to ensure your program still works as intended.</p>
<pre><code class="lang-js">additionCalculatorTester();
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-xp732h?devToolsHeight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Notice that in the examples above, we implemented TDD without using any libraries.</p>
<p>But you can also use powerful test-running tools like <a target="_blank" href="https://jasmine.github.io/">Jasmine</a>, <a target="_blank" href="https://mochajs.org/">Mocha</a>, <a target="_blank" href="https://github.com/substack/tape">Tape</a>, and <a target="_blank" href="https://jestjs.io/">Jest</a>, to make your test implementation faster, simpler, and more fun.</p>
<p>Let's see how to use Jest, for example.</p>
<h2 id="heading-how-to-use-jest-as-a-test-implementation-tool">How to Use Jest as a Test Implementation Tool</h2>
<p>Here are the steps you'll need to follow to get started using Jest as your test implementation tool:</p>
<h3 id="heading-step-1-get-the-right-node-and-npm-version">Step 1: Get the right Node and NPM version</h3>
<p>Make sure you have Node 10.16 (or greater) and NPM 5.6 (or greater) installed on your system.</p>
<p>You can get both by installing the latest LTS from the <a target="_blank" href="https://nodejs.org/en/">Node.js</a> website.</p>
<p>If you prefer to use Yarn, ensure you have <a target="_blank" href="https://yarnpkg.com/">Yarn 0.25 (or greater)</a>.</p>
<h3 id="heading-step-2-create-a-project-directory">Step 2: Create a project directory</h3>
<p>Create a new folder for your project.</p>
<pre><code class="lang-bash">mkdir addition-calculator-jest-project
</code></pre>
<h3 id="heading-step-3-navigate-to-your-project-folder">Step 3: Navigate to your project folder</h3>
<p>Using the command line, navigate to your project directory.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> path/to/addition-calculator-jest-project
</code></pre>
<h3 id="heading-step-4-create-a-packagejson-file">Step 4: Create a <code>package.json</code> file</h3>
<p>Initialize a <code>package.json</code> file for your project.</p>
<pre><code class="lang-bash">npm init -y
</code></pre>
<p>Or, if your <a target="_blank" href="https://codesweetly.com/package-manager-explained">package manager</a> is Yarn, run:</p>
<pre><code class="lang-bash">yarn init -y
</code></pre>
<h3 id="heading-step-5-install-jest">Step 5: Install Jest</h3>
<p>Install Jest as a development dependency package like so:</p>
<pre><code class="lang-bash">npm install jest --save-dev
</code></pre>
<p>Alternatively, if your package manager is Yarn, run:</p>
<pre><code class="lang-bash">yarn add jest --dev
</code></pre>
<h3 id="heading-step-6-make-jest-your-projects-test-runner-tool">Step 6: Make Jest your project's test runner tool</h3>
<p>Open your <code>package.json</code> file and add Jest to the <code>test</code> field.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"jest"</span>
  }
}
</code></pre>
<h3 id="heading-step-7-create-your-project-file">Step 7: Create your project file</h3>
<p>Create a file that you will use to develop your program.</p>
<pre><code class="lang-bash">touch additionCalculator.js
</code></pre>
<h3 id="heading-step-8-create-your-test-file">Step 8: Create your test file</h3>
<p>Create a file that you will use to write your test cases.</p>
<pre><code class="lang-bash">touch additionCalculator.test.js
</code></pre>
<p><strong>Note:</strong> Your test file's name must end with <code>.test.js</code>—so that Jest can recognize it as the file containing your test code.</p>
<h3 id="heading-step-9-write-your-test-case">Step 9: Write your test case</h3>
<p>Open your test file and write some test code that specifies the result you expect your program to produce.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// additionCalculator.test.js</span>

<span class="hljs-keyword">const</span> additionCalculator = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./additionCalculator"</span>);

test(<span class="hljs-string">"addition of 4 and 6 to equal 10"</span>, <span class="hljs-function">() =&gt;</span> {
  expect(additionCalculator(<span class="hljs-number">4</span>, <span class="hljs-number">6</span>)).toBe(<span class="hljs-number">10</span>);
});
</code></pre>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>We imported the <code>additionCalculator.js</code> project file into the <code>additionCalculator.test.js</code> test file.</li>
<li>We wrote a test case specifying that we expect the <code>additionCalculator()</code> program to output <code>10</code> whenever users provide <code>4</code> and <code>6</code> as its <a target="_blank" href="https://codesweetly.com/javascript-arguments">argument</a>.</li>
</ol>
<p><strong>Note:</strong></p>
<ul>
<li><a target="_blank" href="https://jestjs.io/docs/api#testname-fn-timeout"><code>test()</code></a> is one of Jest's global methods. It accepts three arguments:<ol>
<li>The name of the test (<code>"addition of 4 and 6 to equal 10"</code>).</li>
<li>A function containing the expectations you wish to test.</li>
<li>An optional timeout argument.</li>
</ol>
</li>
<li><a target="_blank" href="https://jestjs.io/docs/expect#expectvalue"><code>expect()</code></a> is a Jest method that lets you test the output of your code.</li>
<li><a target="_blank" href="https://jestjs.io/docs/expect#tobevalue"><code>toBe()</code></a> is a <a target="_blank" href="https://jestjs.io/docs/using-matchers">Jest matcher</a> function that enables you to compare <code>expect()</code>'s argument to primitive values.</li>
</ul>
<p>Suppose you run the test code now. The test would fail because you've not developed the program for which you created the test. So, let's do that now.</p>
<h3 id="heading-step-10-develop-your-program">Step 10: Develop your program</h3>
<p>Open your project file and develop a program to pass the prewritten test.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// additionCalculator.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">additionCalculator</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-built_in">module</span>.exports = additionCalculator;
</code></pre>
<p>The snippet above created an <code>additionCalculator()</code> program and exported it with the <code>module.exports</code> statement.</p>
<h3 id="heading-step-11-run-the-test">Step 11: Run the test</h3>
<p>Run the prewritten test to check if your program passed or failed.</p>
<pre><code class="lang-bash">npm run <span class="hljs-built_in">test</span>
</code></pre>
<p>Alternatively, you can use Yarn like so:</p>
<pre><code class="lang-bash">yarn <span class="hljs-built_in">test</span>
</code></pre>
<p>Suppose your project contains multiple test files, and you wish to run a specific one. In such a case, specify the test file as follow:</p>
<pre><code class="lang-bash">npm run <span class="hljs-built_in">test</span> additionCalculator.test.js
</code></pre>
<p>Alternatively, you can use Yarn like this:</p>
<pre><code class="lang-bash">yarn <span class="hljs-built_in">test</span> additionCalculator.test.js
</code></pre>
<p>Once you've initiated the test, Jest will print a pass or fail message on your editor's console. The message will look similar to this:</p>
<pre><code class="lang-bash">$ jest
 PASS  ./additionCalculator.test.js
  √ addition of 4 and 6 to equal 10 (2 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.002 s
Ran all <span class="hljs-built_in">test</span> suites.
Done <span class="hljs-keyword">in</span> 7.80s.
</code></pre>
<p>If you prefer Jest to run your test automatically, add the <code>--watchAll</code> option to your <code>package.json</code>'s <code>test</code> field.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"jest --watchAll"</span>
  }
}
</code></pre>
<p>After adding <code>--watchAll</code>, re-execute the <code>npm run test</code> (or <code>yarn test</code>) command to make Jest automatically begin rerunning your test whenever you save changes.</p>
<p><strong>Note:</strong> You can quit the watch mode by pressing the <strong>Q</strong> key on your keyboard.</p>
<h3 id="heading-step-12-refactor-the-test-code">Step 12: Refactor the test code</h3>
<p>So, now that you've confirmed that your program is working as intended, it's time to check if there's any need to refactor the test code.</p>
<p>For instance, suppose you realized that the <code>additionalCalculator</code> should allow users to add any number of digits. In that case, you can refactor your test code like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// additionCalculator.test.js</span>

<span class="hljs-keyword">const</span> additionCalculator = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./additionCalculator"</span>);

describe(<span class="hljs-string">"additionCalculator's test cases"</span>, <span class="hljs-function">() =&gt;</span> {
  test(<span class="hljs-string">"addition of 4 and 6 to equal 10"</span>, <span class="hljs-function">() =&gt;</span> {
    expect(additionCalculator(<span class="hljs-number">4</span>, <span class="hljs-number">6</span>)).toBe(<span class="hljs-number">10</span>);
  });

  test(<span class="hljs-string">"addition of 100, 50, 20, 45 and 30 to equal 245"</span>, <span class="hljs-function">() =&gt;</span> {
    expect(additionCalculator(<span class="hljs-number">100</span>, <span class="hljs-number">50</span>, <span class="hljs-number">20</span>, <span class="hljs-number">45</span>, <span class="hljs-number">30</span>)).toBe(<span class="hljs-number">245</span>);
  });

  test(<span class="hljs-string">"addition of 7 to equal 7"</span>, <span class="hljs-function">() =&gt;</span> {
    expect(additionCalculator(<span class="hljs-number">7</span>)).toBe(<span class="hljs-number">7</span>);
  });

  test(<span class="hljs-string">"addition of no argument provided to equal 0"</span>, <span class="hljs-function">() =&gt;</span> {
    expect(additionCalculator()).toBe(<span class="hljs-number">0</span>);
  });
});
</code></pre>
<p>Note that the <a target="_blank" href="https://jestjs.io/docs/api#describename-fn">describe()</a> method we used in the snippet above is optional code—it helps organize related test cases into groups.</p>
<p><code>describe()</code> accepts two arguments:</p>
<ol>
<li>A name you wish to call the test case group—for instance, <code>"additionCalculator's test cases"</code>.</li>
<li>A function containing your test cases.</li>
</ol>
<h3 id="heading-step-13-refactor-the-program">Step 13: Refactor the program</h3>
<p>So, now that you've refactored your test code, let's do the same for the <code>additionalCalculator</code> program.</p>
<pre><code class="lang-js"><span class="hljs-comment">// additionCalculator.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">additionCalculator</span>(<span class="hljs-params">...numbers</span>) </span>{
  <span class="hljs-keyword">return</span> numbers.reduce(<span class="hljs-function">(<span class="hljs-params">sum, item</span>) =&gt;</span> sum + item, <span class="hljs-number">0</span>);
}

<span class="hljs-built_in">module</span>.exports = additionCalculator;
</code></pre>
<p>Here's what we did in the snippet above:</p>
<ol>
<li>The <code>...numbers</code> code used JavaScript's <a target="_blank" href="https://codesweetly.com/javascript-rest-operator">rest operator</a> (<code>...</code>) to put the function's arguments into an array.</li>
<li>The <code>numbers.reduce((sum, item) =&gt; sum + item, 0)</code> code used JavaScript's <a target="_blank" href="https://codesweetly.com/javascript-reduce-method">reduce()</a> method to sum up all the items in the <code>numbers</code> array.</li>
</ol>
<h3 id="heading-step-14-rerun-the-test">Step 14: Rerun the test</h3>
<p>Once you've finished refactoring your code, rerun the test to confirm that your program still works as expected.</p>
<h3 id="heading-and-thats-it">And that's it!</h3>
<p>Congratulations! You've successfully used Jest to develop an addition calculator program using a test-driven development approach! 🎉</p>
<h2 id="heading-important-stuff-to-know-about-using-es6-modules-with-jest">Important Stuff to Know about Using ES6 Modules with Jest</h2>
<p>Jest does not currently recognize ES6 modules.</p>
<p>However, suppose you prefer to use ES6's import/export statements. In that case, do the following:</p>
<h3 id="heading-1-install-babel-as-a-development-dependency">1. Install Babel as a development dependency</h3>
<pre><code class="lang-bash">npm install @babel/preset-env --save-dev
</code></pre>
<p>Or, you can use Yarn:</p>
<pre><code class="lang-bash">yarn add @babel/preset-env --dev
</code></pre>
<h3 id="heading-2-create-a-babelrc-file-in-your-projects-root">2. Create a <code>.babelrc</code> file in your project's root</h3>
<pre><code class="lang-bash">touch .babelrc
</code></pre>
<h3 id="heading-3-open-the-babelrc-file-and-replicate-the-code-below">3. Open the <code>.babelrc</code> file and replicate the code below</h3>
<pre><code class="lang-json">{ <span class="hljs-attr">"presets"</span>: [<span class="hljs-string">"@babel/preset-env"</span>] }
</code></pre>
<p>The configuration above will now allow you to change step 9's <code>require()</code> statement from this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> additionCalculator = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./additionCalculator"</span>);
</code></pre>
<p>...to this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> additionCalculator <span class="hljs-keyword">from</span> <span class="hljs-string">"./additionCalculator"</span>;
</code></pre>
<p>Likewise, you can now also substitute step 10's <code>export</code> statement from this:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = additionCalculator;
</code></pre>
<p>...to this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> additionCalculator;
</code></pre>
<p><strong>Note:</strong> Jest also specified similar instructions in their <a target="_blank" href="https://jestjs.io/docs/getting-started#using-babel">using Babel</a> documentation.</p>
<h3 id="heading-4-rerun-the-test">4. Rerun the test</h3>
<p>You can now rerun the test to confirm that your program still works!</p>
<p>So, now that we know what test-driven development is, we can discuss its advantages.</p>
<h2 id="heading-what-are-the-advantages-of-test-driven-development">What Are the Advantages of Test-Driven Development?</h2>
<p>Below are two main advantages of adopting test-driven development (TDD) in your programming workflow.</p>
<h3 id="heading-1-understand-your-programs-purpose">1. Understand your program's purpose</h3>
<p>Test-driven development helps you understand the purposes of your program.</p>
<p>In other words, since you write your test before the actual program, TDD makes you think about what you want your program to do.</p>
<p>Then, after you've documented the program's purposes using one or more tests, you can confidently proceed to create the program.</p>
<p>Therefore, TDD is a helpful way to jot down the specific results you expect your intended program to produce.</p>
<h3 id="heading-2-confidence-booster">2. Confidence booster</h3>
<p>TDD is a benchmark for knowing that your program is working as expected. It gives you the confidence that your program is working correctly.</p>
<p>Therefore, irrespective of any future development on your codebase, TDD provides an effective way to test if your program is still working appropriately.</p>
<p>Let's now discuss some popular TDD terms: "unit test," "integration test," "E2E," and "test doubles."</p>
<h2 id="heading-what-is-a-unit-test-in-test-driven-development">What is a Unit Test in Test-Driven Development?</h2>
<p>A <strong>unit test</strong> is a test you write to assess the functionality of an independent piece of a program. In other words, a unit test checks if a fully isolated unit of program is working as intended.</p>
<p>The test we wrote for step 10's <code>additionalCalculator</code> program is an excellent unit test example.</p>
<p>Step 10's <code>additionalCalculator()</code>'s test is a unit test because the program is an independent function that does not depend on any external code.</p>
<p>Note that a unit test's primary purpose is not to check for bugs. Instead, a unit test's core purpose is to check whether an independent piece of program (called unit) behaves as intended under various test cases.</p>
<h2 id="heading-what-is-an-integration-test-in-test-driven-development">What is an Integration Test in Test-Driven Development?</h2>
<p>An <strong>integration test</strong> assesses the functionality of a dependent piece of program. In other words, an integration test checks if a program—which depends on other code—is working as intended.</p>
<p>The test we wrote for step 13's <code>additionalCalculator</code> program is an excellent example of an integration test.</p>
<p>Step 13's <code>additionalCalculator()</code>'s test is an integration test because the program is a dependent function that depends on JavaScript's <a target="_blank" href="https://codesweetly.com/javascript-reduce-method">reduce()</a> method.</p>
<p>In other words, we used the prewritten test case to assess the integration of <code>additionalCalculator()</code> and <code>reduce()</code>.</p>
<p>Therefore, suppose JavaScript makes <code>reduce()</code> an obsolete method. In such a case, <code>additionalCalculator</code> will fail its test because of the <code>reduce()</code> method.</p>
<h2 id="heading-what-is-an-end-to-end-test-in-test-driven-development">What is an End-to-End Test in Test-Driven Development?</h2>
<p>An <strong>End-to-End (E2E) test</strong> assesses the functionality of a user interface. In other words, E2E checks if your user interface is working as intended.</p>
<p>Watch <a target="_blank" href="https://youtu.be/r9HdJ8P6GQI?t=1755">Max's YouTube video</a> for a good illustration of an End-to-End test.</p>
<h2 id="heading-what-are-test-doubles-in-test-driven-development">What are Test Doubles in Test-Driven Development?</h2>
<p><strong>Test doubles</strong> are the imitation objects used to mimic real dependencies like databases, libraries, networks, and APIs.</p>
<p>A test double allows you to bypass the natural objects on which your program depends. They let you test your code independently of any dependencies.</p>
<p>For instance, suppose you need to verify if an error detected in your app originates from an external API or your code.</p>
<p>But suppose the API's service is available only in production—not in the development environment. In that case, you've got two options:</p>
<ol>
<li>Wait until your app goes live—which could take months.</li>
<li>Clone the API so you can continue your test irrespective of the dependency's availability.</li>
</ol>
<p>Test doubles provide a helpful way to clone your program's dependencies so that your testing activities won't encounter any disruptions.</p>
<p>Typical examples of test doubles are dummy objects, mocks, fakes, and stubs. Let's discuss them below.</p>
<h3 id="heading-what-is-a-dummy-in-test-driven-development">What is a dummy in test-driven development?</h3>
<p>A <strong>dummy</strong> is a test double used to mimic the value of a specific dependency.</p>
<p>For instance, suppose your app depends on a third-party method that requires you to provide some arguments. In such a case, a dummy allows you to pass in pretend values to the parameters of that method.</p>
<h3 id="heading-what-is-a-mock-in-test-driven-development">What is a mock in test-driven development?</h3>
<p><strong>Mock</strong> is a test double used to mimic an external dependency without considering the responses the dependency may return.</p>
<p>For instance, suppose your app depends on a third-party API (for example, Facebook)—which you cannot access in the development mode. Mock allows you to bypass the API so that you can focus on testing your code regardless of the Facebook API's availability.</p>
<h3 id="heading-what-is-a-stub-in-test-driven-development">What is a stub in test-driven development?</h3>
<p>A <strong>stub</strong> is a test double used to mimic an external dependency while returning hand-coded values. You can use the returned value to assess your program's behavior with various test case responses from the dependency.</p>
<p>For instance, suppose your app depends on a third-party API (for example, Facebook)—which you cannot access in the development mode. Stub allows you to bypass the API while mimicking the exact values Facebook will return.</p>
<p>Therefore, stub helps you assess your program's behavior with various response scenarios.</p>
<h3 id="heading-what-is-a-fake-in-test-driven-development">What is a fake in test-driven development?</h3>
<p><strong>Fake</strong> is a test double used to create a working test implementation of an external dependency with dynamic values.</p>
<p>For instance, you can use fake to create a local database that allows you to test how a real database will work with your program.</p>
<h2 id="heading-quick-overview-of-test-driven-development-so-far">Quick Overview of Test-Driven Development So Far</h2>
<p>We've learned that test-driven development helps you jot down your program's behavior before creating the program.</p>
<p>We also saw a simple JavaScript test and used Jest as a test implementation tool.</p>
<p>Let's now see how to test React components.</p>
<h2 id="heading-how-to-test-react-components">How to Test React Components</h2>
<p>The two main tools you need to test your React components are:</p>
<ol>
<li>A test runner tool</li>
<li>A React component testing tool</li>
</ol>
<p>But what exactly is the difference between a test runner and a React component testing tool? Let's find out.</p>
<h2 id="heading-test-runner-vs-react-component-testing-tool-whats-the-difference">Test Runner vs. React Component Testing Tool: What's the Difference?</h2>
<p>Below are the differences between a test runner and a React component testing tool.</p>
<h3 id="heading-what-is-a-test-runner">What is a test runner?</h3>
<p>A <strong>test runner</strong> is a tool developers use to run a test script and print the test's results on the command line (CLI).</p>
<p>For instance, suppose you wish to run the test cases in your project's <code>App.test.js</code> test script. In such a case, you will use a test runner.</p>
<p>The test runner will execute <code>App.test.js</code> and print the test's results on the command line.</p>
<p>Typical examples of test runners are <a target="_blank" href="https://jasmine.github.io/">Jasmine</a>, <a target="_blank" href="https://mochajs.org/">Mocha</a>, <a target="_blank" href="https://github.com/substack/tape">Tape</a>, and <a target="_blank" href="https://jestjs.io/">Jest</a>.</p>
<h3 id="heading-what-is-a-react-component-testing-tool">What is a React component testing tool?</h3>
<p>A <strong>React component testing tool</strong> provides helpful APIs for defining a component's test cases.</p>
<p>For instance, suppose you need to test your project's <code>&lt;App /&gt;</code> component. In such a case, you will use a React component testing tool to define the component's test cases.</p>
<p>In other words, a React component testing tool provides the APIs for writing your component's test cases.</p>
<p>Typical examples are <a target="_blank" href="https://enzymejs.github.io/enzyme/">Enzyme</a> and the <a target="_blank" href="https://testing-library.com/docs/react-testing-library/intro">React Testing Library</a>.</p>
<p>So, now that we know what a test runner and React component testing tool are, let's use a mini-project to understand how React testing works.</p>
<h2 id="heading-project-how-react-testing-works">Project: How React Testing Works</h2>
<p>In the following steps, we will use <a target="_blank" href="https://en.wikipedia.org/wiki/Jest_(JavaScript_framework)">Jest</a> and the <a target="_blank" href="https://testing-library.com/docs/react-testing-library/intro">React Testing Library</a> (by Kent C. Dodds) to learn how React testing works.</p>
<p><strong>Note:</strong> The React official docs <a target="_blank" href="https://reactjs.org/docs/testing.html#tools">recommend</a> the Jest and React Testing Library combination for testing React components.</p>
<h3 id="heading-step-1-get-the-right-node-and-npm-version-1">Step 1: Get the right Node and NPM version</h3>
<p>Make sure that you have <a target="_blank" href="https://codesweetly.com/package-manager-explained#how-to-check-the-installed-node-version">Node 10.16</a> (or greater) and NPM 5.6 (or greater) installed on your system.</p>
<p>If you prefer to use Yarn, ensure you have Yarn 0.25 (or greater).</p>
<h3 id="heading-step-2-create-a-new-react-app">Step 2: Create a new React app</h3>
<p>Use NPM's <a target="_blank" href="https://create-react-app.dev/">create-react-app</a> package to create a new React app called <code>react-testing-project</code>.</p>
<pre><code class="lang-bash">npx create-react-app react-testing-project
</code></pre>
<p>Alternatively, you can use Yarn to configure your project like so:</p>
<pre><code class="lang-bash">yarn create react-app react-testing-project
</code></pre>
<h3 id="heading-step-3-go-inside-the-project-directory">Step 3: Go inside the project directory</h3>
<p>After the installation process, navigate into the project directory like so:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> react-testing-project
</code></pre>
<h3 id="heading-step-4-set-up-your-test-environment">Step 4: Set up your test environment</h3>
<p>Install the following test packages:</p>
<ul>
<li>jest</li>
<li>@testing-library/react</li>
<li>@testing-library/jest-dom</li>
<li>@testing-library/user-event</li>
</ul>
<p><strong>Note:</strong> If you've initialized your React project with <code>create-react-app</code> (step 2), you do not need to install any of the above packages. They come preinstalled and preconfigured in your <code>package.json</code> file.</p>
<p>Now, let's discuss the purpose of each of the above test packages.</p>
<h4 id="heading-what-is-jest">What is Jest?</h4>
<p><a target="_blank" href="https://www.npmjs.com/package/jest">jest</a> is the test runner tool we will use to run this project's test scripts and print the test results on the command line.</p>
<h4 id="heading-what-is-testing-libraryreact">What is @testing-library/react?</h4>
<p><a target="_blank" href="https://www.npmjs.com/package/@testing-library/react">@testing-library/react</a> is the React Testing Library which gives you the APIs you need to write test cases for your React components.</p>
<h4 id="heading-what-is-testing-libraryjest-dom">What is @testing-library/jest-dom?</h4>
<p><a target="_blank" href="https://www.npmjs.com/package/@testing-library/jest-dom">@testing-library/jest-dom</a> provides some set of custom Jest matchers for testing the DOM's state.</p>
<p><strong>Note:</strong> Jest already comes with lots of matchers, so using <code>jest-dom</code> is optional. <code>jest-dom</code> simply extends Jest by providing matchers that make your test more declarative, clear to read, and easy to maintain.</p>
<h4 id="heading-what-is-testing-libraryuser-event">What is @testing-library/user-event?</h4>
<p><a target="_blank" href="https://www.npmjs.com/package/@testing-library/user-event">@testing-library/user-event</a> provides the <code>userEvent</code> API for simulating users' interaction with your app on a web page.</p>
<p><strong>Note:</strong> <code>@testing-library/user-event</code> is a better alternative to the <a target="_blank" href="https://testing-library.com/docs/dom-testing-library/api-events/#fireevent">fireEvent</a> API.</p>
<h3 id="heading-step-5-clean-up-the-src-folder">Step 5: Clean up the <code>src</code> folder</h3>
<p>Delete all files inside the project directory's <code>src</code> folder.</p>
<h3 id="heading-step-6-create-your-code-files">Step 6: Create your code files</h3>
<p>Create the following files inside your project's <code>src</code> folder.</p>
<ul>
<li><code>index.js</code></li>
<li><code>App.js</code></li>
<li><code>App.test.js</code></li>
</ul>
<h3 id="heading-step-7-render-the-app-component">Step 7: Render the <code>App</code> component</h3>
<p>Open your <code>index.js</code> file and render the <code>App</code> component to the DOM like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>

<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { createRoot } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom/client"</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">"./App"</span>;

<span class="hljs-comment">// Render the App component into the root DOM</span>
createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>)).render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>);
</code></pre>
<h3 id="heading-step-8-write-your-test-case">Step 8: Write your test case</h3>
<p>Suppose you want your <code>App.js</code> file to render a <code>&lt;h1&gt;CodeSweetly Test&lt;/h1&gt;</code> element to the web page. In that case, open your <em>test script</em> and write some test code specifying the result you expect your <code>&lt;App /&gt;</code> component to produce.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// App.test.js</span>

<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { render, screen } <span class="hljs-keyword">from</span> <span class="hljs-string">"@testing-library/react"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"@testing-library/jest-dom"</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">"./App"</span>;

test(<span class="hljs-string">"codesweetly test heading"</span>, <span class="hljs-function">() =&gt;</span> {
  render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>);
  expect(screen.getByRole(<span class="hljs-string">"heading"</span>)).toHaveTextContent(<span class="hljs-regexp">/codesweetly test/i</span>);
});
</code></pre>
<p>Here are the main things we did in the test snippet above:</p>
<ol>
<li>We imported the packages needed to write our test case.</li>
<li><p>We wrote a test case specifying that we expect our <code>&lt;App /&gt;</code> component to render a heading element with a <code>"codesweetly test"</code> text.</p>
</li>
<li><p><a target="_blank" href="https://jestjs.io/docs/api#testname-fn-timeout"><code>test()</code></a> is one of Jest's global methods. We use it to run a test case. The method accepts three arguments:</p>
<ul>
<li>The name of the test (<code>"codesweetly test heading"</code>)</li>
<li>A function containing the expectations you wish to test</li>
<li>An optional timeout argument</li>
</ul>
</li>
<li><a target="_blank" href="https://testing-library.com/docs/react-testing-library/api/#render"><code>render()</code></a> is one of the React Testing Library APIs. We use it to render the component we wish to test.</li>
<li><a target="_blank" href="https://jestjs.io/docs/expect#expectvalue"><code>expect()</code></a> is a Jest method that lets you test the output of your code.</li>
<li><a target="_blank" href="https://testing-library.com/docs/queries/about/#screen"><code>screen</code></a> is a React Testing Library's object containing numerous methods for finding elements on a page.</li>
<li><a target="_blank" href="https://testing-library.com/docs/queries/about/#priority"><code>getByRole()</code></a> is one of the React Testing Library's query methods for finding elements on a page.</li>
<li><a target="_blank" href="https://github.com/testing-library/jest-dom#tohavetextcontent"><code>toHaveTextContent()</code></a> is one of <code>jest-dom</code>'s custom matchers that you can use to confirm the presence of a text content in a specific node.</li>
<li><code>/codesweetly test/i</code> is a <a target="_blank" href="https://codesweetly.com/javascript-regular-expression-object">regular expression</a> syntax that we used to specify a case-insensitive search for <code>codesweetly test</code>.</li>
</ol>
<p>Keep in mind that there are three alternative ways to write the above expect statement:</p>
<pre><code class="lang-js"><span class="hljs-comment">// 1. Using jest-dom's toHaveTextContent() method:</span>
expect(screen.getByRole(<span class="hljs-string">"heading"</span>)).toHaveTextContent(<span class="hljs-regexp">/codesweetly test/i</span>);

<span class="hljs-comment">// 2. Using the heading's textContent property and Jest's toMatch() method:</span>
expect(screen.getByRole(<span class="hljs-string">"heading"</span>).textContent).toMatch(<span class="hljs-regexp">/codesweetly test/i</span>);

<span class="hljs-comment">// 3. Using React Testing Library's name option and jest-dom's toBeInTheDocument() method</span>
expect(screen.getByRole(<span class="hljs-string">"heading"</span>, { <span class="hljs-attr">name</span>: <span class="hljs-regexp">/codesweetly test/i</span> })).toBeInTheDocument();
</code></pre>
<p><strong>Tip:</strong></p>
<p>Add a <code>level</code> option to the <code>getByRole()</code> method to specify your heading's level.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js">test(<span class="hljs-string">"codesweetly test heading"</span>, <span class="hljs-function">() =&gt;</span> {
  render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>);
  expect(screen.getByRole(<span class="hljs-string">"heading"</span>, { <span class="hljs-attr">level</span>: <span class="hljs-number">1</span> })).toHaveTextContent(<span class="hljs-regexp">/codesweetly test/i</span>);
});
</code></pre>
<p>The <code>level: 1</code> option specifies an <code>&lt;h1&gt;</code> heading element.</p>
<p>Suppose you run the test code now. The test will fail because you've not developed the component for which you created the test. So, let's do that now.</p>
<h3 id="heading-step-9-develop-your-react-component">Step 9: Develop your React component</h3>
<p>Open your <code>App.js</code> file and develop the component to pass the prewritten test.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// App.js</span>

<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> App = <span class="hljs-function">() =&gt;</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>CodeSweetly Test<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>The <code>App</code> component, in the snippet above, renders a <code>&lt;h1&gt;</code> element containing the <code>"CodeSweetly Test"</code> text.</p>
<h3 id="heading-step-10-run-the-test">Step 10: Run the test</h3>
<p>Run the prewritten test to check if your program passed or failed.</p>
<pre><code class="lang-bash">npm <span class="hljs-built_in">test</span> App.test.js
</code></pre>
<p>Alternatively, you can use Yarn like so:</p>
<pre><code class="lang-bash">yarn <span class="hljs-built_in">test</span> App.test.js
</code></pre>
<p>Once you've initiated the test, Jest will print a pass or fail message on your editor's console. The message will look similar to this:</p>
<pre><code class="lang-bash">$ jest
 PASS  src/App.test.js
  √ codesweetly <span class="hljs-built_in">test</span> heading (59 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.146 s
Ran all <span class="hljs-built_in">test</span> suites related to changed files.
</code></pre>
<p><strong>Note:</strong> The <code>create-react-app</code> configured Jest in <a target="_blank" href="https://codesweetly.com/javascript-module-bundler/#what-is-webpack---progress---watch">watch mode</a> by default. Therefore, after running <code>npm test</code> (or <code>yarn test</code>), your currently opened terminal will continue to process the <code>test</code> command's activities. So, you won't be able to input any command on that terminal until you stop <code>test</code>'s execution. But you can open a new terminal window simultaneously with the one processing <code>test</code>. </p>
<p>In other words, use one terminal to run <code>test</code> and another to input commands.</p>
<h3 id="heading-step-11-run-the-application">Step 11: Run the application</h3>
<p>Take a look at your app in the browser by running:</p>
<pre><code class="lang-bash">npm start
</code></pre>
<p>Or, if your <a target="_blank" href="https://codesweetly.com/package-manager-explained">package manager</a> is Yarn, run:</p>
<pre><code class="lang-bash">yarn start
</code></pre>
<p>Once you run the command above, your app will automatically open on your default browser.</p>
<h3 id="heading-step-12-refactor-the-test-code-1">Step 12: Refactor the test code</h3>
<p>Suppose you wish to change the heading's text when users click a button. In that case, you can simulate users' interaction with the button to confirm that it works as intended.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// App.test.js</span>

<span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { render, screen } <span class="hljs-keyword">from</span> <span class="hljs-string">"@testing-library/react"</span>;
<span class="hljs-keyword">import</span> userEvent <span class="hljs-keyword">from</span> <span class="hljs-string">"@testing-library/user-event"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"@testing-library/jest-dom"</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">"./App"</span>;

describe(<span class="hljs-string">"App component"</span>, <span class="hljs-function">() =&gt;</span> {
  test(<span class="hljs-string">"codesweetly test heading"</span>, <span class="hljs-function">() =&gt;</span> {
    render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>);
    expect(screen.getByRole(<span class="hljs-string">"heading"</span>)).toHaveTextContent(<span class="hljs-regexp">/codesweetly test/i</span>);
  });

  test(<span class="hljs-string">"a codesweetly project heading"</span>, <span class="hljs-function">() =&gt;</span> {
    render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>);

    <span class="hljs-keyword">const</span> button = screen.getByRole(<span class="hljs-string">"button"</span>, { <span class="hljs-attr">name</span>: <span class="hljs-string">"Update Heading"</span> });

    userEvent.click(button);

    expect(screen.getByRole(<span class="hljs-string">"heading"</span>)).toHaveTextContent(<span class="hljs-regexp">/a codesweetly project/i</span>);
  });
});
</code></pre>
<p>Here are the main things we did in the test snippet above:</p>
<ol>
<li>We imported the packages needed to write our test case.</li>
<li>We wrote a test case specifying that we expect the <code>&lt;App /&gt;</code> component to render a heading element with a <code>"codesweetly test"</code> text.</li>
<li>We wrote another test case simulating users' interaction with the app's button element. In other words, we specified that whenever a user clicks the button, we expect <code>&lt;App /&gt;</code>'s heading to update to <code>"a codesweetly project"</code> text.</li>
</ol>
<p><strong>Note:</strong></p>
<ul>
<li><a target="_blank" href="https://jestjs.io/docs/api#describename-fn"><code>describe()</code></a> is one of Jest's global methods. It is optional code that helps organize related test cases into groups. <code>describe()</code> accepts two arguments:<ul>
<li>A name you wish to call the test case group—for instance, <code>"App component"</code>.</li>
<li>A function containing your test cases.</li>
</ul>
</li>
<li><a target="_blank" href="https://www.npmjs.com/package/@testing-library/user-event"><code>userEvent</code></a> is the React Testing Library's package containing several methods for simulating users' interaction with an app. For instance, in the snippet above, we used <code>userEvent</code>'s <code>click()</code> method to simulate a click event on the button element.</li>
<li>We rendered <code>&lt;App /&gt;</code> for each test case because React Testing Library unmounts the rendered components after each test. However, suppose you have numerous test cases for a component. In that case, use Jest's <a target="_blank" href="https://jestjs.io/docs/api#beforeeachfn-timeout"><code>beforeEach()</code></a> method to run <code>render(&lt;App /&gt;)</code> before each test in your file (or <code>describe</code> block).</li>
</ul>
<h3 id="heading-step-13-refactor-your-react-component">Step 13: Refactor your React component</h3>
<p>So, now that you've refactored your test code, let's do the same for the <code>App</code> component.</p>
<pre><code class="lang-js"><span class="hljs-comment">// App.js</span>

<span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> [heading, setHeading] = useState(<span class="hljs-string">"CodeSweetly Test"</span>);

  <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">() =&gt;</span> {
    setHeading(<span class="hljs-string">"A CodeSweetly Project"</span>);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{heading}<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">type</span>=<span class="hljs-string">"button"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span>&gt;</span>
        Update Heading
      <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>Here are the main things we did in the snippet above:</p>
<ol>
<li><code>App</code>'s <code>heading</code> state got initialized with a <code>"CodeSweetly Test"</code> string.</li>
<li>We programmed a <code>handleClick</code> function to update the <code>heading</code> state.</li>
<li>We rendered a <code>&lt;h1&gt;</code> and <code>&lt;button&gt;</code> elements to the DOM.</li>
</ol>
<p>Note the following:</p>
<ul>
<li><code>&lt;h1&gt;</code>'s content is the <code>heading</code> state's current value.</li>
<li>Whenever a user clicks the button element, the <code>onClick()</code> event listener will trigger the <code>handleClick()</code> function. And <code>handleClick</code> will update <code>App</code>'s <code>heading</code> state to <code>"A CodeSweetly Project"</code>. Therefore, <code>&lt;h1&gt;</code>'s content will change to <code>"A CodeSweetly Project"</code>.</li>
</ul>
<h3 id="heading-step-14-rerun-the-test-1">Step 14: Rerun the test</h3>
<p>Once you've refactored your component, rerun the test (or check the actively running test) to confirm that your app still works as expected.</p>
<p>Afterward, check the browser to see your recent updates.</p>
<h3 id="heading-and-thats-it-1">And that's it!</h3>
<p>Congratulations! You've successfully used Jest and the React Testing Library to test a React component. 🎉</p>
<h2 id="heading-overview">Overview</h2>
<p>This article discussed how test-driven development works in JavaScript and ReactJS applications. </p>
<p>We also learned how to use Jest and the React Testing Library to make testing simpler and faster.</p>
<p>Thanks for reading!</p>
<h3 id="heading-and-heres-a-useful-reactjs-resource"><strong>And here's a useful ReactJS resource:</strong></h3>
<p>I wrote a book about React!</p>
<ul>
<li>It's beginner friendly ✔</li>
<li>It has live code snippets ✔</li>
<li>It contains scalable projects ✔</li>
<li>It has plenty of easy-to-grasp examples ✔</li>
</ul>
<p>The <a target="_blank" href="https://www.amazon.com/dp/B09KYGDQYW">React Explained Clearly</a> book is all you need to understand ReactJS.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B09KYGDQYW"><img src="https://www.freecodecamp.org/news/content/images/2022/01/Twitter-React_Explained_Clearly-CodeSweetly-Oluwatobi_Sofela.jpg" alt="React Explained Clearly Book Now Available at Amazon" width="600" height="400" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The JavaScript Modules Handbook – Complete Guide to ES Modules and Module Bundlers ]]>
                </title>
                <description>
                    <![CDATA[ Modules and Module Bundlers are essential components of modern web development. But understanding how they work can quickly become overwhelming. This article will show you all you need to know about ES Modules and Module Bundlers in plain English. Ta... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-es-modules-and-module-bundlers/</link>
                <guid isPermaLink="false">66ba0df4052fa53219e0a365</guid>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ webpack ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Wed, 11 May 2022 23:06:42 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/JavaScript-Module-Book-Cover--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p><strong>Modules</strong> and <strong>Module Bundlers</strong> are essential components of modern web development. But understanding how they work can quickly become overwhelming.</p>
<p>This article will show you all you need to know about ES Modules and Module Bundlers in plain English.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-exactly-is-a-javascript-module-2">What Exactly Is a JavaScript Module?</a></li>
<li><a class="post-section-overview" href="#heading-why-use-modules">Why Use Modules?</a></li>
<li><a class="post-section-overview" href="#heading-common-types-of-module-systems-in-javascript">Common Types of Module Systems in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-how-to-convert-a-javascript-file-into-a-module">How to Convert a JavaScript File into a Module</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-an-es-module">How to Use an ES Module</a></li>
<li><a class="post-section-overview" href="#heading-how-to-export-a-modules-code">How to Export a Module's Code</a></li>
<li><a class="post-section-overview" href="#heading-how-to-import-exported-code">How to Import Exported Code</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-a-modules-imported-code">How to Use a Module's Imported Code</a></li>
<li><a class="post-section-overview" href="#heading-how-to-rename-exports-and-imports-in-es-modules">How to Rename Exports and Imports in ES Modules</a></li>
<li><a class="post-section-overview" href="#heading-why-rename-a-modules-code">Why Rename a Module's Code?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-rename-multiple-exports-in-an-es-module">How to Rename Multiple Exports in an ES Module</a></li>
<li><a class="post-section-overview" href="#heading-how-to-rename-multiple-imports-in-an-es-module">How to Rename Multiple Imports in an ES Module</a></li>
<li><a class="post-section-overview" href="#heading-how-to-import-all-exportable-items-from-an-es-module-in-one-go">How to Import All Exportable Items from an ES Module in One Go</a></li>
<li><a class="post-section-overview" href="#heading-how-to-export-anonymously-to-an-es-module">How to Export Anonymously to an ES Module</a></li>
<li><a class="post-section-overview" href="#heading-what-exactly-is-an-aggregator-file">What Exactly Is an Aggregator File?</a></li>
<li><a class="post-section-overview" href="#heading-project-how-to-use-an-aggregator-file">Project: How to Use an Aggregator File</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-import-syntax-to-load-a-module-dynamically">How to Use the <code>import()</code> Syntax to Load a Module Dynamically</a></li>
<li><a class="post-section-overview" href="#heading-what-exactly-is-importmeta-in-es-modules">What Exactly Is <code>import.meta</code> in ES Modules?</a></li>
<li><a class="post-section-overview" href="#heading-quick-review-of-modules-so-far">Quick Review of Modules So Far</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-module-bundler">What Is a Module Bundler?</a></li>
<li><a class="post-section-overview" href="#heading-why-do-you-need-a-module-bundler">Why Do You Need a Module Bundler?</a></li>
<li><a class="post-section-overview" href="#heading-how-does-a-module-bundler-work">How Does a Module Bundler Work?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-webpack">How to Use Webpack</a></li>
<li><a class="post-section-overview" href="#heading-how-to-make-webpack-auto-generate-your-apps-html-file">How to Make Webpack Auto-Generate Your App's HTML File</a></li>
<li><a class="post-section-overview" href="#heading-how-to-make-htmlwebpackplugin-use-your-source-file-as-a-template-to-auto-generate-a-new-html-page">How to Make <code>HtmlWebpackPlugin</code> Use Your Source File as a Template to Auto-Generate a New HTML Page</a></li>
<li><a class="post-section-overview" href="#heading-important-stuff-to-know-about-updating-your-app">Important Stuff to Know about Updating Your App</a></li>
<li><a class="post-section-overview" href="#heading-how-to-rerun-webpack-automatically-1">How to Rerun Webpack Automatically</a></li>
<li><a class="post-section-overview" href="#heading-how-to-reload-the-browser-automatically">How to Reload the Browser Automatically</a></li>
<li><a class="post-section-overview" href="#heading-what-exactly-is-webpacks-configuration-file-3">What Exactly Is Webpack's Configuration File?</a></li>
<li><a class="post-section-overview" href="#heading-common-webpack-configuration-options">Common Webpack Configuration Options</a></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 modules.</p>
<h2 id="heading-what-exactly-is-a-javascript-module">What Exactly Is a JavaScript Module?</h2>
<p>A JavaScript <strong>module</strong> is a file that allows you to export its code. This allows other JavaScript files to import and use the exported code as their dependencies.</p>
<p>Specifically, a module is simply a JavaScript file that allows you to share its code with other files within your project (or with the world through <a target="_blank" href="https://www.codesweetly.com/package-manager-explained">package managers</a> like Yarn and NPM).</p>
<h2 id="heading-why-use-modules">Why Use Modules?</h2>
<p>In its early days, people used JavaScript mainly for trivial scripting tasks like providing bits and pieces of interactivity to web pages where needed. In other words, developers predominately used JavaScript to write small scripts—not large ones.</p>
<p>Today, however, JavaScript has grown into a vast scripting tool capable of doing a lot more than just making web pages interactive.</p>
<p>It is now the norm to have large JavaScript code used for diverse functions like server-side website development, game development, and mobile app development.</p>
<p>Since JavaScript can be used for virtually any programming task, a need arose to share scripts between a project's files and the world.</p>
<p>So the JavaScript community developed the module system to allow developers to share their scripts on demand.</p>
<h2 id="heading-common-types-of-module-systems-in-javascript">Common Types of Module Systems in JavaScript</h2>
<p>Below are some of the popular module systems in JavaScript:</p>
<ul>
<li><a target="_blank" href="https://github.com/amdjs/amdjs-api/blob/master/AMD.md">Asynchronous Module Definition (AMD)</a></li>
<li><a target="_blank" href="https://en.wikipedia.org/wiki/CommonJS">CommonJS Modules</a></li>
<li><a target="_blank" href="https://github.com/umdjs/umd">Universal Module Definition (UMD)</a></li>
<li><a target="_blank" href="https://tc39.es/ecma262/#sec-modules">ES Modules</a></li>
</ul>
<p><strong>Note:</strong> ES modules are sometimes called "JS modules" or "ECMAScript modules".</p>
<p>Amongst the module systems listed above, the ES module system is the official standard for JavaScript.</p>
<p>The remaining three (AMD, CommonJS, and UMD) were created by various developers when JavaScript did not have a standardized module system.</p>
<p>However, since ES module's appearance in the 2015 ECMAScript standard, the previous module systems have gradually become part of JavaScript's history.</p>
<p>Therefore, this article will focus on showing you how ES modules work.</p>
<p>First, though, it is essential to know how to convert a JavaScript file into a module. So, let's discuss that below.</p>
<h2 id="heading-how-to-convert-a-javascript-file-into-a-module">How to Convert a JavaScript File into a Module</h2>
<p>To convert a JavaScript file to an ES module, do the following:</p>
<h3 id="heading-step-1-create-a-project-directory">Step 1: Create a project directory</h3>
<p>Create a project folder—where this project's HTML and JavaScript files will reside.</p>
<h3 id="heading-step-2-create-your-code-files">Step 2: Create your code files</h3>
<p>Create the following files inside your project folder:</p>
<ol>
<li><code>index.html</code></li>
<li><code>index.js</code></li>
</ol>
<h3 id="heading-step-3-add-your-javascript-file-to-your-html-document">Step 3: Add your JavaScript file to your HTML document</h3>
<p>Open your <code>index.html</code> file and replicate the code below:</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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>ES Module - CodeSweetly<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>ES Module Tutorial<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- Add the "index.js" JavaScript file to this HTML document --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"index.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In the HTML snippet above, we used the <code>&lt;script&gt;</code>'s <code>type="module"</code> attribute to convert the <code>index.js</code> JavaScript file to an ES module.</p>
<p>So, now that we know how to convert a JavaScript file into a module, let's see how to use one.</p>
<h2 id="heading-how-to-use-an-es-module">How to Use an ES Module</h2>
<p>Follow the steps below to learn how to use an ES module.</p>
<h3 id="heading-step-1-create-a-project-directory-1">Step 1: Create a project directory</h3>
<p>Create a project folder—where this project's HTML and module files will reside.</p>
<h3 id="heading-step-2-create-your-code-files-1">Step 2: Create your code files</h3>
<p>Create the following files inside your project folder:</p>
<ol>
<li><code>index.html</code></li>
<li><code>module-1.js</code></li>
<li><code>module-2.js</code></li>
</ol>
<h3 id="heading-step-3-add-the-modules-to-your-html-document">Step 3: Add the modules to your HTML document</h3>
<p>Open your <code>index.html</code> file and replicate the code below:</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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>ES Module - CodeSweetly<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>ES Module Tutorial<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Check the console<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"module-1.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"module-2.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Here are the main things we did in the HTML snippet above:</p>
<ol>
<li>We added the two JavaScript files to our HTML document.</li>
<li>We used the <code>type="module"</code> attribute to convert the regular JavaScript files to ES module files.</li>
</ol>
<p><strong>Note</strong> that JavaScript defers ES modules automatically. So, you do not need to use a <code>defer</code> attribute in your module's <code>&lt;script&gt;</code> element.</p>
<p>Also, the computer will execute a module only once—regardless of the number of <code>&lt;script&gt;</code> tags you use to reference it.</p>
<h3 id="heading-step-4-view-your-app">Step 4: View your app</h3>
<p>Open your <code>index.html</code> file in any browser to see the current state of your app.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/module-tutorial-open-html-file-in-chrome-browser-codesweetly.png" alt="Open your HTML file in your browser - Modules Tutorial" width="600" height="400" loading="lazy">
<em>Opening an index.html file in a Chrome browser</em></p>
<p>Once opened, if you inspect your browser's console, you will see some error messages.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/module-tutorial-cors-policy-error-codesweetly.png" alt="CORS policy error in the browser's console - Modules Tutorial" width="600" height="400" loading="lazy">
<em>Inspecting a Chrome browser's console</em></p>
<p>The browser threw a CORS policy error because ES modules only work through <code>http://</code> and <code>https://</code> URLs—not locally via a <code>file://</code> URL.</p>
<p>In other words, since our HTML file contains two ES modules, we need to load the document via an <code>http://</code> scheme.</p>
<p>The two typical ways to load an HTML document via an <code>http://</code> scheme are:</p>
<ul>
<li>By using a Local Server, or</li>
<li>Through the use of a Module Bundler</li>
</ul>
<p>We will discuss Module Bundlers in detail later on in this article. For now, though, let's see how to use a local server to load the <code>index.html</code> file via an <code>http://</code> scheme.</p>
<h4 id="heading-how-to-run-an-html-file-through-a-local-server">How to run an HTML file through a local server</h4>
<p>The steps below will show you how to use a <a target="_blank" href="https://code.visualstudio.com/">VS Code</a> local server extension to run your HTML file.</p>
<p><strong>Note:</strong> Suppose your code editor is Atom or Sublime Text. In that case, follow the links below to learn how to install a local server plugin.</p>
<ul>
<li><a target="_blank" href="https://atom.io/packages/atom-live-server">Atom Live Server</a></li>
<li><a target="_blank" href="https://youtu.be/5CinAgQylao">Sublime Text Live Server</a></li>
</ul>
<h5 id="heading-1-add-your-project-folder-to-vscodes-workspace">1. Add your project folder to VSCode's workspace</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/module-tutorial-add-proj-folder-to-vscode-workspace-codesweetly.gif" alt="Add your project's folder to VSCode's workspace" width="600" height="400" loading="lazy">
<em>Adding a project folder to VSCode's workspace</em></p>
<h5 id="heading-2-install-a-local-server-live-server-by-ritwick-dey">2. Install a local server (Live Server by Ritwick Dey)</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/module-tutorial-install-live-server-codesweetly.png" alt="Install the Live Server by Ritwick Dey" width="600" height="400" loading="lazy">
<em>Installing the VSCode Live Server by Ritwick Dey</em></p>
<h5 id="heading-3-open-your-html-file-in-the-code-editor">3. Open your HTML file in the code editor</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/module-tutorial-open-html-file-in-code-editor-codesweetly.png" alt="Open your HTML file in your code editor" width="600" height="400" loading="lazy">
<em>Opening HTML file in VSCode editor</em></p>
<h5 id="heading-4-use-live-server-to-run-the-html-file-in-your-default-browser">4. Use Live Server to run the HTML file in your default browser</h5>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/module-tutorial-run-html-file-with-live-server-codesweetly.png" alt="Run your HTML File with Live Server - Modules Tutorial" width="600" height="400" loading="lazy">
<em>Opening the project's HTML file with Live Server</em></p>
<p>Your app should now load with the <code>http://</code> scheme—without any CORS error in your browser's console.</p>
<p><strong>Some things to note:</strong></p>
<ul>
<li>Suppose you did not add your project folder to VSCode's workspace (step 1). In that case, the Live Server might not load your file correctly.</li>
<li>Live Server will auto-reload your browser whenever you save any changes to your HTML file.</li>
<li>Suppose you wish to stop the Live Server. In that case, right-click on the HTML editor page and click on "Stop Live Server".</li>
<li>JavaScript modules operate in strict mode by default. As such, you must abide by JavaScript's strict syntax rules. Otherwise, your program might malfunction.</li>
</ul>
<p>So, now that you've converted your JavaScript file to an ES module, you can begin to use the <code>export</code> and <code>import</code> keywords to share your modules' code. Let's discuss how below.</p>
<h2 id="heading-how-to-export-a-modules-code">How to Export a Module's Code</h2>
<p>There are two equivalent ways to export a module's item.</p>
<ol>
<li>Place an <code>export</code> keyword before your code</li>
<li>Create an export statement</li>
</ol>
<p>Let's discuss both ways below.</p>
<h3 id="heading-how-to-share-a-modules-code-by-placing-an-export-keyword-before-the-code">How to share a module's code by placing an <code>export</code> keyword before the code</h3>
<p>One way to export an item is to place an <code>export</code> keyword before the code you wish to share with other modules.</p>
<p>For instance, open your <code>module-1.js</code> file and replicate the code below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// module-1.js</span>

<span class="hljs-comment">// Export the "bestClub" variable:</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> bestClub = <span class="hljs-string">"Your Club"</span>;
</code></pre>
<p>You can see how we place the <code>export</code> keyword before the <code>const</code> variable statement in the snippet above.</p>
<p>We prepended the <code>const</code> variable with the <code>export</code> keyword to tell the computer to share the <code>bestClub</code> variable with other modules that request it.</p>
<p><strong>Note:</strong> The <code>export</code> keyword highlights the code you wish to share with other modules.</p>
<p><strong>Here's another example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Export the "multiply" function:</span>
<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-keyword">return</span> x * y;
}
</code></pre>
<p>The statement above instructs the computer to export <code>multiply()</code> to the modules that request it.</p>
<p>Let's now see the second way to export a module's code.</p>
<h3 id="heading-how-to-share-a-modules-code-by-creating-an-export-statement">How to share a module's code by creating an export statement</h3>
<p>An alternate way to share a module's code is to use the <code>export</code> keyword as a standalone statement. You can do so by prepending a single <code>export</code> keyword to a block (<code>{...}</code>) of comma-separated names of code you wish to share.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Create a variable named "bestClub":</span>
<span class="hljs-keyword">const</span> bestClub = <span class="hljs-string">"Your Club"</span>;

<span class="hljs-comment">// Create a function named "multiply":</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-keyword">return</span> x * y;
}

<span class="hljs-comment">// Create an array named "fruits":</span>
<span class="hljs-keyword">const</span> fruits = [<span class="hljs-string">"Mango"</span>, <span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Orange"</span>, <span class="hljs-string">"Lemon"</span>];

<span class="hljs-comment">// Export the three statements above:</span>
<span class="hljs-keyword">export</span> { bestClub, multiply, fruits };
</code></pre>
<p>The snippet above used an <code>export</code> statement to indicate that the computer can share <code>bestClub</code>, <code>multiply</code>, and <code>fruits</code> with other modules that request any of them.</p>
<p>Keep in mind that <code>export</code> works only as a top-level item. So, it would not work in a function, for example.</p>
<p>Therefore, the snippet below will throw an error because we used the <code>export</code> keyword inside the function.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">wrong</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">export</span> <span class="hljs-keyword">let</span> bestClub = <span class="hljs-string">"Your Club"</span>;
  <span class="hljs-keyword">return</span> bestClub;
}
</code></pre>
<p><strong>Note:</strong></p>
<ul>
<li>The <code>export</code> keyword works only inside modules—not inside regular JavaScript programs.</li>
<li>JavaScript <a target="_blank" href="https://www.codesweetly.com/javascript-hoisting">hoists</a> <code>export</code> statements. So, you can define them anywhere in your module.</li>
<li>Exported modules operate in strict mode by default—regardless of whether you specified the <code>strict</code> statement.</li>
</ul>
<p>Let's now see how to import the exported code.</p>
<h2 id="heading-how-to-import-exported-code">How to Import Exported Code</h2>
<p>To import exported code, use ES module's <code>import</code> statement.</p>
<p>For instance, open your <code>module-2.js</code> file and replicate the code below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// module-2.js</span>

<span class="hljs-keyword">import</span> { bestClub } <span class="hljs-keyword">from</span> <span class="hljs-string">"./module-1.js"</span>;
</code></pre>
<p>In the snippet above, we used an <code>import</code> statement to bring in the <code>bestClub</code> variable from the <code>module-1.js</code> file.</p>
<p>So, <code>module-2.js</code> is a top-level module because it contains another script.</p>
<p>On the other hand, <code>module-1.js</code> is a submodule because it is a script used inside another file.</p>
<p><strong>Note:</strong></p>
<ul>
<li>We use the <code>import</code> statement to import items from other modules.</li>
<li>It is mandatory to wrap your named exports in curly braces while importing them.</li>
</ul>
<p>Keep in mind that an <code>import</code> statement can only get another module's code if exported with the <code>export</code> keyword.</p>
<p>For instance, the <code>import</code> statement below will import the <code>bestClub</code>, <code>multiply</code>, and <code>fruits</code> items if they got marked for exportation in the <code>module-1.js</code> file.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Import three items from the module-1.js file:</span>
<span class="hljs-keyword">import</span> { bestClub, multiply, fruits } <span class="hljs-keyword">from</span> <span class="hljs-string">"./module-1.js"</span>;
</code></pre>
<p>Suppose you did not use the <code>export</code> keyword to mark the three items as exportable features. In that case, the <code>import</code> statement will throw an <code>Uncaught SyntaxError</code>.</p>
<p><strong>Note:</strong></p>
<ul>
<li>"Module specifier" and the "import specifier" are other names people call the <code>"./module-1.js"</code> file path string in the snippet above.</li>
<li>The dot (<code>.</code>) mark in the <code>"./module-1.js"</code> module specifier means <em>"same directory"</em>. In other words, the dot mark tells the computer to find the <code>module-1.js</code> file in the same folder where the current module is.</li>
<li>The current module referred to in the snippet above is the file where the <code>import</code> statement got defined.</li>
</ul>
<p>An alternative to the import specifier's dot (<code>.</code>) syntax is to write out the entire <a target="_blank" href="https://docs.oracle.com/javase/tutorial/essential/io/path.html">relative path</a> to a module's location.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Import three items from the module-1.js file:</span>
<span class="hljs-keyword">import</span> { bestClub, multiply, fruits } <span class="hljs-keyword">from</span> <span class="hljs-string">"/codesweetly/blog/notes/modular-javascript/es-modules/module-1.js"</span>;
</code></pre>
<p>You can see how long the <code>import</code> statement above is. We often use the dot syntax because of its short and portable length.</p>
<p>Suppose you choose to use the dot syntax. In that case, keep in mind that some module systems (such as Node.js and module bundlers) permit you to omit the dot mark and the file extension like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Import three items from the module-1.js file:</span>
<span class="hljs-keyword">import</span> { bestClub, multiply, fruits } <span class="hljs-keyword">from</span> <span class="hljs-string">"module-1"</span>;
</code></pre>
<p>However, other module systems, such as ES modules, do not permit such omissions.</p>
<p><strong>Note:</strong></p>
<ul>
<li>A module specifier with <em>no</em> dot mark and file extension is called a "bare" module specifier.</li>
<li>A module's imported item is a read-only view of the exported feature. So, you can modify the code only inside the module that exported it—not in the module that imported it.</li>
<li>JavaScript imports a module's code as live binding. So, suppose you update the imported code's value in the exportation module. In that case, your changes will also reflect in the importation module.</li>
</ul>
<p>Let's now discuss how to use the imported code.</p>
<h2 id="heading-how-to-use-a-modules-imported-code">How to Use a Module's Imported Code</h2>
<p>Once you've imported your code, you can use it as if it was defined in the module into which you've imported it.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// module-2.js</span>

<span class="hljs-keyword">import</span> { bestClub } <span class="hljs-keyword">from</span> <span class="hljs-string">"./module-1.js"</span>;

<span class="hljs-keyword">const</span> myBestClub = bestClub + <span class="hljs-string">" "</span> + <span class="hljs-string">"is my best club."</span>;

<span class="hljs-built_in">console</span>.log(myBestClub);
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-ka4gdj?devtoolsheight=33&amp;file=module-2.js"><strong>Try it on StackBlitz</strong></a></p>
<p><strong>Note:</strong></p>
<ul>
<li>The <code>import</code> keyword works only inside modules—not inside regular JavaScript programs.</li>
<li>An imported module's features are not available in the global <a target="_blank" href="https://www.codesweetly.com/javascript-scope">scope</a>. Therefore, you can access imported items only in the script you have imported them into—not in other places like the JavaScript console.</li>
<li>JavaScript <a target="_blank" href="https://www.codesweetly.com/javascript-hoisting">hoists</a> <code>import</code> statements. So, you can define them anywhere in your module.</li>
<li>Imported modules operate in strict mode by default—regardless of whether you specified the <code>strict</code> statement.</li>
</ul>
<p>So, now that we know how to use an ES module, let's discuss how to rename the code you wish to export (or import).</p>
<h2 id="heading-how-to-rename-exports-and-imports-in-es-modules">How to Rename Exports and Imports in ES Modules</h2>
<p>Suppose you wish to rename the code you are exporting (or importing). In such a case, use the <code>as</code> keyword.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// module-1.js</span>

<span class="hljs-comment">// Create a variable named "bestClub":</span>
<span class="hljs-keyword">const</span> bestClub = <span class="hljs-string">"Your Club"</span>;

<span class="hljs-comment">// Export the bestClub variable as "favoriteTeam":</span>
<span class="hljs-keyword">export</span> { bestClub <span class="hljs-keyword">as</span> favoriteTeam };
</code></pre>
<p>In the snippet above, we told the computer to export the <code>bestClub</code> variable <em>as</em> <code>favoriteTeam</code>.</p>
<p>Therefore, when importing the variable, you will use the name <code>favoriteTeam</code>—not <code>bestClub</code>.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// module-2.js</span>

<span class="hljs-keyword">import</span> { favoriteTeam } <span class="hljs-keyword">from</span> <span class="hljs-string">"./module-1.js"</span>;

<span class="hljs-keyword">const</span> myBestClub = favoriteTeam + <span class="hljs-string">" "</span> + <span class="hljs-string">"is my best club."</span>;

<span class="hljs-built_in">console</span>.log(myBestClub);
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-dltrvv?devtoolsheight=33&amp;file=module-2.js"><strong>Try it on StackBlitz</strong></a></p>
<p>We renamed the <code>bestClub</code> variable in the example above while exporting it. However, you can also rename it during its importation.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// module-1.js</span>

<span class="hljs-comment">// Create a variable named "bestClub":</span>
<span class="hljs-keyword">const</span> bestClub = <span class="hljs-string">"Your Club"</span>;

<span class="hljs-comment">// Export the bestClub variable:</span>
<span class="hljs-keyword">export</span> { bestClub };
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">// module-2.js</span>

<span class="hljs-keyword">import</span> { bestClub <span class="hljs-keyword">as</span> favoriteTeam } <span class="hljs-keyword">from</span> <span class="hljs-string">"./module-1.js"</span>;

<span class="hljs-keyword">const</span> myBestClub = favoriteTeam + <span class="hljs-string">" "</span> + <span class="hljs-string">"is my best club."</span>;

<span class="hljs-built_in">console</span>.log(myBestClub);
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-qrnt6y?devtoolsheight=33&amp;file=module-2.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The choice of whether to rename your code during exportation or importation is totally up to you.</p>
<p>However, many developers prefer to rename during importation because you don't always have control over a code's source file, especially when importing from a third party's module.</p>
<h2 id="heading-why-rename-a-modules-code">Why Rename a Module's Code?</h2>
<p>Renaming can help prevent browsers from throwing errors due to name conflicts. For instance, consider these snippets:</p>
<pre><code class="lang-js"><span class="hljs-comment">// module-1.js</span>

<span class="hljs-comment">// Create a variable named "bestClub":</span>
<span class="hljs-keyword">const</span> bestClub = <span class="hljs-string">"Your Club"</span>;

<span class="hljs-comment">// Export the bestClub variable:</span>
<span class="hljs-keyword">export</span> { bestClub };
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">// module-2.js</span>

<span class="hljs-keyword">import</span> { bestClub } <span class="hljs-keyword">from</span> <span class="hljs-string">"./module-1.js"</span>;

<span class="hljs-keyword">const</span> bestClub = bestClub + <span class="hljs-string">" "</span> + <span class="hljs-string">"is my best club."</span>;

<span class="hljs-built_in">console</span>.log(bestClub);
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-vvcy2d?devtoolsheight=33&amp;file=module-2.js"><strong>Try it on StackBlitz</strong></a></p>
<p>When you run the snippets above, the browser will throw an error similar to:</p>
<pre><code class="lang-js"><span class="hljs-string">"SyntaxError: Identifier 'bestClub' has already been declared"</span>
</code></pre>
<p>The browser threw the error because the imported code's name conflicts with <code>module-2.js</code>' <code>bestClub</code> variable.</p>
<p>However, you can rectify the error by simply renaming the imported code like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// module-2.js</span>

<span class="hljs-keyword">import</span> { bestClub <span class="hljs-keyword">as</span> favoriteTeam } <span class="hljs-keyword">from</span> <span class="hljs-string">"./module-1.js"</span>;

<span class="hljs-keyword">const</span> bestClub = favoriteTeam + <span class="hljs-string">" "</span> + <span class="hljs-string">"is my best club."</span>;

<span class="hljs-built_in">console</span>.log(bestClub);
</code></pre>
<p>Keep in mind that you can also rename multiple exports. Let's see how below.</p>
<h2 id="heading-how-to-rename-multiple-exports-in-an-es-module">How to Rename Multiple Exports in an ES Module</h2>
<p>You can rename multiple exports by separating each <code>as</code> statement with a comma.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// module-1.js</span>

<span class="hljs-keyword">const</span> bestClub = <span class="hljs-string">"Your Club"</span>;
<span class="hljs-keyword">const</span> fruits = [<span class="hljs-string">"Grape"</span>, <span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Pineapple"</span>, <span class="hljs-string">"Lemon"</span>];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-keyword">return</span> x * y;
}

<span class="hljs-comment">// Export the three statements above:</span>
<span class="hljs-keyword">export</span> { 
  bestClub <span class="hljs-keyword">as</span> favoriteTeam, 
  fruits <span class="hljs-keyword">as</span> crops, 
  multiply <span class="hljs-keyword">as</span> product 
};
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">// module-2.js</span>

<span class="hljs-keyword">import</span> { favoriteTeam, crops, product } <span class="hljs-keyword">from</span> <span class="hljs-string">"./module-1.js"</span>;

<span class="hljs-keyword">const</span> bestClub = <span class="hljs-string">`I bought <span class="hljs-subst">${product(<span class="hljs-number">2</span>, <span class="hljs-number">11</span>)}</span> <span class="hljs-subst">${crops[<span class="hljs-number">2</span>]}</span>s at <span class="hljs-subst">${favoriteTeam}</span>.`</span>;

<span class="hljs-built_in">console</span>.log(bestClub);
</code></pre>
<p><strong><a target="_blank" href="https://stackblitz.com/edit/web-platform-ir5f1h?devtoolsheight=33&amp;file=module-1.js">Try it on StackBlitz</a></strong></p>
<p>You can also rename multiple imports. Let's see how.</p>
<h2 id="heading-how-to-rename-multiple-imports-in-an-es-module">How to Rename Multiple Imports in an ES Module</h2>
<p>You can rename multiple imports by separating each <code>as</code> statement with a comma.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// module-1.js</span>

<span class="hljs-keyword">const</span> bestClub = <span class="hljs-string">"Your Club"</span>;
<span class="hljs-keyword">const</span> fruits = [<span class="hljs-string">"Grape"</span>, <span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Pineapple"</span>, <span class="hljs-string">"Lemon"</span>];
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-keyword">return</span> x * y;
}

<span class="hljs-comment">// Export the three statements above:</span>
<span class="hljs-keyword">export</span> { bestClub, fruits, multiply };
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">// module-2.js</span>

<span class="hljs-keyword">import</span> { 
  bestClub <span class="hljs-keyword">as</span> favoriteTeam, 
  fruits <span class="hljs-keyword">as</span> crops, 
  multiply <span class="hljs-keyword">as</span> product 
} <span class="hljs-keyword">from</span> <span class="hljs-string">"./module-1.js"</span>;

<span class="hljs-keyword">const</span> bestClub = <span class="hljs-string">`I bought <span class="hljs-subst">${product(<span class="hljs-number">2</span>, <span class="hljs-number">11</span>)}</span> <span class="hljs-subst">${crops[<span class="hljs-number">2</span>]}</span>s at <span class="hljs-subst">${favoriteTeam}</span>.`</span>;

<span class="hljs-built_in">console</span>.log(bestClub);
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-yinyru?devtoolsheight=33&amp;file=module-2.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Suppose you wish to import all exportable content from <code>module-1.js</code> without specifying each import's name. How can you do this? Let's find out.</p>
<h2 id="heading-how-to-import-all-exportable-items-from-an-es-module-in-one-go">How to Import All Exportable Items from an ES Module in One Go</h2>
<p>Suppose you wish to import all exportable items from a specific module without specifying each import's name. In such a case, use the <code>import * as</code> syntax to bring in the items through a module object.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Import all exportable features from the "countries.js" module:</span>
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> allCountries <span class="hljs-keyword">from</span> <span class="hljs-string">"./countries.js"</span>;
</code></pre>
<p>The statement above instructs the computer to import all exportable content of the <code>./countries.js</code> module and encase the imports in a module object named <code>allCountries</code>.</p>
<p>After the importation, you can use the imported items just as before. However, you now need to access them through the module object's name.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// module-1.js</span>

<span class="hljs-keyword">const</span> bestClub = <span class="hljs-string">"Your Club"</span>;
<span class="hljs-keyword">const</span> fruits = [<span class="hljs-string">"Grape"</span>, <span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Pineapple"</span>, <span class="hljs-string">"Lemon"</span>];
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-keyword">return</span> x * y;
}

<span class="hljs-comment">// Export the three statements above:</span>
<span class="hljs-keyword">export</span> { bestClub, fruits, multiply };
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">// module-2.js</span>

<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> firstModule <span class="hljs-keyword">from</span> <span class="hljs-string">"./module-1.js"</span>;

<span class="hljs-keyword">const</span> bestClub = <span class="hljs-string">`I bought <span class="hljs-subst">${firstModule.multiply(<span class="hljs-number">2</span>, <span class="hljs-number">11</span>)}</span> <span class="hljs-subst">${firstModule.fruits[<span class="hljs-number">2</span>]}</span>s at <span class="hljs-subst">${firstModule.bestClub}</span>.`</span>;

<span class="hljs-built_in">console</span>.log(bestClub);
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-s5bug2?devtoolsheight=33&amp;file=module-2.js"><strong>Try it on StackBlitz</strong></a></p>
<p>So, what if you prefer to export a module's content anonymously? Let's discuss the technique you can use.</p>
<h2 id="heading-how-to-export-anonymously-to-an-es-module">How to Export Anonymously to an ES Module</h2>
<p>So far, we have exported items by explicitly stating the name of the specific code we wish to share—for instance, <code>export { bestClub }</code>.</p>
<p>Such exportation technique is called the <strong>named export</strong>.</p>
<p>You can also export anonymously by using the <strong>default export</strong> technique. But what exactly is a default export? Let's find out.</p>
<h3 id="heading-what-exactly-is-a-default-export-in-es-modules">What Exactly Is a Default Export in ES Modules?</h3>
<p><strong>Default export</strong> is a technique developers use to export code anonymously (namelessly).</p>
<p>You can implement a default export by prepending the keyword <code>default</code> to the code you wish to export. By so doing, the computer will share the code as a default export.</p>
<p>In other words, the code will get exported with the special name, <code>default</code>—instead of its original name (if it had one).</p>
<p>So, during the code's importation, you will have the options to import it with the name <code>default</code>, a custom name of choice, or without any name.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// module-1.js</span>

<span class="hljs-keyword">const</span> bestClub = <span class="hljs-string">"Your Club"</span>;

<span class="hljs-comment">// Export the bestClub variable as a default export:</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> bestClub;
</code></pre>
<p>We did not use curly braces in the default export statement above because you can have only one default export in a module.</p>
<p>Alternatively, you can also rewrite the code above like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// module-1.js</span>

<span class="hljs-comment">// Export the string value as a default export:</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-string">"Your Club"</span>;
</code></pre>
<p>Keep in mind that you can use the default export technique to share a function, variable, string, class, or object literal.</p>
<p>However, you cannot prepend the <code>export default</code> keyword to a <code>var</code>, <code>let</code>, or <code>const</code> keyword.</p>
<p>In other words, the snippet below will throw a <code>SyntaxError</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">const</span> bestClub = <span class="hljs-string">"Your Club"</span>;
</code></pre>
<p>Let's now discuss how to import a default export.</p>
<h3 id="heading-how-to-import-a-default-export-into-an-es-module">How to Import a Default Export into an ES Module</h3>
<p>There are two equivalent ways to import a default export:</p>
<ul>
<li>Use the <code>default as</code> syntax</li>
<li>Specify the imported code's name only</li>
</ul>
<p>Let's discuss the two importation techniques.</p>
<h4 id="heading-how-to-use-the-default-as-syntax-to-import-a-default-export">How to use the <code>default as</code> syntax to import a default export</h4>
<p>One way to import a default export is to use the <code>default as</code> syntax like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { <span class="hljs-keyword">default</span> <span class="hljs-keyword">as</span> newName } <span class="hljs-keyword">from</span> <span class="hljs-string">"./module-relative-path.js"</span>;
</code></pre>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// module-1.js</span>

<span class="hljs-comment">// Export the string value as a default export:</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-string">"Your Club"</span>;
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">// module-2.js</span>

<span class="hljs-keyword">import</span> { <span class="hljs-keyword">default</span> <span class="hljs-keyword">as</span> favoriteTeam } <span class="hljs-keyword">from</span> <span class="hljs-string">"./module-1.js"</span>;

<span class="hljs-keyword">const</span> bestClub = favoriteTeam + <span class="hljs-string">" "</span> + <span class="hljs-string">"is my best club."</span>;

<span class="hljs-built_in">console</span>.log(bestClub);
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-zcyvst?devtoolsheight=33&amp;file=module-2.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Notice that we didn't need to specify the name of the code we imported from the <code>module-1.js</code> file. Instead, we used the <code>default</code> keyword to import the code anonymously.</p>
<p>Afterward, we renamed the imported code <em>as</em> <code>favoriteTeam</code>.</p>
<p>Let's now see the second way to import a default export.</p>
<h4 id="heading-how-to-import-a-default-export-by-specifying-the-imported-codes-name-only">How to import a default export by specifying the imported code's name only</h4>
<p>An alternate way to import a default export is to ignore the curly braces (<code>{...}</code>), the <code>default</code> keyword, and the <code>as</code> keyword.</p>
<p>Instead, simply specify the name you wish to use to reference the imported code like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> newName <span class="hljs-keyword">from</span> <span class="hljs-string">"./module-relative-path.js"</span>;
</code></pre>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// module-1.js</span>

<span class="hljs-comment">// Export the string value as a default export:</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-string">"Your Club"</span>;
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">// module-2.js</span>

<span class="hljs-keyword">import</span> favoriteTeam <span class="hljs-keyword">from</span> <span class="hljs-string">"./module-1.js"</span>;

<span class="hljs-keyword">const</span> bestClub = favoriteTeam + <span class="hljs-string">" "</span> + <span class="hljs-string">"is my best club."</span>;

<span class="hljs-built_in">console</span>.log(bestClub);
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-rgrlh7?devtoolsheight=33&amp;file=module-2.js"><strong>Try it on StackBlitz</strong></a></p>
<p>You can see that the shortened importation technique above is neater than the previous option.</p>
<p><strong>Note:</strong></p>
<ul>
<li>The <code>export default</code> statement makes it possible for a JavaScript module to interpolate (work reliable) with existing CommonJS and AMD module systems.</li>
<li>See the "<a target="_blank" href="https://hacks.mozilla.org/2015/08/es6-in-depth-modules/">Default exports</a>" section of <em>ES6 In Depth: Modules</em> to learn more about interpolation.</li>
</ul>
<p>Before we wrap up our discussion on ES modules, you should be aware that you can use an aggregator file to collate your project's <code>import</code> statements.</p>
<p>But what exactly is an aggregator file, I hear you ask? Let's find out below.</p>
<h2 id="heading-what-exactly-is-an-aggregator-file">What Exactly Is an Aggregator File?</h2>
<p>An <strong>aggregator file</strong> is a script used solely to import and re-export the items you've exported from other modules.</p>
<p>In other words, instead of congesting your <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary#top-level-module-javascript">top-level module</a> with multiple import statements from various files, you can create a single parent script (the aggregator file).</p>
<p>The parent script's sole purpose will be to import and re-export items from other modules.</p>
<p>Then, in your top-level module, you can simply import any required code from the aggregator file alone—not from numerous other scripts.</p>
<p>By so doing, you will make your top-level module neater.</p>
<p>So, what exactly does all this mean? Let's see with a mini-project.</p>
<h2 id="heading-project-how-to-use-an-aggregator-file">Project: How to Use an Aggregator File</h2>
<p>Follow the steps below to learn how to use an aggregator file.</p>
<h3 id="heading-step-1-create-a-project-directory-2">Step 1: Create a project directory</h3>
<p>Create a project folder—where this project's HTML and module files will reside.</p>
<h3 id="heading-step-2-create-your-code-files-2">Step 2: Create your code files</h3>
<p>Create the following files inside your project folder:</p>
<ol>
<li><code>index.html</code></li>
<li><code>index.js</code></li>
<li><code>preferences.js</code></li>
<li><code>calculation.js</code></li>
<li><code>bio.js</code></li>
</ol>
<h3 id="heading-step-3-add-the-modules-to-your-html-document-1">Step 3: Add the modules to your HTML document</h3>
<p>Open your <code>index.html</code> file and replicate the code below:</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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>ES Module - CodeSweetly<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>How to use an aggregator file - ES Module Tutorial<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Check the console<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"index.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"preferences.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"calculation.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"bio.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Here are the main things we did in the HTML snippet above:</p>
<ol>
<li>We added the four JavaScript files to our HTML document.</li>
<li>We used the <code>type="module"</code> attribute to convert the regular JavaScript files to ES module files.</li>
</ol>
<h3 id="heading-step-4-export-items-from-your-preference-module">Step 4: Export items from your <code>preference</code> module</h3>
<p>Open your <code>preferences.js</code> module and export some items from it like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bestFruits = [<span class="hljs-string">"Grape"</span>, <span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Pineapple"</span>, <span class="hljs-string">"Lemon"</span>];
<span class="hljs-keyword">const</span> bestColor = <span class="hljs-string">"White"</span>;
<span class="hljs-keyword">const</span> bestNumber = <span class="hljs-number">111</span>;
<span class="hljs-keyword">const</span> bestClub = <span class="hljs-string">"Your Club"</span>;
<span class="hljs-keyword">const</span> bestTime = <span class="hljs-string">"Now"</span>;

<span class="hljs-keyword">export</span> { bestClub, bestFruits };
</code></pre>
<h3 id="heading-step-5-export-items-from-your-calculation-module">Step 5: Export items from your <code>calculation</code> module</h3>
<p>Open your <code>calculation.js</code> module and export some items from it like so:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-keyword">return</span> x + y;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">subtract</span>(<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-keyword">return</span> x - y;
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-keyword">return</span> x * y;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">divide</span>(<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-keyword">return</span> x / y;
}
</code></pre>
<h3 id="heading-step-6-export-items-from-your-bio-module">Step 6: Export items from your <code>bio</code> module</h3>
<p>Open your <code>bio.js</code> module and export some items from it like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> aboutMe = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>,
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span>, 
  <span class="hljs-attr">companyName</span>: <span class="hljs-string">"CodeSweetly"</span>,
  <span class="hljs-attr">profession</span>: <span class="hljs-string">"Web Developer"</span>,
  <span class="hljs-attr">gender</span>: <span class="hljs-string">"Male"</span>,
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> aboutMe;
</code></pre>
<h3 id="heading-step-7-import-the-exported-features">Step 7: Import the exported features</h3>
<p>To import the exported items into your top-level module, you have two options:</p>
<ol>
<li>Import directly from the exporting modules to your top-level script.</li>
<li>Import from an aggregator file to your top-level module.</li>
</ol>
<p>Let's see the difference between the two options.</p>
<h4 id="heading-import-directly-from-the-exporting-modules-to-your-top-level-script">Import directly from the exporting modules to your top-level script</h4>
<p>One way to import your code is to import it directly from the exporting scripts to your top-level module.</p>
<p>For instance, open your <code>index.js</code> file and import the exported content of the <code>preferences.js</code>, <code>calculation.js</code>, and <code>bio.js</code> modules like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>

<span class="hljs-keyword">import</span> { bestFruits } <span class="hljs-keyword">from</span> <span class="hljs-string">"./preferences.js"</span>;
<span class="hljs-keyword">import</span> { multiply } <span class="hljs-keyword">from</span> <span class="hljs-string">"./calculation.js"</span>;
<span class="hljs-keyword">import</span> aboutMe <span class="hljs-keyword">from</span> <span class="hljs-string">"./bio.js"</span>;

<span class="hljs-keyword">const</span> news = <span class="hljs-string">`All <span class="hljs-subst">${aboutMe.companyName}</span>'s staff gave Tom <span class="hljs-subst">${multiply(<span class="hljs-number">7</span>, <span class="hljs-number">129</span>)}</span> <span class="hljs-subst">${bestFruits[<span class="hljs-number">2</span>]}</span>s.`</span>;

<span class="hljs-built_in">console</span>.log(news);
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-dqmd1u?devtoolsheight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>You can see that we imported items directly from three exporting scripts into the <code>index.js</code> module.</p>
<p>The above importation technique works OK. However, a cleaner alternative is to use an aggregator file. Let's see how.</p>
<h4 id="heading-import-from-an-aggregator-file-to-your-top-level-module">Import from an aggregator file to your top-level module</h4>
<p>An alternate way to bring in your code is to import it from an aggregator file to your top-level module.</p>
<p>Follow the steps below to see how you can create and use an aggregator file.</p>
<h5 id="heading-1-create-the-aggregator-file">1. Create the aggregator file</h5>
<p>You can name the file <code>aggregator.js</code> or any other name you prefer.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/module-tutorial-aggregator-file-highlight-codesweetly.png" alt="Create an aggregator file - Modules Tutorial" width="600" height="400" loading="lazy">
<em>A highlight of the project's aggregator file</em></p>
<h5 id="heading-2-add-the-aggregator-script-to-your-html-file">2. Add the aggregator script to your HTML file</h5>
<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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>ES Module - CodeSweetly<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>How to use an aggregator file - ES Module Tutorial<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Check the console<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"index.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"preferences.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"calculation.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"bio.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"aggregator.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Note the following:</p>
<ol>
<li><code>index.js</code> is the <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary#top-level-module-javascript">top-level module</a> because it is the file where we imported and used <code>preferences.js</code>, <code>calculation.js</code>, and <code>bio.js</code>.</li>
<li><code>preferences.js</code>, <code>calculation.js</code>, and <code>bio.js</code> are the <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary#submodule-javascript">submodules</a> because they are the files we imported into the top-level module.</li>
<li><code>aggregator.js</code> is the <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary#parent-module-es-module">parent module</a> because it is the script for aggregating and re-exporting the three submodules.</li>
</ol>
<p>Technically, you can indicate just the top-level module in your project's HTML file like so:</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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>ES Module - CodeSweetly<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>How to use an aggregator file - ES Module Tutorial<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Check the console<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"index.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>By so doing, you avoid cluttering your HTML page with the submodules and parent module.</p>
<p>Let's now see how to use the aggregator module.</p>
<h5 id="heading-3-use-the-aggregator-module-to-aggregate-the-submodules">3. Use the aggregator module to aggregate the submodules</h5>
<p>Here's how to use the aggregator module to import and re-export all your project's exported items:</p>
<pre><code class="lang-js"><span class="hljs-comment">// aggregator.js</span>

<span class="hljs-keyword">import</span> { bestFruits } <span class="hljs-keyword">from</span> <span class="hljs-string">"./preferences.js"</span>;
<span class="hljs-keyword">import</span> { multiply } <span class="hljs-keyword">from</span> <span class="hljs-string">"./calculation.js"</span>;
<span class="hljs-keyword">import</span> aboutMe <span class="hljs-keyword">from</span> <span class="hljs-string">"./bio.js"</span>;

<span class="hljs-keyword">export</span> { bestFruits, multiply, aboutMe };
</code></pre>
<p>You can see that we used the aggregator file only to import and re-export our project's exported features.</p>
<p>The shorthand way to write the <code>import</code>/<code>export</code> statements above is like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// aggregator.js</span>

<span class="hljs-keyword">export</span> { bestFruits } <span class="hljs-keyword">from</span> <span class="hljs-string">"./preferences.js"</span>;
<span class="hljs-keyword">export</span> { multiply } <span class="hljs-keyword">from</span> <span class="hljs-string">"./calculation.js"</span>;
<span class="hljs-keyword">export</span> { <span class="hljs-keyword">default</span> <span class="hljs-keyword">as</span> aboutMe } <span class="hljs-keyword">from</span> <span class="hljs-string">"./bio.js"</span>;
</code></pre>
<p>Keep in mind that the following syntax is invalid:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> aboutMe <span class="hljs-keyword">from</span> <span class="hljs-string">"./bio.js"</span>;
</code></pre>
<p>In other words, whenever you use the <code>export...from</code> syntax to re-export a default export, make sure that you rename the re-exportation like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> { <span class="hljs-keyword">default</span> <span class="hljs-keyword">as</span> aboutMe } <span class="hljs-keyword">from</span> <span class="hljs-string">"./bio.js"</span>;
</code></pre>
<p>Let's now see how to import the re-exported features from an aggregator file.</p>
<h5 id="heading-4-import-your-exports-from-the-aggregator-file">4. Import your exports from the aggregator file</h5>
<p>Once you've aggregated all your submodules into the aggregator module, go to your top-level script (<code>index.js</code> in this case) and import the exported items.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>

<span class="hljs-keyword">import</span> { bestFruits, multiply, aboutMe } <span class="hljs-keyword">from</span> <span class="hljs-string">"./aggregator.js"</span>;

<span class="hljs-keyword">const</span> news = <span class="hljs-string">`All <span class="hljs-subst">${aboutMe.companyName}</span>'s staff gave Tom <span class="hljs-subst">${multiply(<span class="hljs-number">7</span>, <span class="hljs-number">129</span>)}</span> <span class="hljs-subst">${bestFruits[<span class="hljs-number">2</span>]}</span>s.`</span>;

<span class="hljs-built_in">console</span>.log(news);
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-fttqqb?devtoolsheight=33&amp;file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>You see, like magic, we've cleaned up our code by replacing three <code>import</code> statements with a single line!</p>
<p>Using an aggregator file to collate your project's exports helps separate concerns and makes your top-level module neater.</p>
<p>Up till now, we've used the static <code>import</code> syntax to instruct the computer to evaluate our imported modules' code at load time.</p>
<p>But suppose you prefer to load your modules conditionally or on-demand. In that case, you can use the dynamic <code>import()</code> syntax. Let's see exactly how it works below.</p>
<h2 id="heading-how-to-use-the-import-syntax-to-load-a-module-dynamically">How to Use the <code>import()</code> Syntax to Load a Module Dynamically</h2>
<p>To load your module conditionally or on-demand, use the <code>import()</code> syntax like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span>(<span class="hljs-string">"./module/relative-path.js"</span>).then(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">module</span>) </span>{ });
</code></pre>
<p>The <code>import()</code> syntax does two main things:</p>
<ol>
<li>It loads its module specifier argument (<code>"./module/relative-path.js"</code> in this case).</li>
<li>It returns a promise object that resolves to a module object containing the import specifier's exports.</li>
</ol>
<p>So, since the <code>import()</code> syntax returns a promise, you can also use the <code>await</code> keyword with it.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> <span class="hljs-built_in">module</span> = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">"./module/relative-path.js"</span>);
</code></pre>
<p><strong>Note:</strong> Although <code>import()</code> resembles a function call, it is not. Instead, the <code>import()</code> code is a special ES modules syntax that uses parentheses (similar to the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super"><code>super()</code></a> syntax).</p>
<p>Therefore, you cannot <a target="_blank" href="https://www.codesweetly.com/call-apply-bind-javascript/#what-is-the-call-method">call</a>, <a target="_blank" href="https://www.codesweetly.com/call-apply-bind-javascript/#what-is-the-apply-method">apply</a>, or <a target="_blank" href="https://www.codesweetly.com/call-apply-bind-javascript/#what-is-the-bind-method">bind</a> the <code>import()</code> syntax because it does not inherit <code>Function.prototype</code>'s properties.</p>
<p>To see precisely how <code>import()</code> works in practice, let's update our previous project by following the steps below.</p>
<h3 id="heading-1-update-your-html-file">1. Update your HTML file</h3>
<p>Open your <code>index.html</code> file and do the following:</p>
<ol>
<li>Update your <code>&lt;h1&gt;</code>'s content to "The Latest News".</li>
<li>Substitute the <code>&lt;h2&gt;</code> element with an empty <code>&lt;p&gt;</code> element.</li>
<li>Create a <code>&lt;button&gt;</code> element.</li>
</ol>
<p>In other words, your <code>index.html</code> file should look like this:</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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>ES Module - CodeSweetly<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>The Latest News<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">id</span>=<span class="hljs-string">"news-paragraph"</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">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"news-button"</span>&gt;</span>Get the News<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"index.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h3 id="heading-2-update-your-indexjs-module">2. Update your <code>index.js</code> module</h3>
<p>Open your <code>index.js</code> file and replicate the code below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>

<span class="hljs-keyword">const</span> paragraphElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"news-paragraph"</span>);
<span class="hljs-keyword">const</span> buttonElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"news-button"</span>);

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayNews</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">let</span> news = <span class="hljs-literal">null</span>;
  <span class="hljs-comment">// highlight-next-line</span>
  <span class="hljs-keyword">const</span> aggregatorModule = <span class="hljs-keyword">await</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">"./aggregator.js"</span>);

  news = <span class="hljs-string">`All <span class="hljs-subst">${aggregatorModule.aboutMe.companyName}</span>'s staff gave Tom <span class="hljs-subst">${aggregatorModule.multiply(<span class="hljs-number">7</span>, <span class="hljs-number">129</span>)}</span> <span class="hljs-subst">${aggregatorModule.bestFruits[<span class="hljs-number">2</span>]}</span>s.`</span>;

  paragraphElement.innerText = news;
}

buttonElement.addEventListener(<span class="hljs-string">"click"</span>, displayNews);
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-pw3xpq?file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>You can see how we used the <code>import()</code> method to load the aggregator module on demand (when a user clicks the button)—rather than upfront.</p>
<p>Although dynamic importation can improve your program's initial load-time performance, it's best to use it only when needed.</p>
<p><strong>Note:</strong> The <code>import()</code> method does not require its <a target="_blank" href="https://www.codesweetly.com/javascript-arguments">argument</a> to have a <code>&lt;script&gt;</code> of <code>type="module"</code>. Therefore, you can use it in a regular JavaScript file.</p>
<p>Now, suppose you wish to get <a target="_blank" href="https://en.wikipedia.org/wiki/Metadata">metadata</a> about your current module. In that case, you can use the <code>import.meta</code> syntax.</p>
<h2 id="heading-what-exactly-is-importmeta-in-es-modules">What Exactly Is <code>import.meta</code> in ES Modules?</h2>
<p>The <code>import.meta</code> code is an object containing information about your current module.</p>
<p><strong>Here's an example:</strong></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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>ES Module - CodeSweetly<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>About import.meta<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Check the console ⬇⬇⬇<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span>&gt;</span><span class="javascript">
      <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">import</span>.meta);
      <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">import</span>.meta.url);
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-8ky5vd?devtoolsheight=33&amp;file=index.html"><strong>Try it on StackBlitz</strong></a></p>
<p>The <code>import.meta</code> code in the snippet above will return some information about the module in which it got used.</p>
<h2 id="heading-quick-review-of-modules-so-far">Quick Review of Modules So Far</h2>
<p>We've learned that a JavaScript module is simply a file with an add-on capability to share its code with other modules within a project—or <a target="_blank" href="https://www.codesweetly.com/package-manager-explained/#how-to-publish-your-project-to-the-npm-registry">with the world</a> through package managers like Yarn and NPM.</p>
<p>We also used a local server to load our HTML documents via an <code>http://</code> scheme—which made browsers load our apps without throwing any CORS error.</p>
<p>However, live servers are limited to local developments and testing purposes.</p>
<p>In other words, you cannot use a live server in production to serve your HTML document via an <code>http://</code> scheme. Instead, it would be best if you used a <em>module bundler</em>.</p>
<p>But what exactly is a module bundler, I hear you ask? Let's find out below.</p>
<h2 id="heading-what-is-a-module-bundler">What Is a Module Bundler?</h2>
<p>A <strong>module bundler</strong> is a tool developers use to bundle an app's <a class="post-section-overview" href="#heading-what-exactly-is-a-javascript-module-2">modules</a> and dependencies into a single browser-compatible JavaScript file.</p>
<h2 id="heading-why-do-you-need-a-module-bundler">Why Do You Need a Module Bundler?</h2>
<p>Module bundlers allow browsers to access the file you specified in a <code>require()</code> or <code>import</code> statement.</p>
<p>In other words, suppose a browser runs a JavaScript file with a <code>require("./node_module/test/sample/app.js")</code> statement. In such a case, the browser will throw an error that says <code>Uncaught ReferenceError: require is not defined</code>.</p>
<p>The computer will throw such an error because browsers cannot access files specified in a JavaScript program.</p>
<p>However, you can use a module bundler to create a new JavaScript file containing code browsers can read.</p>
<h2 id="heading-how-does-a-module-bundler-work">How Does a Module Bundler Work?</h2>
<p>A module bundler does its bundling work as follows:</p>
<h3 id="heading-first-it-creates-an-output-script-file">First, it creates an output script file</h3>
<p>The module bundler will first create an "output script file" in your project's <code>dist</code> folder.</p>
<p><strong>Note:</strong></p>
<ul>
<li>The bundler uses the <em>output script file</em> to save the bundled code.</li>
<li>An <strong>output file</strong> is the compiled version of an entry file. In other words, an output script file refers to the JavaScript file a bundler generates automatically for your project.</li>
<li>An <strong>entry point</strong> is a file that a bundler uses to start building a <a target="_blank" href="https://webpack.js.org/concepts/dependency-graph/">dependency graph</a> of all the project's modules it needs to combine into a single browser-compatible module.</li>
<li>An entry point is the most critical file of a build step that links (directly or indirectly) to every other module in a project.</li>
</ul>
<h3 id="heading-next-the-module-bundler-compiles-your-code">Next, the module bundler compiles your code</h3>
<p>Secondly, the bundler will check the build step's entry point for any occurrence of some <code>require()</code> or <code>import</code> statements.</p>
<p>Suppose the module bundler finds a <code>require()</code> or <code>import</code> statement. In such a case, the bundler will compile (combine) the content of each dependency specified in the statements with the entry point's content.</p>
<p><strong>Note:</strong></p>
<ul>
<li>A <strong>build step</strong> is a process through which a module bundler builds a new browser compatible JavaScript file.</li>
<li>A build step's output file is sometimes called a <strong>distribution code</strong>. In other words, distribution code is the minified and optimized source code version.</li>
<li>A <strong>dependency</strong> is a file your script requires to work as intended. So, in <code>import { variable } from "./path/to/module.js"</code>, <code>module.js</code> is the dependency file because it is a script our app depends on to function as designed.</li>
</ul>
<p>Let's now discuss the last thing a module bundler does.</p>
<h3 id="heading-finally-it-saves-the-compiled-code">Finally, it saves the compiled code</h3>
<p>A module bundler's last step is to save the compiled code into <a class="post-section-overview" href="#heading-first-it-creates-an-output-script-file">step 1</a>'s output script file.</p>
<p>As a result, step 1's script file (the build step's output) will contain the content of the entry point and its dependencies—but no <code>require()</code> or <code>import</code> statements.</p>
<p><strong>Note:</strong> Typical examples of module bundlers are <a target="_blank" href="https://webpack.js.org">webpack</a>, <a target="_blank" href="http://browserify.org/">browserify</a>, <a target="_blank" href="https://rollupjs.org/guide/en/">rollup</a>, and <a target="_blank" href="https://parceljs.org/">parcel</a>.</p>
<p>So, now that we know how a module bundler works, let's discuss how to use a popular one—<em>Webpack</em>.</p>
<h2 id="heading-how-to-use-webpack">How to Use Webpack</h2>
<p>Follow the steps below to learn how to use Webpack to bundle your project's JavaScript file and its dependencies into a single output script file.</p>
<h3 id="heading-step-1-create-a-project-directory-3">Step 1: Create a project directory</h3>
<p>Create a project folder—where this project's files will reside.</p>
<h3 id="heading-step-2-go-to-the-projects-root-folder">Step 2: Go to the project's root folder</h3>
<p>Using the command line, navigate to the root directory of your project like so:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> path/to/project/root-directory
</code></pre>
<p><strong>Note:</strong> A <strong>root directory</strong> is a folder containing all other files and sub-folders of a specific project.</p>
<p>In other words, the folder you created in step 1 is your root folder because it will house everything concerning this particular project.</p>
<h3 id="heading-step-3-create-a-packagejson-file">Step 3: Create a <code>package.json</code> file</h3>
<p>Create a <a target="_blank" href="https://www.codesweetly.com/package-json-file-explained">package.json</a> file in your project's root directory like so:</p>
<pre><code class="lang-bash">npm init -y
</code></pre>
<p>Alternatively, you can use Yarn like this:</p>
<pre><code class="lang-bash">yarn init -y
</code></pre>
<p><strong>Note:</strong></p>
<ul>
<li>The <code>-y</code> flag instructs NPM (or Yarn) to <a target="_blank" href="https://www.codesweetly.com/package-json-file-explained/#how-to-create-a-default-packagejson-file">create a default <code>package.json</code> file</a>.</li>
<li>You must have Node and NPM installed on your system for the initialization code above to work. You can get both by installing the latest LTS version from the <a target="_blank" href="https://nodejs.org/en/">Node.js</a> website.</li>
</ul>
<h3 id="heading-step-4-install-the-webpack-module-bundler">Step 4: Install the Webpack module bundler</h3>
<p>Install <code>webpack</code> and <code>webpack-cli</code> locally into your project as <a target="_blank" href="https://www.codesweetly.com/package-manager-explained/#npm-installation-command">development dependency</a> libraries:</p>
<pre><code class="lang-bash">npm install webpack webpack-cli --save-dev
</code></pre>
<p>Or, if your package manager is Yarn, run:</p>
<pre><code class="lang-bash">yarn add webpack webpack-cli --dev
</code></pre>
<p><strong>Note:</strong> The <code>webpack-cli</code> package makes running webpack on the command line possible.</p>
<h3 id="heading-step-5-create-your-projects-directories">Step 5: Create your project's directories</h3>
<p>Create a "source" code folder (<code>./src</code>) and a "distribution" code folder (<code>./dist</code>).</p>
<pre><code class="lang-bash">mkdir src dist
</code></pre>
<p><strong>Note:</strong> Although <code>src</code> and <code>dist</code> are the names typically given to the source and distribution code's folders, you are free to choose any other name you prefer.</p>
<h3 id="heading-step-6-create-your-source-code-files">Step 6: Create your source code files</h3>
<p>Create the following files inside the newly created source code directory:</p>
<ol>
<li><code>index.html</code></li>
<li><code>index.js</code></li>
</ol>
<p><strong>Note:</strong></p>
<ul>
<li>Webpack recommends saving <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary#source-code">source code</a> in a <code>./src</code> directory and <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary#distribution-code">distribution code</a> in a <code>./dist</code> directory.</li>
<li>Webpack does not alter any other code apart from the <code>require()</code>, <code>import</code>, and <code>export</code> statements.</li>
</ul>
<h3 id="heading-step-7-add-the-javascript-file-to-your-html-document">Step 7: Add the JavaScript file to your HTML document</h3>
<p>Open your <code>index.html</code> file and replicate the code below:</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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>ES Module - CodeSweetly<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> <span class="hljs-attr">id</span>=<span class="hljs-string">"body"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Module Bundler Tutorial<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">id</span>=<span class="hljs-string">"button"</span>&gt;</span>Click Me to Change Color!<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./index.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Here are the main things we did in the HTML snippet above:</p>
<ol>
<li>We created a <code>&lt;h1&gt;</code> and <code>&lt;button&gt;</code> element.</li>
<li>We added step 6's JavaScript file to our HTML document.</li>
</ol>
<p><strong>Note:</strong> When using a bundler, you do not need to add the <code>type="module"</code> attribute to your project's <code>&lt;script&gt;</code> element. Instead, the bundler will automatically treat all scripts containing <code>import</code> and <code>export</code> statements as modules.</p>
<h3 id="heading-step-8-install-some-dependencies">Step 8: Install some dependencies</h3>
<p>Using your text editor, <a target="_blank" href="https://www.codesweetly.com/package-manager-explained/#local-package-installation">install your project's dependencies locally</a>.</p>
<p>For instance, here's how you can install the <a target="_blank" href="https://www.npmjs.com/package/randomcolor">randomColor</a> package as a local dependency:</p>
<pre><code class="lang-bash">npm install randomcolor --save
</code></pre>
<p><strong>Note:</strong></p>
<ul>
<li>Use the <code>npm install package-name --save</code> command for dependencies your app needs in production.</li>
<li>Use the <code>npm install package-name --save-dev</code> command for dependencies your app only needs for its local development and testing purposes.</li>
</ul>
<p>Alternatively, you can use Yarn like so:</p>
<pre><code class="lang-bash">yarn add randomcolor
</code></pre>
<p><strong>Note:</strong> Use the <code>yarn add package-name --dev</code> command for dependencies your app only needs for its local development and testing purposes.</p>
<h3 id="heading-step-9-import-your-dependencies">Step 9: Import your dependencies</h3>
<p>Import your dependencies into your JavaScript source code with the <code>require()</code> method or the <code>import</code> statement.</p>
<p>For instance, here's how to use the <code>import</code> statement to bring in step 8's <code>randomColor</code> dependency into your <code>index.js</code> script file:</p>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>

<span class="hljs-keyword">import</span> randomColor <span class="hljs-keyword">from</span> <span class="hljs-string">"randomcolor"</span>;
</code></pre>
<p>The <code>require()</code> method equivalence of the snippet above is like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>

<span class="hljs-keyword">const</span> randomColor = <span class="hljs-built_in">require</span>(<span class="hljs-string">"randomcolor"</span>);
</code></pre>
<p><strong>Note:</strong></p>
<ul>
<li>The <code>import</code> statement is JavaScript's native way of importing modules.</li>
<li>The <code>require()</code> function is the CommonJS syntax for importing modules into a script.</li>
<li>An alternative way to import your project's dependencies is to implicitly load them with your HTML document's <code>&lt;script&gt;</code> tag. However, such a technique pollutes the global scope. So, using the <code>import</code> or <code>require()</code> syntax is better.</li>
</ul>
<h3 id="heading-step-10-use-the-dependencies">Step 10: Use the dependencies</h3>
<p>Use the dependencies you imported in step 9 to do as you desire.</p>
<p>For instance, here's how you may use the <code>randomColor</code> dependency:</p>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>

<span class="hljs-keyword">import</span> randomColor <span class="hljs-keyword">from</span> <span class="hljs-string">"randomcolor"</span>;

<span class="hljs-keyword">const</span> bodyElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"body"</span>);
<span class="hljs-keyword">const</span> buttonElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"button"</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">changeBodyColor</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> color = randomColor();
  bodyElement.style.backgroundColor = color;
}

buttonElement.addEventListener(<span class="hljs-string">"click"</span>, changeBodyColor);
</code></pre>
<p>In the snippet above, we told the computer that whenever a user clicks the <code>buttonElement</code>, it should:</p>
<ol>
<li>Invoke the <code>changeBodyColor</code> function.</li>
<li>Initialize the function's <code>color</code> variable with <code>randomColor</code>'s <a target="_blank" href="https://www.codesweetly.com/declaration-initialization-invocation-in-programming/#what-does-invocation-mean-in-programming">invocation</a> output.</li>
<li>Use the <code>color</code> variable's value to style the <code>bodyElement</code>'s background color.</li>
</ol>
<p>Let's now bundle up our entry point (the <code>index.js</code> file) and the <code>randomColor</code> dependency into a single JavaScript file.</p>
<h3 id="heading-step-11-start-the-build-step">Step 11: Start the build step</h3>
<p>Using your terminal, create your bundle by running webpack like so:</p>
<pre><code class="lang-bash">npx webpack
</code></pre>
<p>After running the command above, webpack will do the following:</p>
<ol>
<li>It will use your <code>index.js</code> as its entry point.</li>
<li>It will create a bundle (the output file) in your project's <code>dist</code> folder containing the content of the entry point and its dependencies.</li>
</ol>
<p><strong>Note:</strong></p>
<ul>
<li>By default, Webpack generates its bundle as a <code>main.js</code> file—which it will save in the distribution folder you created in step 5. However, you can change the default setting by creating a configuration file—which Webpack will use automatically. We will discuss creating and using a configuration file <a class="post-section-overview" href="#heading-what-exactly-is-webpacks-configuration-file-3">later</a> in this guide.</li>
<li><a target="_blank" href="https://nodejs.dev/learn/the-npx-nodejs-package-runner">NPX</a> is Node's package runner that will automatically find and execute Webpack.</li>
</ul>
<p>Our next step is to tell browsers to use the newly created bundle. Let's do that below.</p>
<h3 id="heading-step-12-refer-browsers-to-the-newly-created-bundle">Step 12: Refer browsers to the newly created bundle</h3>
<p>So, now that you have created a browser-compatible bundle file, you need to tell browsers to use it instead of the <code>index.js</code> source code file.</p>
<p>Therefore, go to your HTML file and substitute the reference to your JavaScript source code with Webpack's distribution bundle.</p>
<p>For instance, instead of using <code>"./index.js"</code> in the <code>&lt;script&gt;</code> tag of your HTML file, you would use <code>"../dist/main.js"</code> like so:</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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>ES Module - CodeSweetly<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> <span class="hljs-attr">id</span>=<span class="hljs-string">"body"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Module Bundler Tutorial<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">id</span>=<span class="hljs-string">"button"</span>&gt;</span>Click Me to Change Color!<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"../dist/main.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Let's now see our app!</p>
<h3 id="heading-step-13-check-your-app-in-the-browser">Step 13: Check your app in the browser</h3>
<p>Open your HTML file in the browser to confirm that the browser can successfully read your app and its dependencies.</p>
<p>Remember that you created your HTML file manually in <a class="post-section-overview" href="#heading-step-6-create-your-source-code-files">step 6</a>. However, Webpack can also auto-generate one for you. Let's find out how.</p>
<h2 id="heading-how-to-make-webpack-auto-generate-your-apps-html-file">How to Make Webpack Auto-Generate Your App's HTML File</h2>
<p>Suppose your app is now outputting multiple bundles, or you've started <a target="_blank" href="https://www.codesweetly.com/javascript-module-bundler#substitutions-technique-3-content-hash">using hashes</a> to create unique filenames. In that case, you may find it increasingly difficult to manage your HTML file manually.</p>
<p>Therefore, Webpack allows you to use the <a target="_blank" href="https://webpack.js.org/plugins/html-webpack-plugin/">HtmlWebpackPlugin</a> to auto-generate and manage your project's <code>index.html</code> file.</p>
<p>Follow the steps below to learn how to use <code>HtmlWebpackPlugin</code> to auto-generate and manage your project's HTML file.</p>
<h3 id="heading-step-1-install-htmlwebpackplugin">Step 1: Install <code>HtmlWebpackPlugin</code></h3>
<p>Install the <code>HtmlWebpackPlugin</code> like so:</p>
<pre><code class="lang-bash">npm install html-webpack-plugin --save-dev
</code></pre>
<p>Or, if your package manager is Yarn, use:</p>
<pre><code class="lang-bash">yarn add html-webpack-plugin --dev
</code></pre>
<h3 id="heading-step-2-create-a-configuration-file">Step 2: Create a configuration file</h3>
<p>Create a Webpack configuration file in your project's <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary#root-directory">root folder</a> like so:</p>
<pre><code class="lang-bash">touch webpack.config.js
</code></pre>
<h3 id="heading-step-3-add-the-plugin-to-webpacks-configuration">Step 3: Add the plugin to webpack's configuration</h3>
<p>Open your <code>webpack.config.js</code> file and add the <code>HtmlWebpackPlugin</code> plugin to it like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> HtmlWebpackPlugin = <span class="hljs-built_in">require</span>(<span class="hljs-string">"html-webpack-plugin"</span>);

<span class="hljs-built_in">module</span>.exports = { 
  <span class="hljs-attr">plugins</span>: [<span class="hljs-keyword">new</span> HtmlWebpackPlugin()] 
}
</code></pre>
<p><strong>Note:</strong> We will discuss how to use a configuration file <a class="post-section-overview" href="#heading-what-exactly-is-webpacks-configuration-file-3">later</a> in this guide.</p>
<h3 id="heading-step-4-run-the-build-step">Step 4: Run the build step</h3>
<p>Once you've installed and added <code>HtmlWebpackPlug</code> into your project, recompile your modules like so:</p>
<pre><code class="lang-bash">npx webpack
</code></pre>
<p>After running the build step, <code>HtmlWebpackPlugin</code> will do the following:</p>
<ol>
<li>It will auto-generate a new <code>index.html</code> file.</li>
<li>The plugin will automatically insert the bundles that Webpack generated into the newly created HTML document.</li>
<li>It will auto-save the new HTML file inside your project's distribution folder.</li>
</ol>
<p>In other words, after running a build, the <code>new HtmlWebpackPlugin()</code>'s invocation (in the configuration file) will auto-generate a <code>dist/index.html</code> file with the following content:</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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Webpack App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width,initial-scale=1"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">defer</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"main.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">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">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Notice that the HTML document generated by <code>HtmlWebpackPlugin</code> does not contain <a class="post-section-overview" href="#heading-step-7-add-the-javascript-file-to-your-html-document">your source file</a>'s <code>&lt;h1&gt;</code> and <code>&lt;button&gt;</code> elements.</p>
<p>In other words, suppose you open the <code>dist/index.html</code> file in the browser. In that case, the browser will open an empty HTML page.</p>
<p>The <code>HtmlWebpackPlugin</code> omitted the content of the source code's <code>&lt;body&gt;</code> element because it did not create the new file from the original document. Instead, it automatically created a brand-new HTML page that includes only the bundles Webpack generated.</p>
<p>However, you can also tell <code>HtmlWebpackPlugin</code> to use your source file as a template. Let's see how below.</p>
<h2 id="heading-how-to-make-htmlwebpackplugin-use-your-source-file-as-a-template-to-auto-generate-a-new-html-page">How to Make <code>HtmlWebpackPlugin</code> Use Your Source File as a Template to Auto-Generate a New HTML Page</h2>
<p>To make <code>HtmlWebpackPlugin</code> use your HTML source file as a template, do the following:</p>
<h3 id="heading-1-update-your-html-file-1">1. Update your HTML file</h3>
<p>Open your <code>index.html</code> <em>source code</em> file and delete the <code>&lt;script&gt;</code> tag you <a class="post-section-overview" href="#heading-step-12-refer-browsers-to-the-newly-created-bundle">previously used</a> to reference Webpack's distribution bundle.</p>
<p>So, your HTML source code should look like this:</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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>ES Module - CodeSweetly<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> <span class="hljs-attr">id</span>=<span class="hljs-string">"body"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Module Bundler Tutorial<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">id</span>=<span class="hljs-string">"button"</span>&gt;</span>Click Me to Change Color!<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>
<p>We deleted the distribution bundle's script because <code>HtmlWebpackPlugin</code> will automatically insert one while it auto-generates the new HTML file.</p>
<p><strong>Remember:</strong> The plugin will use your source code as a template to create the new file. Therefore, deleting the hand-coded bundle's reference helps avoid conflicting scripts.</p>
<p>Now, let's configure the plugin to use your source code as a template.</p>
<h3 id="heading-2-update-your-configuration-file">2.  Update your configuration file</h3>
<p>Open your project's <code>webpack.config.js</code> file and update <code>HtmlWebpackPlugin</code>'s settings like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> HtmlWebpackPlugin = <span class="hljs-built_in">require</span>(<span class="hljs-string">"html-webpack-plugin"</span>);

<span class="hljs-built_in">module</span>.exports = { 
  <span class="hljs-attr">plugins</span>: [<span class="hljs-keyword">new</span> HtmlWebpackPlugin({
    <span class="hljs-attr">template</span>: <span class="hljs-string">"./src/index.html"</span>
  })] 
}
</code></pre>
<p>In the configuration snippet above, we did the following:</p>
<ol>
<li>We passed an object argument containing a <code>template</code> property to the <code>HtmlWebpackPlugin</code> function.</li>
<li>We initialized the <code>template</code> property with the path to our HTML source code.</li>
</ol>
<p>So, if you now run the <code>npx webpack</code> command, <code>HtmlWebpackPlugin</code> will use <code>./src/index.html</code> as a template to generate the new <code>dist/index.html</code> file.</p>
<p>Therefore, the newly created HTML distribution file will look like so:</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">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>ES Module - CodeSweetly<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">defer</span>=<span class="hljs-string">"defer"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"main.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"body"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Module Bundler Tutorial<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">id</span>=<span class="hljs-string">"button"</span>&gt;</span>Click Me to Change Color!<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>
<p>Suppose an <code>index.html</code> file already exists in your output (<code>dist</code>) directory. In that case, the new one generated by <code>HtmlWebpackPlugin</code> will replace the existing HTML file.</p>
<h3 id="heading-3-check-your-app-in-the-browser">3. Check your app in the browser</h3>
<p>Open the newly generated <code>dist/index.html</code> file in the browser to confirm that the browser can successfully read your app and its dependencies.</p>
<p><strong>Note:</strong></p>
<ul>
<li><code>HtmlWebpackPlugin</code> allows you to specify how and where you want it to generate your HTML file by providing specific <a target="_blank" href="https://github.com/jantimon/html-webpack-plugin#options">configuration options</a>. For instance, <code>new HtmlWebpackPlugin({ title: "A CodeSweetly Project" })</code> tells the plugin to use <code>"A CodeSweetly Project"</code> as the title of the generated HTML file.</li>
<li>Suppose you get an error message (for instance, <code>ReferenceError: __webpack_base_uri__ is not defined</code>). In that case, you likely need to update your Webpack dependency. You can do so by running <code>npm update webpack webpack-cli</code> on your terminal.</li>
</ul>
<h2 id="heading-important-stuff-to-know-about-updating-your-app">Important Stuff to Know about Updating Your App</h2>
<p>Whenever you make changes to your source code, make sure you do the following for your updates to reflect in the browser:</p>
<ol>
<li>Rerun the build step.</li>
<li>Refresh your browser.</li>
</ol>
<p>Repeating the manual process of running the build step and refreshing your browser can be burdensome. Luckily, Webpack provides a way to automate the two tasks. Let's find out how.</p>
<h2 id="heading-how-to-rerun-webpack-automatically">How to Rerun Webpack Automatically</h2>
<p>Suppose you wish to automate the process of rerunning the build step. In that case, you can add a <code>watch</code> property to your <a target="_blank" href="https://www.codesweetly.com/package-json-file-explained/">package.json</a>'s <code>scripts</code> field.</p>
<p>For instance, do the following:</p>
<h3 id="heading-1-add-watch-to-the-scripts-fields">1. Add <code>watch</code> to the <code>scripts</code> fields</h3>
<p>Open your project's <code>package.json</code> file and add a <code>watch</code> property to its <code>scripts</code> field like so:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"your_package"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span>,
    <span class="hljs-attr">"watch"</span>: <span class="hljs-string">"webpack --progress --watch"</span>
  }
}
</code></pre>
<p>The snippet above added a <code>"watch"</code> property—with the value <code>"webpack --progress --watch"</code>—to the <code>"scripts"</code> field of our <code>package.json</code> file.</p>
<h3 id="heading-2-run-the-watch-script">2. Run the <code>watch</code> script</h3>
<p>Using your terminal, invoke your <code>package.json</code>'s <code>watch</code> script like so:</p>
<pre><code class="lang-bash">npm run watch
</code></pre>
<p>Alternatively, you can use Yarn like this:</p>
<pre><code class="lang-bash">yarn run watch
</code></pre>
<p>Once you've invoked the <code>watch</code> script, NPM will execute <code>"webpack --progress --watch"</code>.</p>
<h3 id="heading-what-is-webpack-progress-watch">What is <code>"webpack --progress --watch"</code>?</h3>
<p>The <code>"webpack --progress --watch"</code> command instructs NPM to:</p>
<ol>
<li>Run Webpack.</li>
<li>Pass the <code>--progress</code> and <code>--watch</code> options to Webpack's configuration.</li>
</ol>
<p>The <code>--progress</code> option will make NPM show the percentage progress of Webpack's compilation.</p>
<p>The <code>--watch</code> option activates Webpack's watch mode.</p>
<p>In other words, <code>--watch</code> instructs Webpack to watch and automatically recompile your modules each time you save changes to files within your dependency graph.</p>
<p>As an example, go to your <code>index.js</code> file and add a <code>console.log</code> statement to the <code>changeBodyColor()</code> function like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// index.js</span>

<span class="hljs-keyword">import</span> randomColor <span class="hljs-keyword">from</span> <span class="hljs-string">"randomcolor"</span>;

<span class="hljs-keyword">const</span> bodyElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"body"</span>);
<span class="hljs-keyword">const</span> buttonElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"button"</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">changeBodyColor</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> color = randomColor();
  bodyElement.style.backgroundColor = color;
  <span class="hljs-built_in">console</span>.log(color);
}

buttonElement.addEventListener(<span class="hljs-string">"click"</span>, changeBodyColor);
</code></pre>
<p>Afterward, save your changes. Then refresh your browser.</p>
<p>After the refresh, do the following:</p>
<ol>
<li>Open your browser's console.</li>
<li>Click your app's <code>"Click Me to Change Color!"</code> button.</li>
</ol>
<p>You can see that the <code>--watch</code> flag automatically recompiled your modules when you saved your source code's changes.</p>
<p>Therefore, you no longer need to run the <code>npx webpack</code> command manually again. Instead, the <code>--watch</code> flag will watch and automatically recompile your modules whenever you save changes.</p>
<p><strong>Note:</strong></p>
<ul>
<li>After running <code>npm run watch</code>, your currently opened terminal will continue to process the <code>watch</code> command's activities. So, you won't be able to input any command on that terminal until you stop <code>watch</code>'s execution. However, you can open a new terminal window to use simultaneously with the one processing <code>watch</code>. In other words, use one terminal to run <code>watch</code> and another to input commands.</li>
<li>To stop <code>watch</code>'s execution, use <code>ctrl + c</code> on windows or <code>cmd + c</code> on mac.</li>
<li>You can rename the <code>"watch"</code> key (or any other <a target="_blank" href="https://www.codesweetly.com/package-json-file-explained/#scripts">scripts' key</a>) to any other name you prefer.</li>
<li>You can ignore watching huge folders like <code>node_modules</code> by adding them to the <a target="_blank" href="https://webpack.js.org/configuration/watch/#watchoptionsignored">watchOptions.ignored</a> field of your project's <a target="_blank" href="https://www.codesweetly.com/javascript-module-bundler#what-exactly-is-webpacks-configuration-file">configuration file</a>.</li>
</ul>
<p>So, now that we know how to automate Webpack's execution, let's discuss how to reload the browser automatically.</p>
<h2 id="heading-how-to-reload-the-browser-automatically">How to Reload the Browser Automatically</h2>
<p>Suppose you wish to automate the process of reloading your browser. In that case, you can use Webpack's <a target="_blank" href="https://github.com/webpack/webpack-dev-server">dev server</a> package.</p>
<p>The following steps will show you how to configure and use the package.</p>
<h3 id="heading-step-1-install-webpacks-web-server">Step 1: Install webpack's web server</h3>
<p>Using your terminal, install the <code>webpack-dev-server</code> package like so:</p>
<pre><code class="lang-bash">npm install webpack-dev-server --save-dev
</code></pre>
<p>Or, if your package manager is Yarn, run:</p>
<pre><code class="lang-bash">yarn add webpack-dev-server --dev
</code></pre>
<p><strong>Note:</strong> The <code>webpack-dev-server</code> package enables watch mode by default. Therefore, you do not need to enable a <code>watch</code> script manually whenever you use the dev server.</p>
<p>In other words, once you've decided to use Webpack's dev server, do the following:</p>
<ol>
<li>Use <code>ctrl + c</code> on windows or <code>cmd + c</code> on mac to stop <code>watch</code>'s execution (if the script is still running).</li>
<li>Delete the <code>watch</code> property you <a class="post-section-overview" href="#heading-how-to-rerun-webpack-automatically-1">previously added</a> to your <code>package.json</code> file.</li>
</ol>
<h3 id="heading-step-2-specify-your-files-location">Step 2: Specify your files' location</h3>
<p>Tell the web server where it should get the files that Webpack did not generate by adding a <code>devServer</code> option to the configuration file you <a class="post-section-overview" href="#heading-step-2-create-a-configuration-file">created previously</a>:</p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> HtmlWebpackPlugin = <span class="hljs-built_in">require</span>(<span class="hljs-string">"html-webpack-plugin"</span>);

<span class="hljs-built_in">module</span>.exports = { 
  <span class="hljs-attr">plugins</span>: [<span class="hljs-keyword">new</span> HtmlWebpackPlugin({
    <span class="hljs-attr">template</span>: <span class="hljs-string">"./src/index.html"</span>
  })],
  <span class="hljs-attr">devServer</span>: {
    <span class="hljs-attr">static</span>: <span class="hljs-string">"./dist"</span>
  }
}
</code></pre>
<p>The configuration snippet above tells the dev server to serve contents Webpack did not build from the project's <code>dist</code> folder.</p>
<p>Note that the dev server serves files on <code>localhost:8080</code> by default. However, you can specify the port you wish to use by adding a <code>port</code> property to the <code>devServer</code> option like so:</p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> HtmlWebpackPlugin = <span class="hljs-built_in">require</span>(<span class="hljs-string">"html-webpack-plugin"</span>);

<span class="hljs-built_in">module</span>.exports = { 
  <span class="hljs-attr">plugins</span>: [<span class="hljs-keyword">new</span> HtmlWebpackPlugin({
    <span class="hljs-attr">template</span>: <span class="hljs-string">"./src/index.html"</span>
  })],
  <span class="hljs-attr">devServer</span>: {
    <span class="hljs-attr">static</span>: <span class="hljs-string">"./dist"</span>,
    <span class="hljs-attr">port</span>: <span class="hljs-number">5001</span>
  }
}
</code></pre>
<p><strong>Note:</strong></p>
<ul>
<li><code>webpack-dev-server</code> uses <a target="_blank" href="https://www.codesweetly.com/javascript-module-bundler#outputpath">output.path</a>'s directory to serve bundled files.<br>In other words, the dev server will use <code>http://[devServer.host]:[devServer.port]/[output.publicPath]/[output.filename]</code> to generate the bundled file's URL.</li>
<li>We will discuss how to use a configuration file <a class="post-section-overview" href="#heading-what-exactly-is-webpacks-configuration-file-3">later</a> in this guide.</li>
</ul>
<p>Let's now see how to run the dev server.</p>
<h3 id="heading-step-3-run-the-dev-server">Step 3: Run the dev server</h3>
<p>There are two ways to run the dev server.</p>
<ul>
<li>Use NPX on your CLI</li>
<li>Use <code>package.json</code>'s scripts field</li>
</ul>
<p>Let's discuss both ways below.</p>
<h4 id="heading-how-to-run-webpacks-dev-server-by-using-npx-on-your-cli">How to run Webpack's dev server by using NPX on your CLI</h4>
<p>Using the terminal, navigate to your project's root directory—where the <code>webpack.config.js</code> file is—then use NPX to run the dev server like this:</p>
<pre><code class="lang-bash">npx webpack serve --mode development --open
</code></pre>
<p>The snippet above uses NPX to do the following:</p>
<ol>
<li>Run the build step by executing Webpack.</li>
<li>Serve the build step's output file from memory, not your hard disk.</li>
</ol>
<p><strong>Note:</strong></p>
<ul>
<li>The dev server requires an HTML document (usually an <code>index.html</code> file) to serve the build step's output.</li>
<li>The <code>--mode development</code> flag tells Webpack to run the build step in development mode.</li>
<li>The <code>--open</code> flag tells the dev server to open your default browser.</li>
</ul>
<p>Keep in mind that the dev server does not save the build step's output file to any of your project's directories. Instead, it does the following:</p>
<ol>
<li>It keeps the build step's output files <a target="_blank" href="https://en.wikipedia.org/wiki/In-memory_processing">in memory</a> (your system's RAM).</li>
<li>It serves the output files from memory, not your system's <a target="_blank" href="https://www.computerhope.com/jargon/m/memory.htm#storage">hard drive</a>.</li>
</ol>
<p>Using your system's memory to build and serve the output file makes the dev server fast at serving your bundle.</p>
<p>However, when your app is ready for production, remember to run the <code>npx webpack</code> compilation command to save your bundle in your project's distribution folder—rather than in memory.</p>
<p>Let's now discuss the second way to run the dev server.</p>
<h4 id="heading-how-to-run-webpacks-dev-server-by-using-packagejsons-scripts-field">How to run Webpack's dev server by using <code>package.json</code>'s scripts field</h4>
<p>An alternate way to run the dev server is to add the <code>"webpack serve --mode development --open"</code> command to your <code>package.json</code>'s <code>scripts</code> field like so:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"your_package"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span>,
    <span class="hljs-attr">"start"</span>: <span class="hljs-string">"webpack serve --mode development --open"</span>
  }
}
</code></pre>
<p>Afterward, you can use <code>npm run start</code> on your terminal to execute the <code>webpack serve --mode development --open</code> command.</p>
<p>Once you've started the dev server—via either option 1 or 2, your default browser will automatically open with your project's HTML page.</p>
<p>Then, anytime you save changes to your source code, the dev server will automatically reload your browser to reflect the recent updates.</p>
<p><strong>Note:</strong></p>
<ul>
<li>After running <code>npm run start</code>, your currently opened terminal will continue to process the dev server's activities. So, you won't be able to input any command on that terminal until you stop the server. However, you can open a new terminal window while using the current one to process the server. In other words, use one terminal to run the dev server and another to input commands.</li>
<li>To stop the dev server's execution, use <code>ctrl + c</code> on windows or <code>cmd + c</code> on mac.</li>
<li>You can rename the <code>"start"</code> key (or any other <a target="_blank" href="https://www.codesweetly.com/package-json-file-explained/#scripts">scripts' key</a>) to any other name you prefer.</li>
<li>Check out <a target="_blank" href="https://webpack.js.org/configuration/dev-server">Webpack's documentation</a> for more ways to configure the dev server.</li>
</ul>
<p>Remember that we used a configuration file in <a class="post-section-overview" href="#heading-step-2-specify-your-files-location">step 2</a>. Let's talk more about what the file does.</p>
<h2 id="heading-what-exactly-is-webpacks-configuration-file">What Exactly Is Webpack's Configuration File?</h2>
<p>Webpack's <strong>configuration file</strong> is a JavaScript file that allows you to modify or extend Webpack's default settings.</p>
<p>For instance, Webpack's default setting assumes your project's entry point is <code>src/index.js</code>.</p>
<p>Also, by default, Webpack will minimize, optimize, and output the result of its build step into a <code>dist/main.js</code> file.</p>
<p>However, suppose you wish to change those default settings (or add more configurations). In such a case, you would need to create a configuration file—which Webpack will use automatically.</p>
<p>The following steps will show you how to create and use a Webpack configuration file.</p>
<p><strong>Note:</strong> You can skip steps 1 and 2 if your project already has a configuration file.</p>
<h3 id="heading-step-1-go-to-the-projects-root-folder">Step 1: Go to the project's root folder</h3>
<p>Navigate to your project's root directory like so:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> path/to/project/root-directory
</code></pre>
<h3 id="heading-step-2-create-your-projects-configuration-file">Step 2: Create your project's configuration file</h3>
<p>Create a configuration file in your project's root folder like so:</p>
<pre><code class="lang-bash">touch webpack.config.js
</code></pre>
<h3 id="heading-step-3-specify-your-configurations">Step 3: Specify your configurations</h3>
<p>Open your project's <code>webpack.config.js</code> file and specify the <a target="_blank" href="https://webpack.js.org/configuration/#options">configuration options</a> you wish to change (or add).</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> HtmlWebpackPlugin = <span class="hljs-built_in">require</span>(<span class="hljs-string">"html-webpack-plugin"</span>);

<span class="hljs-built_in">module</span>.exports = { 
  <span class="hljs-attr">plugins</span>: [<span class="hljs-keyword">new</span> HtmlWebpackPlugin()] 
};
</code></pre>
<p>Here's what we did in the configuration file above:</p>
<ol>
<li>We initialized the <code>HtmlWebpackPlugin</code> variable with the <code>"html-webpack-plugin"</code> package.</li>
<li>We exported an object containing the <code>plugins</code> configuration we want Webpack to use.</li>
</ol>
<p>So, whenever you run the build step, Webpack will automatically use the settings you've specified in the configuration file—rather than its default settings.</p>
<p>Let's now run the build step.</p>
<h3 id="heading-step-4-run-the-module-bundler">Step 4: Run the module bundler</h3>
<p>Using your terminal, create your bundle by running Webpack like so:</p>
<pre><code class="lang-bash">npx webpack --config webpack.config.js
</code></pre>
<p>The <code>--config webpack.config.js</code> code used in the snippet above is optional. We used it above to illustrate that it is possible to pass a configuration of <a target="_blank" href="https://webpack.js.org/configuration/#use-a-different-configuration-file">any name</a>—which you may need for complex configurations that requires a split into multiple files.</p>
<p>However, Webpack will use the <code>webpack.config.js</code> file by default if it is present in your project's root directory.</p>
<p>Keep in mind that <a target="_blank" href="https://webpack.js.org/concepts/plugins/">plugins</a> is only one of the numerous options you can use in a configuration file.</p>
<p>Let's discuss other configuration options developers use.</p>
<h2 id="heading-common-webpack-configuration-options">Common Webpack Configuration Options</h2>
<p>Below are popular configuration options you can use to alter (or extend) Webpack's default settings.</p>
<h3 id="heading-entry">entry</h3>
<p>The <code>entry</code> field specifies the file or files you want Webpack to use to begin the application's bundling process.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">"./src/index.js"</span>,
};
</code></pre>
<p>The snippet above instructs Webpack to start its bundling process from <code>"./src/index.js"</code>.</p>
<p>Suppose you used an array (or an object) as the <code>entry</code> field's value. In that case, Webpack will process all the array's (or object's) items as the application's entry points.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: [
    <span class="hljs-string">"./src/index.js"</span>,
    <span class="hljs-string">"./src/index-two.js"</span>,
    <span class="hljs-string">"./src/index-three.js"</span>
  ]
}
</code></pre>
<p>The code above instructs Webpack to start its bundling process from the three files specified in the <code>entry</code> array (that is, <code>"./src/index.js"</code>, <code>"./src/index-two.js"</code>, and <code>"./src/index-three.js"</code>).</p>
<p><strong>Here's another example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: {
    <span class="hljs-attr">index</span>: <span class="hljs-string">"./src/index.js"</span>,
    <span class="hljs-attr">indexTwo</span>: <span class="hljs-string">"./src/index-two.js"</span>,
    <span class="hljs-attr">indexThree</span>: <span class="hljs-string">"./src/index-three.js"</span>
  }
}
</code></pre>
<p>The code above instructs Webpack to start its bundling process from the three files specified in the <code>entry</code> object (that is, <code>"./src/index.js"</code>, <code>"./src/index-two.js"</code>, and <code>"./src/index-three.js"</code>).</p>
<p><strong>Note:</strong></p>
<ul>
<li>If <code>entry</code>'s value is a string or an array, Webpack will create a chunk (bundle)—which it will name <code>main</code> by default.</li>
<li>If <code>entry</code>'s value is an object, Webpack will create one or more chunks. The specific number of chucks created will depend on the total properties of the object.</li>
<li>Supposing <code>entry</code>'s value is an object. In that case, Webpack will use each key to name each chunk. For instance, in <code>entry: { home: './home-module.js' }</code>, Webpack will create a chunk (bundle) named <code>home</code>.</li>
</ul>
<h3 id="heading-context">context</h3>
<p>The <code>context</code> field points Webpack to the directory containing your entry files.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">context</span>: path.resolve(__dirname, <span class="hljs-string">"src"</span>)
}
</code></pre>
<p>The snippet above tells Webpack to locate the <code>index.js</code> entry file in the project's <code>src</code> directory.</p>
<h3 id="heading-output">output</h3>
<p>The <code>output</code> field specifies how and where Webpack should output the bundles and assets it processed.</p>
<p>The three options commonly used with the <code>output</code> field are <code>path</code>, <code>filename</code>, and <code>clean</code>.</p>
<h4 id="heading-outputpath">output.path</h4>
<p>The <code>output.path</code> option specifies the output directory you want Webpack to place the bundled file.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">"./src/index.js"</span>,
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
  }
}
</code></pre>
<p>The snippet above used the <code>output.path</code> option to tell Webpack to use the project's <code>"./dist"</code> folder as the output directory.</p>
<h4 id="heading-outputfilename">output.filename</h4>
<p>The <code>output.filename</code> option specifies how Webpack should name each bundle it creates.</p>
<p>Suppose you are creating only a single bundle via one entry point. In that case, you can specify a static name as the bundle's filename.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">"./src/index.js"</span>,
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"codesweetly.js"</span>,
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
  }
}
</code></pre>
<p>The <code>output.filename</code> option tells Webpack to use <code>"codesweetly.js"</code> as the filename of the bundle created after processing <code>"./src/index.js"</code>.</p>
<p>Suppose you wish to create multiple bundles through two or more entry points, code splitting, or various plugins. In such a case, it is better to dynamically generate each bundle's filename via any of Webpack's substitutions techniques.</p>
<p><strong>Note:</strong> Substitutions—in Webpack—refer to using bracketed strings to create <a target="_blank" href="https://webpack.js.org/configuration/output/#template-strings">templates</a> for filenames.</p>
<p>Let's now discuss the three commonly used substitution techniques.</p>
<h5 id="heading-substitutions-technique-1-entry-name">Substitutions technique 1: Entry name</h5>
<p>The <strong>"entry name"</strong> substitutions naming technique makes Webpack create each bundle's name by <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary#concatenation">concatenating</a> a bundle's entry point's name with a given string.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: {
    <span class="hljs-attr">home</span>: <span class="hljs-string">"./src/home-module.js"</span>,
    <span class="hljs-attr">promo</span>: <span class="hljs-string">"./src/promo-module.js"</span>,
    <span class="hljs-attr">music</span>: <span class="hljs-string">"./src/music-module.js"</span>
  },
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"[name].bundle.js"</span>,
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
  }
}
</code></pre>
<p>The <code>output.filename</code> option tells Webpack to create each bundle's filename by concatenating each entry point's name with the <code>".bundle.js"</code> string value.</p>
<p>So, for instance, suppose Webpack has finished processing the <code>promo</code> entry point (that is, <code>"./src/promo-module.js"</code>). In that case, the final bundle's name will be <code>"promo.bundle.js"</code>.</p>
<p>Let's now discuss the second substitutions technique.</p>
<h5 id="heading-substitutions-technique-2-internal-chunk-id">Substitutions technique 2: Internal chunk id</h5>
<p>The <strong>"internal chunk id"</strong> substitutions naming technique makes Webpack create each bundle's name by concatenating a bundle's entry point's id with a given string.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: {
    <span class="hljs-attr">home</span>: <span class="hljs-string">"./src/home-module.js"</span>,
    <span class="hljs-attr">promo</span>: <span class="hljs-string">"./src/promo-module.js"</span>,
    <span class="hljs-attr">music</span>: <span class="hljs-string">"./src/music-module.js"</span>
  },
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"[id].bundle.js"</span>,
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
  }
}
</code></pre>
<p>The <code>output.filename</code> option tells Webpack to create each bundle's filename by concatenating each entry point's internal chuck id with the <code>".bundle.js"</code> string value.</p>
<p>Let's now discuss the third substitutions technique.</p>
<h5 id="heading-substitutions-technique-3-content-hash">Substitutions technique 3: Content hash</h5>
<p>The <strong>"content hash"</strong> substitutions naming technique makes Webpack create each bundle's name by concatenating the generated content's hashes with a given string.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: {
    <span class="hljs-attr">home</span>: <span class="hljs-string">"./src/home-module.js"</span>,
    <span class="hljs-attr">promo</span>: <span class="hljs-string">"./src/promo-module.js"</span>,
    <span class="hljs-attr">music</span>: <span class="hljs-string">"./src/music-module.js"</span>
  },
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"[contenthash].bundle.js"</span>,
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
  }
}
</code></pre>
<p>The <code>output.filename</code> option tells Webpack to create each bundle's filename by concatenating each chunk's content hash with the <code>".bundle.js"</code> string value.</p>
<p>Keep in mind that Webpack allows you to combine different substitutions—for instance, <code>filename: "[name].[contenthash].bundle.js"</code>.</p>
<p>You can also use a function to return a filename like so:</p>
<pre><code class="lang-js">filename: <span class="hljs-function">(<span class="hljs-params">pathData</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> pathData.chunk.name === <span class="hljs-string">"main"</span> ? <span class="hljs-string">"[name].js"</span> : <span class="hljs-string">"[name].bundle.js"</span>;
}
</code></pre>
<p>Webpack also permits you to initialize the filename property with a folder structure like so:</p>
<pre><code class="lang-js">filename: <span class="hljs-string">"codesweetly/[name]/bundle.js"</span>
</code></pre>
<p>Now, let's discuss the third property developers commonly use within the <code>output</code> field.</p>
<h4 id="heading-outputclean">output.clean</h4>
<p>As Webpack increasingly generates and saves files into your output directory, it is common to clutter a project's <code>/dist</code> folder with unused files.</p>
<p>So, a good practice is to clean your output directory before each build step. By so doing, your <code>/dist</code> folder will contain used files only.</p>
<p>Let's see how to do the cleanup below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">"./src/index.js"</span>,
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"codesweetly.js"</span>,
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>),
    <span class="hljs-attr">clean</span>: <span class="hljs-literal">true</span>
  }
}
</code></pre>
<p>The <code>clean</code> option in the snippet above tells Webpack to clean the project's output directory before each build step.</p>
<p>In other words, Webpack will empty the output directory before it begins each build step.</p>
<p>Therefore, the output directory will contain only the files generated from the compilation process—not any of the old files that Webpack previously saved there.</p>
<p>Let's now discuss another popular configuration option that you can use to alter (or extend) Webpack's default settings.</p>
<h3 id="heading-module">module</h3>
<p>The <code>module</code> field makes Webpack process assets—like CSS files and fonts—as <a class="post-section-overview" href="#heading-what-exactly-is-a-javascript-module-2">modules</a> in the dependency graph.</p>
<p>So, suppose you want Webpack to bundle non-JavaScript assets such as images, CSS files, fonts, and so on. In such a case, you can use the <code>module</code> option to specify how Webpack should manage those assets before adding them to the dependency graph.</p>
<p>Below are some common ways to use the <code>module</code> option.</p>
<h4 id="heading-how-to-use-webpacks-module-option-to-load-css-stylesheets">How to use Webpack's <code>module</code> option to load CSS stylesheets</h4>
<p>Here's how you can use Webpack's module option to load CSS stylesheets:</p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">"./src/index.js"</span>,
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"main.js"</span>,
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
  },
  <span class="hljs-attr">module</span>: {
    <span class="hljs-attr">rule</span>: [
      {
        <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.css$/i</span>,
        use: [<span class="hljs-string">"style-loader"</span>, <span class="hljs-string">"css-loader"</span>]
      }
    ]
  }
}
</code></pre>
<p>The configuration snippet above used the <code>module</code> property to tell Webpack to use <code>"style-loader"</code> and <code>"css-loader"</code> to load CSS files.</p>
<p>Keep in mind that the loaders' order matters.</p>
<p>In other words, Webpack reads the loaders from right to left. Therefore, it will first execute the <code>"css-loader"</code> before the <code>"style-loader"</code>.</p>
<p>So, <a target="_blank" href="https://github.com/webpack-contrib/css-loader">"css-loader"</a> will pass its result (that is, the processed resource) to the <code>"style-loader"</code>. Then, <a target="_blank" href="https://github.com/webpack-contrib/style-loader">"style-loader"</a> will insert the final CSS resource into the <code>&lt;head&gt;</code> element of your HTML page.</p>
<p>It is necessary to install the loaders you want Webpack to use in loading your CSS assets.</p>
<p>So, for instance, before Webpack can use the previous configuration file to load ".css" assets, you need to install <code>"style-loader"</code> and the <code>"css-loader"</code>.</p>
<p>Here's how to install the two loaders:</p>
<pre><code class="lang-bash">npm install style-loader css-loader --save-dev
</code></pre>
<p>Alternatively, if your package manager is Yarn, run:</p>
<pre><code class="lang-bash">yarn add style-loader css-loader --dev
</code></pre>
<p><strong>Note:</strong></p>
<ul>
<li><code>"css-loader"</code> helps to interpret and resolve <code>@import</code> and <code>url()</code> items such as <code>import</code>, <code>require()</code>, and <code>url('./my-image.png')</code>.</li>
<li><code>"style-loader"</code> helps to inject a <code>&lt;style&gt;</code> tag and the styles derived from <code>"css-loader"</code> to your project's HTML file.</li>
</ul>
<p>Let's now see how to use the <code>module</code> option to load images.</p>
<h4 id="heading-how-to-use-webpacks-module-option-to-load-images">How to use Webpack's <code>module</code> option to load images</h4>
<p>Here's how you can use Webpack's <code>module</code> option to load images:</p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">"./src/index.js"</span>,
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"main.js"</span>,
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
  },
  <span class="hljs-attr">module</span>: {
    <span class="hljs-attr">rule</span>: [
      {
        <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.(png|svg|jpg|jpeg|gif)$/i</span>,
        type: <span class="hljs-string">"asset/resource"</span>
      }
    ]
  }
}
</code></pre>
<p>The configuration snippet above used the module property to tell webpack to load <code>".png"</code>, <code>".svg"</code>, <code>".jpg"</code>, <code>".jpeg"</code>, and <code>".gif"</code> files as <a target="_blank" href="https://webpack.js.org/guides/asset-modules/#resource-assets">resource asset modules</a>.</p>
<p>So, suppose the following <code>import</code> statement is in your script file:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> anyImage <span class="hljs-keyword">from</span> <span class="hljs-string">"./your-image.png"</span>;
</code></pre>
<p>In such a case, here's how Webpack will load the image:</p>
<ol>
<li>Webpack will process <code>your-image.png</code>.</li>
<li>It will add the processed image to your <em>output</em> directory.</li>
<li>Webpack will initialize the <code>anyImage</code> variable with the processed image's URL.</li>
</ol>
<p><strong>Note:</strong> While processing and adding <code>your-image.png</code> to the output folder, Webpack will change the image's filename to something like <code>150b55a1bf7461efb720.png</code>.</p>
<p>Let's now see how to use the <code>module</code> option to load fonts.</p>
<h4 id="heading-how-to-use-webpacks-module-option-to-load-fonts">How to use Webpack's <code>module</code> option to load fonts</h4>
<p>Here's how you can use Webpack's <code>module</code> option to load fonts:</p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">"./src/index.js"</span>,
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"main.js"</span>,
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
  },
  <span class="hljs-attr">module</span>: {
    <span class="hljs-attr">rule</span>: [
      {
        <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.(woff|woff2|eot|ttf|otf)$/i</span>,
        type: <span class="hljs-string">"asset/resource"</span>
      }
    ]
  }
}
</code></pre>
<p>The configuration snippet above used the <code>module</code> property to tell Webpack to load <code>".woff"</code>, <code>".woff2"</code>, <code>".eot"</code>, <code>".ttf"</code>, and <code>".otf"</code> files as <a target="_blank" href="https://webpack.js.org/guides/asset-modules/#resource-assets">resource asset modules</a>.</p>
<p>Once you've configured the loader, you can incorporate your fonts via the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face">@font-face</a> CSS declaration.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-comment">/* styles.css */</span>

<span class="hljs-keyword">@font-face</span> {
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Digital7"</span>;
  <span class="hljs-attribute">src</span>: <span class="hljs-built_in">url</span>(<span class="hljs-string">"./digital-7.regular.woff"</span>) <span class="hljs-built_in">format</span>(<span class="hljs-string">"woff"</span>),
       <span class="hljs-built_in">url</span>(<span class="hljs-string">"./digital-7.regular.ttf"</span>) <span class="hljs-built_in">format</span>(<span class="hljs-string">"truetype"</span>);
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">600</span>;
  <span class="hljs-attribute">font-style</span>: italic;
}

<span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">color</span>: red;
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Digital7"</span>;
}
</code></pre>
<p>Whenever <code>css-loader</code> loads the stylesheet above, it will process the specified fonts and add the processed copies to your project's output directory.</p>
<p><strong>Note:</strong></p>
<ul>
<li>Webpack will change the processed fonts' filename to something similar to <code>93911ab167c943140756.ttf</code>.</li>
<li>See <a target="_blank" href="https://webpack.js.org/guides/asset-management/#loading-data">Webpack's documentation</a> to learn how to load JSON, CSV, TSV, and XML files.</li>
</ul>
<p>Let's now discuss another popular configuration option that you can use to alter (or extend) Webpack's default settings.</p>
<h3 id="heading-devtool">devtool</h3>
<p>The <code>devtool</code> field tells Webpack to convert a compiled file to the source code format. Therefore, making it easier for you to debug the exact file (and line) where an error occurred in your source code.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">"./src/index.js"</span>,
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"main.js"</span>,
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
  },
  <span class="hljs-attr">devtool</span>: <span class="hljs-string">"source-map"</span>
}
</code></pre>
<p>At compilation time, if Webpack sees a <code>devtool</code> property in your configuration script, it will generate a <code>.js.map</code> file that the browser will use instead of the <code>.js</code> file.</p>
<p><strong>Note:</strong> There are different <a target="_blank" href="https://webpack.js.org/configuration/devtool/">devtool options</a> for specifying if and how Webpack should generate the source maps.</p>
<p>Let's now discuss another popular configuration option that you can use to alter (or extend) Webpack's default settings.</p>
<h3 id="heading-mode">mode</h3>
<p>The <code>mode</code> field tells Webpack the specific built-in optimization configuration you want it to use to build your output file.</p>
<p>You can specify whether Webpack should use <code>production</code>, <code>development</code>, or no (<code>none</code>) configuration to optimize your bundle. Let's discuss each of the three optimization settings below.</p>
<h4 id="heading-development-mode">Development mode</h4>
<p>A <code>mode: "development"</code> setting tells Webpack to build an output file for use in the development environment.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">"./src/index.js"</span>,
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"main.js"</span>,
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
  },
  <span class="hljs-attr">devtool</span>: <span class="hljs-string">"source-map"</span>,
  <span class="hljs-attr">mode</span>: <span class="hljs-string">"development"</span>
}
</code></pre>
<p>Setting a <code>mode: "development"</code> configuration will make Webpack create a bundle that:</p>
<ul>
<li>is fast to build</li>
<li>is less optimized</li>
<li>includes comments</li>
<li>is not minified</li>
<li>produces helpful error messages</li>
<li>is easy to debug</li>
</ul>
<p>Here's an example of a <code>mode: "development"</code> bundle:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/bundle-development-mode-webpack-codesweetly.png" alt="A development mode bundle" width="600" height="400" loading="lazy">
<em>Image of a development mode bundle compiled with webpack</em></p>
<p>To make a non-minified output file readable, ensure Webpack's <a class="post-section-overview" href="#heading-devtool">devtool</a> field is not <code>eval</code>.</p>
<p>Whenever you set the <code>mode</code> to <code>development</code>, Webpack may default <code>devtool</code>'s value to <code>eval</code>. So, ensure to select a different <code>devtool</code>—like <a target="_blank" href="https://webpack.js.org/configuration/devtool/#devtool">source-map</a> or disable it by setting its value to <code>"false"</code>—whenever you wish to make your output file readable.</p>
<p>Suppose you choose to run Webpack in development mode. In that case, remember to change your configuration to production mode when you are ready to deploy your app.</p>
<p>Now, let's discuss configuring Webpack to build your output file in production mode.</p>
<h4 id="heading-production-mode">Production mode</h4>
<p>A <code>mode: "production"</code> setting tells Webpack to build an output file for use in the production environment.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">"./src/index.js"</span>,
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"main.js"</span>,
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
  },
  <span class="hljs-attr">devtool</span>: <span class="hljs-string">"source-map"</span>,
  <span class="hljs-attr">mode</span>: <span class="hljs-string">"production"</span>
}
</code></pre>
<p>Setting a <code>mode: "production"</code> configuration will make Webpack create a bundle that:</p>
<ul>
<li>is slow to build</li>
<li>is more optimized</li>
<li>excludes comments</li>
<li>is minified</li>
<li>does not produce detailed error messages</li>
<li>is difficult to debug</li>
</ul>
<p>Here's an example of a <code>mode: "production"</code> bundle:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/bundle-production-mode-webpack-codesweetly.png" alt="A production mode bundle" width="600" height="400" loading="lazy">
<em>Image of a production mode bundle compiled with webpack</em></p>
<p><strong>Note:</strong> Webpack <a target="_blank" href="https://webpack.js.org/guides/production/#source-mapping">recommends</a> having source maps—like <code>source-map</code>—enabled in production.</p>
<p>Now, let's discuss configuring Webpack to build your output file without any optimization settings.</p>
<h4 id="heading-none-mode">None mode</h4>
<p>A <code>mode: "none"</code> setting tells Webpack to build an output file without optimizing it for development or production.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// webpack.config.js</span>

<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">"./src/index.js"</span>,
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"main.js"</span>,
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
  },
  <span class="hljs-attr">mode</span>: <span class="hljs-string">"none"</span>
}
</code></pre>
<p>Here's an example of a <code>mode: "none"</code> bundle:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/05/bundle-none-mode-webpack-codesweetly.png" alt="A none mode bundle" width="600" height="400" loading="lazy">
<em>Image of a none mode bundle compiled with webpack</em></p>
<h4 id="heading-important-stuff-to-know-about-the-mode-option">Important stuff to know about the <code>mode</code> option</h4>
<p>To make switching between development and production mode easy, you can store the <code>mode</code> configurations in the <code>"scripts"</code> field of your <code>package.json</code> file.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"your-app-name"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span>,
    <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"webpack --mode development"</span>,
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"webpack --mode production"</span>
  }
}
</code></pre>
<p>The snippet above initialized the scripts' <code>"dev"</code> property with Webpack's <code>development</code> mode command.</p>
<p>Likewise, we initialized the scripts' <code>"build"</code> property with Webpack's <code>production</code> mode command.</p>
<p>Therefore, suppose you execute <code>npm run dev</code> on your terminal. In that case, Webpack will execute the build step in development mode.</p>
<h2 id="heading-overview">Overview</h2>
<p>This article discussed what a JavaScript module is and how it works. We also discussed how to use a popular module bundler (Webpack) to bundle a project's JavaScript file and its dependencies into a single output file.</p>
<p>And there we have it. I hope you have found this article helpful.</p>
<p>Thanks for reading!</p>
<h3 id="heading-and-heres-a-useful-reactjs-resource"><strong>And here's a useful ReactJS resource:</strong></h3>
<p>I wrote a book about React!</p>
<ul>
<li>It's beginners friendly ✔</li>
<li>It has live code snippets ✔</li>
<li>It contains scalable projects ✔</li>
<li>It has plenty of easy-to-grasp examples ✔</li>
</ul>
<p>The <a target="_blank" href="https://www.amazon.com/dp/B09KYGDQYW">React Explained Clearly</a> book is all you need to understand ReactJS.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B09KYGDQYW"><img src="https://www.freecodecamp.org/news/content/images/2022/01/Twitter-React_Explained_Clearly-CodeSweetly-Oluwatobi_Sofela.jpg" alt="React Explained Clearly Book Now Available at Amazon" width="600" height="400" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Package Manager – Complete Guide to NPM and Yarn ]]>
                </title>
                <description>
                    <![CDATA[ A package manager is a tool developers use to automate finding, downloading, installing, configuring, upgrading, and removing a system's packages. This article will show you all you need to get started with package managers like NPM and Yarn. But why... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-package-manager-npm-and-yarn/</link>
                <guid isPermaLink="false">66ba0dfd7fb82b484b253a2b</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ npm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Yarn ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Tue, 05 Apr 2022 00:08:08 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/package-manager-npm-and-yarn-explained-curology-pDsmoI5j3B8-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A <strong>package manager</strong> is a tool developers use to automate finding, downloading, installing, configuring, upgrading, and removing a system's packages.</p>
<p>This article will show you all you need to get started with package managers like NPM and Yarn.</p>
<p>But why exactly do we need a package manager in our development workflow? Let's find out.</p>
<h2 id="heading-why-do-you-need-a-package-manager">Why Do You Need a Package Manager?</h2>
<p>Suppose there were no package managers. In that case, you would have to do the following manually:</p>
<ul>
<li>Find all the correct packages for your project</li>
<li>Verify that the packages don't have any known vulnerabilities</li>
<li>Download the packages</li>
<li>Install them at the appropriate location</li>
<li>Keep track of new updates for all your packages</li>
<li>Upgrade each package whenever there is a new release</li>
<li>Remove the packages you no longer need</li>
</ul>
<p>Manually managing tens or hundreds of packages is a tiresome and time-consuming endeavor.</p>
<p>Therefore, package managers—such as <a target="_blank" href="https://www.npmjs.com/">NPM</a>, <a target="_blank" href="https://pnpm.io/">pNPM</a>, <a target="_blank" href="https://bower.io/">Bower</a>, and <a target="_blank" href="https://yarnpkg.com/">Yarn</a>—help automate and eliminate the tedious process of managing all your packages manually.</p>
<p>Keep in mind that a package manager is not the same as a package registry. So, let's find out the main difference.</p>
<h2 id="heading-package-manager-vs-package-registry-whats-the-difference">Package Manager vs. Package Registry – What's the Difference?</h2>
<p>A <strong>package manager</strong> is a tool developers use to automatically find, download, install, configure, upgrade, and uninstall a computer's packages.</p>
<p>NPM (Node Package Manager) and Yarn (Yet Another Resource Negotiator) are two popularly used package managers.</p>
<p>A <strong>package registry</strong> is a database (storage) for thousands of packages (libraries, plugins, frameworks, or tools).</p>
<p>In other words, a package registry is the place packages get published to and installed from.</p>
<p><a target="_blank" href="https://www.npmjs.com/">NPM registry</a> and <a target="_blank" href="https://github.com/features/packages">GitHub Packages</a> are two popularly used package registries.</p>
<p>So, now that we know what a package manager is and why it is needed, we can discuss how to use the two popular ones—NPM and Yarn.</p>
<p>Note that there are numerous NPM vs. Yarn debates out there – so we will avoid them here because the best package manager is the one that works best for you.</p>
<p>Therefore, this article will show you how NPM and Yarn work rather than tell you which package manager is best. It is then up to you to decide which you prefer.</p>
<p>Alternatively, you can choose to use NPM for a specific project and Yarn for another—depending on which manager you believe is best suited for the job.</p>
<p>So, without any further ado, let's begin by learning how to install the two managers.</p>
<h2 id="heading-how-to-install-node-package-manager-npm">How to Install Node Package Manager (NPM)</h2>
<p>NPM gets installed automatically while installing Node.</p>
<p>Therefore, to get NPM installed on your system, go to the <a target="_blank" href="https://nodejs.org/en/">NodeJS</a> website and get Node's <a target="_blank" href="https://tamalweb.com/which-nodejs-version">latest LTS or the current version</a>.</p>
<h2 id="heading-how-to-install-yarn">How to Install Yarn</h2>
<p>It is best to install Yarn through NPM. So, first, install NPM from the <a target="_blank" href="https://nodejs.org/en/">Node.js</a> website.</p>
<p>Once you've installed NPM, proceed to install Yarn like so:</p>
<pre><code class="lang-bash">npm install -g yarn
</code></pre>
<h2 id="heading-how-to-check-the-installed-node-version">How to Check the Installed Node Version</h2>
<p>To check the Node.js version installed on your system, run:</p>
<pre><code class="lang-bash">node -v
</code></pre>
<p>The <code>-v</code> flag in the snippet above is a shorthand for <code>--version</code>.</p>
<h2 id="heading-how-to-check-the-installed-npm-version">How to Check the Installed NPM Version</h2>
<p>To check the NPM version installed on your system, run:</p>
<pre><code class="lang-bash">npm -v
</code></pre>
<h2 id="heading-how-to-check-the-installed-yarn-version">How to Check the Installed Yarn Version</h2>
<p>To check the Yarn version installed on your system, run:</p>
<pre><code class="lang-bash">yarn -v
</code></pre>
<h2 id="heading-how-to-upgrade-node-package-manager">How to Upgrade Node Package Manager</h2>
<p>Update to the latest NPM version by running:</p>
<pre><code class="lang-bash">npm install npm@latest -g
</code></pre>
<h2 id="heading-how-to-upgrade-nodejs">How to Upgrade NodeJS</h2>
<p>Suppose you wish to upgrade your Node.js installation. In that case, you have two options:</p>
<h3 id="heading-option-1-upgrade-via-the-nodejs-website">Option 1: Upgrade via the NodeJS website</h3>
<p>One way to upgrade your NodeJS installation is to manually download and install the latest version from the <a target="_blank" href="https://nodejs.org/en/">Node.js website</a>.</p>
<h3 id="heading-option-2-upgrade-via-a-version-management-tool">Option 2: Upgrade via a version management tool</h3>
<p>Another way to upgrade your NodeJS installation is to use a <a target="_blank" href="https://nodejs.org/en/download/package-manager/">version manager</a> such as <a target="_blank" href="https://github.com/nvm-sh/nvm">NVM</a>, <a target="_blank" href="https://github.com/tj/n">n</a>, or <a target="_blank" href="https://github.com/jasongin/nvs">nvs</a>.</p>
<h2 id="heading-how-to-upgrade-yarn">How to Upgrade Yarn</h2>
<p>Update to the latest Yarn version by running:</p>
<pre><code class="lang-bash">yarn <span class="hljs-built_in">set</span> version latest
</code></pre>
<p>So, now that we have NPM (or Yarn) on our computer, we can start using the installed manager to find, install, configure, and remove our project's packages.</p>
<p>But what exactly is a package? Let's find out.</p>
<h2 id="heading-what-exactly-is-a-package">What Exactly Is a Package?</h2>
<p>A <strong>package</strong> is a <a target="_blank" href="https://www.codesweetly.com/git-basic-introduction/#h-working-directory">directory</a> (or project) that has a <code>package.json</code> file used to record information about it.</p>
<p><strong>Note:</strong> You can only publish packages (a project described by a <code>package.json</code> file) to the <a target="_blank" href="https://docs.npmjs.com/cli/v6/using-npm/registry">NPM registry</a>.</p>
<h2 id="heading-how-to-install-packages">How to Install Packages</h2>
<p>There are two ways to install a package: locally or globally.</p>
<h3 id="heading-local-package-installation">Local package installation</h3>
<p>A locally installed package is one that you can use only in the project in which you've installed it.</p>
<p>To install a package locally, do the following:</p>
<ol>
<li>Navigate to the <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary/#h-root-directory">root directory</a> of your project from the command line.</li>
<li>Install your package using the NPM or Yarn installation command below (depending on the package manager you've chosen to use for your project).</li>
</ol>
<p><strong>Note:</strong> You must have Node and NPM installed on your system for the NPM (and Yarn) installation commands below to work. You can get both by installing the latest LTS or the current version from the Node.js website.</p>
<h4 id="heading-npm-installation-command">NPM installation command</h4>
<pre><code class="lang-bash">npm install package-name --save
</code></pre>
<p>Note that the <code>--save</code> command above instructs NPM to save <code>package-name</code> in the <code>package.json</code> file as one of the packages on which the project depends.</p>
<p>Suppose you wish to install an exact version of a package. In such a case, add a <code>@[version-number]</code> after the package's name like so:</p>
<pre><code class="lang-bash">npm install package-name@4.14.1 --save
</code></pre>
<p>Alternatively, if the package you are installing is for development and testing purposes, use:</p>
<pre><code class="lang-bash">npm install package-name --save-dev
</code></pre>
<p>The commands above will cause NPM to download three items into your project's root directory: a <code>node_modules</code> folder, a <code>package.json</code> file, and a <code>package-lock.json</code> file. We will discuss these items in detail later on in this article.</p>
<h4 id="heading-yarn-installation-command">Yarn installation command</h4>
<pre><code class="lang-bash">yarn add package-name
</code></pre>
<p>Suppose you wish to install an exact version of a package. In such a case, add a <code>@[version-number]</code> after the package's name like so:</p>
<pre><code class="lang-bash">yarn add package-name@4.14.1
</code></pre>
<p>Alternatively, if the package you are installing is for development and testing purposes, use:</p>
<pre><code class="lang-bash">yarn add package-name --dev
</code></pre>
<p>The commands above will cause Yarn to download three items into your project's root directory: a <code>node_modules</code> folder, a <code>package.json</code> file, and a <code>yarn.lock</code> file. We will discuss these items in detail later on in this article.</p>
<p>So, now that we know how to install a package locally, we can discuss the global package installation.</p>
<h3 id="heading-global-package-installation">Global package installation</h3>
<p>A globally installed package is a package that you can use anywhere on your system.</p>
<p>To install a package globally, run the code below on your terminal:</p>
<pre><code class="lang-bash">npm install package-name -g
</code></pre>
<p>Alternatively, you can use Yarn like so:</p>
<pre><code class="lang-bash">yarn global add package-name
</code></pre>
<p>Note that you can run the commands above from any location on your system.</p>
<h3 id="heading-local-vs-global-package-installation">Local vs. global package installation</h3>
<p>Generally, it is better to install a package locally. Below are some of the differences between a local and global installation.</p>
<h4 id="heading-difference-1-installation-location">Difference 1: Installation location</h4>
<p>A locally installed package gets installed in the directory where you executed the <code>npm install package-name</code> (or <code>yarn add package-name</code>) command.</p>
<p>Specifically, you will find a project's locally installed packages in its <code>node_module</code> directory.</p>
<p>In contrast, a globally installed package gets installed in a single location on your system. The exact location depends on your system's configuration.</p>
<h4 id="heading-difference-2-package-versions">Difference 2: Package versions</h4>
<p>Suppose you installed your package locally. Then, you can use different versions of the same package for multiple app development.</p>
<p>However, you are forced to use the same package version for all your apps when you install globally.</p>
<h4 id="heading-difference-3-updates">Difference 3: Updates</h4>
<p>A local installation allows you to choose the project's packages you wish to upgrade to the latest version. This makes it easier to manage upgrades that break compatibility with other packages.</p>
<p>However, upgrading a globally installed package updates the package for all projects—which can cause maintenance nightmares if the upgrade breaks compatibility with other packages.</p>
<h4 id="heading-difference-4-usage-recommendation">Difference 4: Usage recommendation</h4>
<p>Global installation is best for packages you intend to use only on your command line—especially when they provide executable commands reusable across projects.</p>
<p>However, local installation is best for packages you intend to use in your program—through the <code>import</code> statement or <code>require()</code> function.</p>
<h4 id="heading-difference-5-examples">Difference 5: Examples</h4>
<p><a target="_blank" href="https://www.npmjs.com/">NPM</a>, <a target="_blank" href="https://reactnative.dev/docs/environment-setup">React Native CLI</a>, <a target="_blank" href="https://www.gatsbyjs.com/docs/reference/gatsby-cli/">Gatsby CLI</a>, <a target="_blank" href="https://gruntjs.com/getting-started">Grunt CLI</a>, and <a target="_blank" href="https://cli.vuejs.org/">Vue CLI</a> are well-known examples of global packages.</p>
<p>Common examples of local packages are <a target="_blank" href="https://webpack.js.org/">Webpack</a>, <a target="_blank" href="https://lodash.com/">Lodash</a>, <a target="_blank" href="https://jestjs.io/">Jest</a>, and <a target="_blank" href="https://momentjs.com/">MomentJS</a>.</p>
<p><strong>Note:</strong></p>
<ul>
<li>You can <a target="_blank" href="https://nodejs.org/en/blog/npm/npm-1-0-global-vs-local-installation/#when-you-can-t-choose">do both local and global installation</a> of packages you intend to use both on the command line and in your project. Typical examples of such packages are <a target="_blank" href="https://expressjs.com/">ExpressJS</a> and <a target="_blank" href="https://coffeescript.org/">CoffeeScript</a>.</li>
<li>Your package manager does not execute an installed package. NPM (and Yarn) only install packages to the <code>node_modules</code> directory. And if you had specified the <code>--save</code> command, your manager would add details about the package to the <code>package.json</code> file.</li>
<li>To execute (run) any <a target="_blank" href="https://helpdeskgeek.com/how-to/what-is-an-executable-file-how-to-create-one/">executable</a> package, you must explicitly do so yourself. We will discuss how in a later section of this article.</li>
</ul>
<p>But what exactly are the <code>node_modules</code> folder, <code>package.json</code> file, <code>package-lock.json</code> file, and <code>yarn.lock</code> file? Let's find out.</p>
<h2 id="heading-what-is-a-nodemodules-folder">What Is a <code>node_modules</code> Folder?</h2>
<p>The <strong>node_modules</strong> directory is the folder where NPM places all the packages it downloads locally for your project.</p>
<h2 id="heading-what-is-a-packagejson-file">What Is a <code>package.json</code> File?</h2>
<p>A <strong>package.json</strong> file is a JSON document that package managers—like NPM and Yarn—use to store information about a specific project.</p>
<p>In other words, a <code>package.json</code> file is a project's metadata file.</p>
<h3 id="heading-advantages-of-a-packagejson-file">Advantages of a <code>package.json</code> File</h3>
<p>A <code>package.json</code> file:</p>
<ul>
<li>makes it possible to publish your project to the NPM registry</li>
<li>makes it easy for others to manage and install your package</li>
<li>helps NPM manage a <a target="_blank" href="https://www.codesweetly.com/javascript-modules-tutorial/">module</a>'s dependencies easily</li>
<li>makes your package reproducible and shareable with other developers</li>
</ul>
<h3 id="heading-how-to-create-a-packagejson-file">How to Create a <code>package.json</code> File</h3>
<p>Go to your project's root directory and initialize the creation of a <code>package.json</code> file by running:</p>
<pre><code class="lang-bash">npm init
</code></pre>
<p>Or, if your package manager is Yarn, run:</p>
<pre><code class="lang-bash">yarn init
</code></pre>
<p>Once you've executed the initialization command above, your package manager will walk you through creating the <code>package.json</code> file by asking a few questions about your project.</p>
<p>If you wish to skip the questionnaire, you can create a default <code>package.json</code> file. Let's see how.</p>
<h3 id="heading-how-to-create-a-default-packagejson-file">How to Create a Default <code>package.json</code> File</h3>
<p>Suppose you prefer to skip the questionnaire prompted by the <code>npm init</code> (or <code>yarn init</code>) command. In such a case, go to your project's <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary/#h-root-directory">root directory</a> and run:</p>
<pre><code class="lang-bash">npm init -y
</code></pre>
<p>Or, if your package manager is Yarn, run:</p>
<pre><code class="lang-bash">yarn init -y
</code></pre>
<p>The command above will use <a target="_blank" href="https://docs.npmjs.com/creating-a-package-json-file#default-values-extracted-from-the-current-directory">default values extracted from the current directory</a> to create your project's <code>package.json</code> file.</p>
<p><strong>Note:</strong> The <code>-y</code> flag is a shorthand for <code>--yes</code>.</p>
<p>Once your package manager finishes its initialization process, your project's <code>package.json</code> file will contain an object with a set of properties.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"codesweetly-project"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>
}
</code></pre>
<p>You can see that the <code>package.json</code> file above contains the <code>name</code>, <code>version</code>, and <code>main</code> fields. Let's learn more about these properties below.</p>
<h3 id="heading-the-packagejsons-fields">The <code>package.json</code>'s Fields</h3>
<p>The <code>package.json</code>'s properties make your project usable to package managers and end-users.</p>
<p>Suppose you wish to publish your package to the NPM registry. In that case, your <code>package.json</code> file must have the <code>"name"</code> and <code>"version"</code> fields.</p>
<p>However, if you do not intend to publish your package, in that case, all fields—including the <code>"name"</code> and <code>"version"</code> properties—are optional.</p>
<p>Let's learn more about the commonly used fields in a <code>package.json</code> file.</p>
<h4 id="heading-name">name</h4>
<p>The <code>"name"</code> field is a property used to record a project's name.</p>
<p>The <code>"name"</code> property's value must be:</p>
<ul>
<li>a single word</li>
<li>lowercase lettering</li>
<li>and less than or equal to 214 characters</li>
</ul>
<p>Note that you can join words together with hyphens and underscores.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"code_sweetly-project"</span>
}
</code></pre>
<h4 id="heading-version">version</h4>
<p>The <code>"version"</code> field indicates a project's current version number.</p>
<p>The <code>"version"</code> property must be in the form of a <code>major.minor.patch</code> format. It must also follow the <a target="_blank" href="https://docs.npmjs.com/about-semantic-versioning">semantic versioning guidelines</a>.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>
}
</code></pre>
<h4 id="heading-description">description</h4>
<p>The <code>"description"</code> field is a property containing a brief description of a project's purpose.</p>
<p>NPM recommends having a <code>"description"</code> property to make your package easier to find on the NPM website.</p>
<p>Your description will be one of the things that's shown when people run the <code>npm search</code> command.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">"A brief description about this package (project)"</span>
}
</code></pre>
<h4 id="heading-main">main</h4>
<p>The <code>"main"</code> field indicates a project's <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary/#entry-point">entry point</a>.</p>
<p>In other words, when someone runs the <code>require()</code> function, Node will resolve the invocation to <code>require(&lt;package.json:main&gt;)</code>.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"./src/index.js"</span>
}
</code></pre>
<h4 id="heading-private">private</h4>
<p>The <code>"private"</code> field lets package managers know whether they should publish your project to the NPM registry.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"private"</span>: <span class="hljs-literal">true</span>
}
</code></pre>
<p>If you set your package.json's <code>"private"</code> property to <code>true</code>, package managers will not publish your project.</p>
<p>Therefore, setting the property is an excellent way to prevent accidental publication of your package.</p>
<h4 id="heading-scripts">scripts</h4>
<p>The <code>"scripts"</code> field defines the script commands you want to run at various times in your project's lifecycle.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"jest"</span>,
    <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"webpack --mode development"</span>,
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"webpack --mode production"</span>,
    <span class="hljs-attr">"predeploy"</span>: <span class="hljs-string">"npm run build"</span>,
    <span class="hljs-attr">"deploy"</span>: <span class="hljs-string">"gh-pages -d build"</span> 
  }
}
</code></pre>
<p>The <code>"scripts"</code> field above contains five properties whose values are the commands we want our package manager to run whenever we invoke the property's key.</p>
<p>So, for instance, running <code>npm run dev</code> will execute the <code>"webpack --mode development"</code> command.</p>
<h4 id="heading-keywords">keywords</h4>
<p>The <code>"keywords"</code> field specifies an array of keywords that can help people discover your package.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"keywords"</span>: [
    <span class="hljs-string">"drag"</span>,
    <span class="hljs-string">"drop"</span>,
    <span class="hljs-string">"drag and drop"</span>,
    <span class="hljs-string">"dragndrop"</span>,
    <span class="hljs-string">"draggable"</span> 
  ]
}
</code></pre>
<p>The <code>"keywords"</code> property is part of the information shown when people run the <code>npm search</code> command.</p>
<h4 id="heading-author">author</h4>
<p>The <code>"author"</code> field lists a project's author's details.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">"Oluwatobi Sofela &lt;oluwatobiss@codesweetly.com&gt; (https://www.codesweetly.com)"</span>
}
</code></pre>
<p>You can also write the snippet above as:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"author"</span>: {
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Oluwatobi Sofela"</span>,
    <span class="hljs-attr">"email"</span>: <span class="hljs-string">"oluwatobiss@codesweetly.com"</span>,
    <span class="hljs-attr">"url"</span>: <span class="hljs-string">"https://www.codesweetly.com"</span>
  }
}
</code></pre>
<p>Note that the <code>"email"</code> and <code>"url"</code> properties are optional.</p>
<h4 id="heading-dependencies">dependencies</h4>
<p>The <code>"dependencies"</code> field lists all the packages a project depends on in production.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"dependencies"</span>: {
    <span class="hljs-attr">"first-package"</span>: <span class="hljs-string">"^1.0.4"</span>,
    <span class="hljs-attr">"second-package"</span>: <span class="hljs-string">"~2.1.3"</span>
  }
}
</code></pre>
<p>So, whenever a user installs your project from the NPM registry, the dependencies property ensures package managers can automatically find and install the packages listed.</p>
<p>Note that you can add a package to the <code>"dependencies"</code> field through either of the following ways:</p>
<ul>
<li>Manually add the name and the <a target="_blank" href="https://docs.npmjs.com/about-semantic-versioning">semantic version</a> of each package your project depends on in production.</li>
<li>Run the <code>npm install package-name --save-prod</code> command on your terminal. Or <code>yarn add package-name</code> if Yarn is your package manager.</li>
</ul>
<h4 id="heading-devdependencies">devDependencies</h4>
<p>The <code>"devDependencies"</code> field lists all the packages a project does not need in production—but requires for its local development and testing purposes.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"devDependencies"</span>: {
    <span class="hljs-attr">"first-dev-package"</span>: <span class="hljs-string">"^5.8.1"</span>,
    <span class="hljs-attr">"second-dev-package"</span>: <span class="hljs-string">"3.2.2—4.0.0"</span>
  }
}
</code></pre>
<p>Note that the packages listed in the <code>"devDependencies"</code> field will be available in the project's development environment but not on its production server.</p>
<p>Suppose a user installs the project through the <code>npm install</code> (or <code>yarn add</code>) command. In such a case, the package manager will find and download all the listed <code>devDependencies</code> to the project's <code>node_modules</code> directory.</p>
<p>Keep in mind that you can add a package to the <code>"devDependencies"</code> field through either of the following ways:</p>
<ul>
<li>Manually add the name and the semantic version of each package on which your project depends for its development and testing purposes.</li>
<li>Run the <code>npm install package-name --save-dev</code> command on your terminal. Or <code>yarn add package-name --dev</code> if Yarn is your package manager.</li>
</ul>
<h4 id="heading-homepage">homepage</h4>
<p>The <code>"homepage"</code> field specifies the URL to your project's homepage.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"homepage"</span>: <span class="hljs-string">"https://codesweetly.com/package-json-file-explained"</span>
}
</code></pre>
<p>So, now that we know what a <code>package.json</code> file is, we can discuss <code>package-lock.json</code>.</p>
<h2 id="heading-what-is-a-package-lockjson-file">What Is a <code>package-lock.json</code> File?</h2>
<p>The <strong>package-lock.json</strong> file is a <a target="_blank" href="https://www.codesweetly.com/document-vs-data-vs-code/#h-what-is-a-document">document</a> NPM uses to record the exact version of all the packages you've installed locally to your project's <code>node_modules</code> directory.</p>
<p>A <code>package-lock.json</code> file makes an app 100% reproducible in the exact way you published it to the NPM registry.</p>
<p>So, suppose a user clones your app and runs the <code>npm install</code> command. In such a case, <code>package-lock.json</code> ensures that the user downloads the exact version of the packages you used to develop the application.</p>
<p>For instance, let's say a user cloned your app containing <em>no</em> <code>package-lock.json</code> file, and a dependency used in the app has a newer version.</p>
<p>Suppose the dependency's version number in the <code>package.json</code> file has a caret sign (for example, <code>^2.6.2</code>). In that case, NPM will install the latest minor version of the dependency—which might cause the app to produce erroneous results.</p>
<p>However, suppose the user cloned your app containing a <code>package-lock.json</code> file. In that case, NPM will install the exact version of the dependency as recorded in the <code>package-lock.json</code> file—regardless of whether a newer version exists.</p>
<p>Therefore, users will always get your app the precise way you published it to the NPM registry.</p>
<p>In other words, NPM uses the <code>package-lock.json</code> file to lock your package's dependencies to the specific version numbers you used for the project's development.</p>
<p><strong>Note:</strong> NPM will update the packages recorded in the <code>package-lock.json</code> file whenever you run the <code>npm update</code> command.</p>
<h2 id="heading-what-is-a-yarnlock-file">What Is a <code>yarn.lock</code> File?</h2>
<p>The <code>yarn.lock</code> file is a document Yarn uses to record the exact version of all the packages you've installed locally to your project's <code>node_modules</code> directory.</p>
<p>The <code>yarn.lock</code> file is comparable to NPM's <a class="post-section-overview" href="#heading-what-is-a-package-lockjson-file">package-lock.json</a> lockfile.</p>
<p>We earlier mentioned that your package manager does not execute an installed package—you must explicitly do so yourself. Let's discuss how.</p>
<h2 id="heading-how-to-run-an-executable-package">How to Run an Executable Package</h2>
<p>There are several ways to run an executable package. Below are the standard techniques.</p>
<h3 id="heading-manually-locate-and-execute-the-package">Manually locate and execute the package</h3>
<p>One way to run an executable package is to type its local path on your command line like so:</p>
<pre><code class="lang-bash">./node_modules/.bin/package-name
</code></pre>
<h3 id="heading-add-the-package-to-the-packagejsons-scripts-field">Add the package to the package.json's <code>scripts</code> field</h3>
<p>An alternate way to execute a package is to first add it to the <code>"scripts"</code> field of your project's package.json file like this:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"your_package"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"desired-name"</span>: <span class="hljs-string">"name-of-package-to-execute"</span>
  }
}
</code></pre>
<p>Afterward, you can run the package like so:</p>
<pre><code class="lang-bash">npm run desired-name
</code></pre>
<p>Note that the command above is shorthand for <code>npm run-script desired-name</code>.</p>
<p>Alternatively, you can execute the package with Yarn like so:</p>
<pre><code class="lang-bash">yarn run desired-name
</code></pre>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"codesweetly-app"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"webpack"</span>,
  }
}
</code></pre>
<p>The snippet above added <a target="_blank" href="https://www.codesweetly.com/javascript-module-bundler/">webpack</a> to your <code>package.json</code>'s <code>"scripts"</code> field. So, we can now execute <code>webpack</code> on the command line like this:</p>
<pre><code class="lang-bash">npm run build
</code></pre>
<p>Or, if your package manager is Yarn, you can run webpack like this:</p>
<pre><code class="lang-bash">yarn run build
</code></pre>
<h3 id="heading-use-npx">Use NPX</h3>
<p>A faster way to run an executable package is to use NPX like so:</p>
<pre><code class="lang-bash">npx package-name
</code></pre>
<p>With NPX, you no longer need to add your package to the <code>"scripts"</code> field of your project's <code>package.json</code> file.</p>
<p>NPX (Node Package Execute) is a <a target="_blank" href="https://nodejs.dev/learn/the-npx-nodejs-package-runner">Node package runner</a> that automatically finds and executes a specified package.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-bash">npx webpack
</code></pre>
<p>The command above will automatically find and execute <a target="_blank" href="https://www.codesweetly.com/javascript-module-bundler/">webpack</a>. So, we do not need to add the <code>"build": "webpack"</code> property to the <code>"scripts"</code> field of our <code>package.json</code> file.</p>
<p><strong>Note:</strong> NPX automatically gets installed when you install Node 8.2/NPM 5.2.0 or higher.</p>
<p>You can also run some code using your preferred Node.js version. Let's find out how.</p>
<h2 id="heading-how-to-run-code-using-your-preferred-nodejs-version">How to Run Code Using Your Preferred Node.js Version</h2>
<p>You can use the <code>@</code> character and the <a target="_blank" href="https://www.npmjs.com/package/node">node npm package</a> to specify the Node.js version you wish to use to execute your code.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-bash">npx node@7 index.js
</code></pre>
<p>The snippet above tells NPX to run <code>index.js</code> with the latest version of Node from version 7 major.</p>
<p>Using the <code>node@</code> command is a helpful way to avoid using Node.js version management tools like <a target="_blank" href="https://github.com/nvm-sh/nvm">nvm</a> to switch between Node versions.</p>
<p>Suppose you wish to confirm the Node version NPX will use to run your code. In that case, run:</p>
<pre><code class="lang-bash">npx node@7 -v
</code></pre>
<p>The snippet above will display the latest Node version from version 7 major that NPX will use to run your code—for example, <code>v7.10.1</code>.</p>
<h2 id="heading-how-to-check-for-outdated-local-packages">How to Check for Outdated Local Packages</h2>
<p>To determine if any of your project's packages are outdated, run:</p>
<pre><code class="lang-bash">npm outdated
</code></pre>
<p>If the command outputs nothing, it means all your project's packages are up to date.</p>
<p>Otherwise, see this <a target="_blank" href="https://docs.npmjs.com/cli/v6/commands/npm-outdated">npm-outdated article</a> for a detailed explanation of the command's output.</p>
<p>Alternatively, you can use Yarn like so:</p>
<pre><code class="lang-bash">yarn outdated
</code></pre>
<p><strong>Note:</strong> To check a specific package's outdated status, add the package's name after the <code>outdated</code> keyword—for example, <code>npm outdated lodash</code>.</p>
<h2 id="heading-how-to-check-for-outdated-global-packages">How to Check for Outdated Global Packages</h2>
<p>To confirm which global package is outdated, run:</p>
<pre><code class="lang-bash">npm outdated -g --depth=0
</code></pre>
<h2 id="heading-how-to-check-for-locally-installed-packages">How to Check for Locally Installed Packages</h2>
<p>Here are three ways to check for locally installed packages:</p>
<h3 id="heading-locally-installed-packages-and-their-dependencies">Locally installed packages and their dependencies</h3>
<pre><code class="lang-bash">npm list
</code></pre>
<p>Or use Yarn like so:</p>
<pre><code class="lang-bash">yarn list
</code></pre>
<h3 id="heading-locally-installed-packageswithout-their-dependencies">Locally installed packages—without their dependencies</h3>
<pre><code class="lang-bash">npm list --depth=0
</code></pre>
<p>Or,</p>
<pre><code class="lang-bash">yarn list --depth=0
</code></pre>
<h3 id="heading-check-if-a-specific-package-got-installed-locally">Check if a specific package got installed locally</h3>
<pre><code class="lang-bash">npm list package-name
</code></pre>
<h2 id="heading-how-to-check-for-globally-installed-packages">How to Check for Globally Installed Packages</h2>
<p>Here are three ways to check for globally installed packages:</p>
<h3 id="heading-globally-installed-packages-and-their-dependencies">Globally installed packages and their dependencies</h3>
<pre><code class="lang-bash">npm list -g
</code></pre>
<p>Or use Yarn like so:</p>
<pre><code class="lang-bash">yarn list -g
</code></pre>
<h3 id="heading-globally-installed-packageswithout-their-dependencies">Globally installed packages—without their dependencies</h3>
<pre><code class="lang-bash">npm list -g --depth=0
</code></pre>
<p>Or,</p>
<pre><code class="lang-bash">yarn list -g --depth=0
</code></pre>
<h3 id="heading-check-if-a-specific-package-got-installed-globally">Check if a specific package got installed globally</h3>
<pre><code class="lang-bash">npm list -g package-name
</code></pre>
<h2 id="heading-how-to-update-packages">How to Update Packages</h2>
<p>Here's how to update packages with NPM and Yarn:</p>
<h3 id="heading-how-to-update-a-specific-package-to-its-latest-version">How to update a specific package to its latest version</h3>
<pre><code class="lang-bash">npm update package-name
</code></pre>
<p>Or, for projects managed with Yarn, run:</p>
<pre><code class="lang-bash">yarn upgrade package-name
</code></pre>
<h3 id="heading-how-to-update-all-of-a-projects-locally-installed-packages">How to update all of a project's locally installed packages</h3>
<pre><code class="lang-bash">npm update
</code></pre>
<p>Or,</p>
<pre><code class="lang-bash">yarn upgrade
</code></pre>
<h3 id="heading-how-to-update-a-specific-globally-installed-package">How to update a specific globally installed package</h3>
<p>You can update a globally installed package like this:</p>
<pre><code class="lang-bash">npm update package-name -g
</code></pre>
<h3 id="heading-how-to-update-all-your-systems-globally-installed-packages">How to update all your system's globally installed packages</h3>
<pre><code class="lang-bash">npm update -g
</code></pre>
<h2 id="heading-how-to-uninstall-packages">How to Uninstall Packages</h2>
<p>Here's how to uninstall packages with NPM and Yarn:</p>
<h3 id="heading-how-to-uninstall-a-package-from-a-specific-project">How to uninstall a package from a specific project</h3>
<p>First, navigate to the project's <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary/#h-root-directory">root directory</a> from the command line and run:</p>
<pre><code class="lang-bash">npm uninstall package-name
</code></pre>
<p><strong>Note:</strong></p>
<ul>
<li>Add the <code>-S</code> (or <code>--save</code>) flag to remove references to the package in the <code>dependencies</code> field of the project's <code>package.json</code> file.</li>
<li>Add the <code>-D</code> (or <code>--save-dev</code>) flag to remove references to the package in the <code>devDependencies</code> field of the project's <code>package.json</code> file.</li>
</ul>
<p>For projects managed with Yarn, run:</p>
<pre><code class="lang-bash">yarn remove package-name
</code></pre>
<p><strong>Note:</strong> The <code>yarn remove</code> command will automatically update the project's <code>package.json</code> and <code>yarn.lock</code> files.</p>
<h3 id="heading-how-to-uninstall-a-global-package">How to uninstall a global package</h3>
<pre><code class="lang-bash">npm uninstall package-name -g
</code></pre>
<p>Note that it is best practice not to remove packages manually from the <code>node_modules</code> folder as such action can affect other <em>modules</em> depending on it.</p>
<p>But what exactly is a module in NodeJS? Let's find out below.</p>
<h2 id="heading-what-exactly-is-a-module-in-nodejs">What Exactly Is a Module in NodeJS?</h2>
<p>A <strong>module</strong> in NodeJS is any file in the <code>node_modules</code> folder that the computer can load through Node's <code>require()</code> function.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./codesweetly.js"</span>);
</code></pre>
<p>Suppose the computer successfully used the <code>require()</code> function to load the <code>codesweetly.js</code> file. In such a case, it means <code>codesweetly.js</code> is a module—assigned to the <code>myModule</code> variable.</p>
<p>Keep in mind that a module may also be a package—but not always.</p>
<p>A module is <em>not</em> a package if it does <em>not</em> have a <code>package.json</code> file used to record information about it.</p>
<p>Also, note that for a module to be loadable by the <code>require()</code> function, the module must be one of the following:</p>
<ul>
<li>A package—whose <code>package.json</code> file contains a <code>"main"</code> field.</li>
<li>A JavaScript file.</li>
</ul>
<h2 id="heading-how-to-publish-your-project-to-the-npm-registry">How to Publish Your Project to the NPM Registry</h2>
<p>NPM is a free registry for <a target="_blank" href="https://www.npmjs.com/products">public package authors</a>.</p>
<p>So, you can use it to publish any project (folder) from your computer that has a <code>package.json</code> file.</p>
<p>Below are the steps required to share your package with the world.</p>
<h3 id="heading-step-1-sign-in-or-sign-up">Step 1: Sign in or sign up</h3>
<p>Go to the <a target="_blank" href="https://www.npmjs.com/">NPM website</a> and sign in (or sign up if you do not yet have an account).</p>
<p><strong>Note:</strong> make sure that you verify your email after creating a new account. Otherwise, you will get a <code>403 Forbidden</code> error while publishing your package.</p>
<h3 id="heading-step-2-log-in">Step 2: Log in</h3>
<p>Login to your NPM account from the command line like so:</p>
<pre><code class="lang-bash">npm login
</code></pre>
<p><strong>Note:</strong> You can use the <code>npm whoami</code> command to check if you are currently logged in.</p>
<h3 id="heading-step-3-publish-your-package">Step 3: Publish your package!</h3>
<p>Go to your project's root directory and publish it like so:</p>
<pre><code class="lang-bash">npm publish
</code></pre>
<p>Make sure that your package's name does not currently exist on NPM. Otherwise, you will get an error while publishing.</p>
<p>You can use the <code>npm search</code> command (or the <a target="_blank" href="https://www.npmjs.com/">NPM website</a>'s search bar) to search if the name you wish to use already exists on NPM.</p>
<p>Suppose all the suitable names for your package are already taken. In that case, NPM allows you to publish your project as a scope.</p>
<p>In other words, you can publish your package as a sub-section of your username. Let's see how below.</p>
<h3 id="heading-how-to-publish-your-package-as-a-scope-of-your-username">How to publish your package as a scope of your username</h3>
<p>Open your <code>package.json</code> file and prefix your package's name with your username.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"@username/package-name"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"MIT"</span>
}
</code></pre>
<p>NPM's default setting assumes that a scoped name package is a private project. So, you will get an error if you use the <code>npm publish</code> command to share a scoped name package.</p>
<p>Therefore, to publish your package as a scope of your username, add the <code>--access=public</code> flag to the <code>npm publish</code> command:</p>
<pre><code class="lang-bash">npm publish --access=public
</code></pre>
<p><strong>Note:</strong> You can make your project a scoped package during the initialization process by using the <code>npm init --scope=username</code> command instead of <code>npm init</code>.</p>
<h2 id="heading-overview">Overview</h2>
<p>This article discussed what a package manager is. We also looked at how two popular package managers (NPM and Yarn) work.</p>
<p>Thanks for reading!</p>
<h3 id="heading-and-heres-a-useful-reactjs-resource"><strong>And here's a useful ReactJS resource:</strong></h3>
<p>I wrote a book about React!</p>
<ul>
<li>It's beginners friendly ✔</li>
<li>It has live code snippets ✔</li>
<li>It contains scalable projects ✔</li>
<li>It has plenty of easy-to-grasp examples ✔</li>
</ul>
<p>The <a target="_blank" href="https://amzn.to/30iVPIG">React Explained Clearly</a> book is all you need to understand ReactJS.</p>
<p><a target="_blank" href="https://amzn.to/30iVPIG"><img src="https://www.freecodecamp.org/news/content/images/2022/01/Twitter-React_Explained_Clearly-CodeSweetly-Oluwatobi_Sofela.jpg" alt="React Explained Clearly Book Now Available at Amazon" width="600" height="400" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Temporal Dead Zone (TDZ) and Hoisting in JavaScript – Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ Temporal Dead Zone and Hoisting are two essential terms in JavaScript. But understanding how they work can easily confuse you if you don't approach them properly. But don't fret! This article is here to help you get a good grasp of the two terms. So ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-temporal-dead-zone-and-hoisting-explained/</link>
                <guid isPermaLink="false">66ba0e03f602a81788fe2186</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Mon, 24 Jan 2022 23:10:03 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/01/javascript-temporal-dead-zone-and-hoisting-explained-codesweetly-image-by-bronis-aw-dr--ka-from-pixabay.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Temporal Dead Zone and Hoisting are two essential terms in JavaScript. But understanding how they work can easily confuse you if you don't approach them properly.</p>
<p>But don't fret! This article is here to help you get a good grasp of the two terms.</p>
<p>So relax, grab your favorite cup of coffee, and let’s get started with TDZ.</p>
<h2 id="heading-what-exactly-is-a-temporal-dead-zone-in-javascript">What Exactly Is a Temporal Dead Zone in JavaScript?</h2>
<p>A <strong>temporal dead zone (TDZ)</strong> is the area of a block where a variable is inaccessible until the moment the computer completely initializes it with a value.</p>
<ul>
<li>A <a target="_blank" href="https://www.codesweetly.com/code-block/">block</a> is a pair of braces (<code>{...}</code>) used to group multiple statements.</li>
<li><a target="_blank" href="https://www.codesweetly.com/declaration-initialization-invocation-in-programming/">Initialization</a> occurs when you assign an initial value to a variable.</li>
</ul>
<p>Suppose you attempt to access a variable before its complete initialization. In such a case, JavaScript will throw a <code>ReferenceError</code>.</p>
<p>So, to prevent JavaScript from throwing such an error, you’ve got to remember to access your variables from outside the temporal dead zone.</p>
<p>But where exactly does the TDZ begin and end? Let’s find out below.</p>
<h2 id="heading-where-exactly-is-the-scope-of-a-temporal-dead-zone">Where Exactly Is the Scope of a Temporal Dead Zone?</h2>
<p>A block’s temporal dead zone starts at the beginning of the block’s local scope. It ends when the computer fully initializes your variable with a value.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js">{
  <span class="hljs-comment">// bestFood’s TDZ starts here (at the beginning of this block’s local scope)</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-built_in">console</span>.log(bestFood); <span class="hljs-comment">// returns ReferenceError because bestFood’s TDZ continues here</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-keyword">let</span> bestFood = <span class="hljs-string">"Vegetable Fried Rice"</span>; <span class="hljs-comment">// bestFood’s TDZ ends here</span>
  <span class="hljs-comment">// bestFood’s TDZ does not exist here</span>
  <span class="hljs-comment">// bestFood’s TDZ does not exist here</span>
  <span class="hljs-comment">// bestFood’s TDZ does not exist here</span>
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-sjp8hk?file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, the block’s TDZ starts from the opening curly bracket (<code>{</code>) and ends once the computer initializes <code>bestFood</code> with the string value <code>"Vegetable Fried Rice"</code>.</p>
<p>When you run the snippet, you will see that the <code>console.log()</code> statement will return a <code>ReferenceError</code>.</p>
<p>JavaScript will return a <code>ReferenceError</code> because we used the <code>console.log()</code> code to access <code>bestFood</code> before its complete initialization. In other words, we invoked <code>bestFood</code> within the temporal dead zone.</p>
<p>However, here is how you can access <code>bestFood</code> successfully after its complete initialization:</p>
<pre><code class="lang-js">{
  <span class="hljs-comment">// TDZ starts here (at the beginning of this block’s local scope)</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-keyword">let</span> bestFood = <span class="hljs-string">"Vegetable Fried Rice"</span>; <span class="hljs-comment">// bestFood’s TDZ ends here</span>
  <span class="hljs-built_in">console</span>.log(bestFood); <span class="hljs-comment">// returns "Vegetable Fried Rice" because bestFood’s TDZ does not exist here</span>
  <span class="hljs-comment">// bestFood’s TDZ does not exist here</span>
  <span class="hljs-comment">// bestFood’s TDZ does not exist here</span>
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-utknki?file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Now, consider this example:</p>
<pre><code class="lang-js">{
  <span class="hljs-comment">// TDZ starts here (at the beginning of this block’s local scope)</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-comment">// bestFood’s TDZ continues here</span>
  <span class="hljs-keyword">let</span> bestFood; <span class="hljs-comment">// bestFood’s TDZ ends here</span>
  <span class="hljs-built_in">console</span>.log(bestFood); <span class="hljs-comment">// returns undefined because bestFood’s TDZ does not exist here</span>
  bestFood = <span class="hljs-string">"Vegetable Fried Rice"</span>; <span class="hljs-comment">// bestFood’s TDZ does not exist here</span>
  <span class="hljs-built_in">console</span>.log(bestFood); <span class="hljs-comment">// returns "Vegetable Fried Rice" because bestFood’s TDZ does not exist here</span>
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-uyxf4y?file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>You can see that the first <code>console.log</code> code in the snippet above returned <code>undefined</code>.</p>
<p>JavaScript returned <code>undefined</code> because we did not assign <code>bestFood</code> a value before using (<a target="_blank" href="https://www.codesweetly.com/declaration-initialization-invocation-in-programming/#what-does-invocation-mean-in-programming">invoking</a>) it. As such, JavaScript defaulted its value to <code>undefined</code>.</p>
<p>Keep in mind that you must specify a value for a <code>const</code> variable while <a target="_blank" href="https://www.codesweetly.com/declaration-initialization-invocation-in-programming/#what-exactly-does-declaration-mean">declaring</a> it. Apart from this exception, all other temporal dead zone principles of <code>let</code> variables apply also to <code>const</code>. However, <code>var</code> works differently.</p>
<h2 id="heading-how-does-vars-tdz-differ-from-let-and-const-variables">How Does Var’s TDZ Differ from Let and Const Variables?</h2>
<p>The main difference between the temporal dead zone of a <code>var</code>, <code>let</code>, and <code>const</code> variable is when their TDZ ends.</p>
<p>For instance, consider this code:</p>
<pre><code class="lang-js">{
  <span class="hljs-comment">// bestFood’s TDZ starts and ends here</span>
  <span class="hljs-built_in">console</span>.log(bestFood); <span class="hljs-comment">// returns undefined because bestFood’s TDZ does not exist here</span>
  <span class="hljs-keyword">var</span> bestFood = <span class="hljs-string">"Vegetable Fried Rice"</span>; <span class="hljs-comment">// bestFood’s TDZ does not exist here</span>
  <span class="hljs-built_in">console</span>.log(bestFood); <span class="hljs-comment">// returns "Vegetable Fried Rice" because bestFood’s TDZ does not exist here</span>
  <span class="hljs-comment">// bestFood’s TDZ does not exist here</span>
  <span class="hljs-comment">// bestFood’s TDZ does not exist here</span>
}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-gcn7j5?file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>When you run the snippet above, you will see that the first <code>console.log</code> statement will return <code>undefined</code>.</p>
<p>The <code>console.log</code> statement successfully returned a value (<code>undefined</code>) because JavaScript automatically assigns <code>undefined</code> to a hoisted <code>var</code> variable.</p>
<p>In other words, when the computer hoists a <code>var</code> variable, it automatically initializes the variable with the value <code>undefined</code>.</p>
<p>In contrast, JavaScript does not initialize a <code>let</code> (or <code>const</code>) variable with any value whenever it hoists the variable. Instead, the variable remains dead and inaccessible.</p>
<p>Therefore, a <code>let</code> (or <code>const</code>) variable’s TDZ ends when JavaScript fully initializes it with the value specified during its declaration.</p>
<p>However, a <code>var</code> variable’s TDZ ends immediately after its hoisting—not when the variable gets fully initialized with the value specified during its declaration.</p>
<p>But what exactly does “hoisting” mean? Let’s find out below.</p>
<h2 id="heading-what-exactly-does-hoisting-mean-in-javascript">What Exactly Does Hoisting Mean in JavaScript?</h2>
<p><strong>Hoisting</strong> refers to JavaScript giving higher precedence to the declaration of variables, classes, and functions during a program’s execution.</p>
<p>Hoisting makes the computer process declarations before any other code.</p>
<p><strong>Note:</strong> Hoisting does not mean JavaScript rearranges or moves code above one another.</p>
<p>Hoisting simply gives higher specificity to JavaScript declarations. Thus, it makes the computer read and process declarations first before analyzing any other code in a program.</p>
<p>For instance, consider this snippet:</p>
<pre><code class="lang-js">{
  <span class="hljs-comment">// Declare a variable:</span>
  <span class="hljs-keyword">let</span> bestFood = <span class="hljs-string">"Fish and Chips"</span>;

  <span class="hljs-comment">// Declare another variable:</span>
  <span class="hljs-keyword">let</span> myBestMeal = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(bestFood);
    <span class="hljs-keyword">let</span> bestFood = <span class="hljs-string">"Vegetable Fried Rice"</span>;
  };

  <span class="hljs-comment">// Invoke myBestMeal function:</span>
  myBestMeal();
}

<span class="hljs-comment">// The code above will return:</span>
<span class="hljs-string">"Uncaught ReferenceError: Cannot access 'bestFood' before initialization"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/js-ymmkih?file=index.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above returned a <code>ReferenceError</code> because of the order of precedence by which the computer executed each code.</p>
<p>In other words, the program’s <a target="_blank" href="https://www.codesweetly.com/declaration-initialization-invocation-in-programming#what-exactly-does-declaration-mean">declarations</a> got higher precedence over <a target="_blank" href="https://www.codesweetly.com/declaration-initialization-invocation-in-programming#what-does-initialization-mean">initializations</a>, <a target="_blank" href="https://www.codesweetly.com/declaration-initialization-invocation-in-programming#what-does-invocation-mean-in-programming">invocations</a>, and other code.</p>
<p>Let’s go through a step-by-step tour of how JavaScript executed the snippet above.</p>
<h2 id="heading-how-javascript-hoisting-works-step-by-step">How JavaScript Hoisting Works Step-by-Step</h2>
<p>Below is a walk-through of how JavaScript executed the previous snippet.</p>
<h3 id="heading-1-javascript-parsed-the-first-bestfood-declaration">1. JavaScript parsed the first <code>bestFood</code> declaration</h3>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> bestFood <span class="hljs-comment">// This is the first bestFood declaration in the program</span>
</code></pre>
<p>The first <code>bestFood</code> variable declaration is the first code the computer analyzed.</p>
<p>Note that after the computer read the <code>bestFood</code> variable declaration, JavaScript automatically kept the variable in a <em>temporal dead zone</em> until it got fully initialized.</p>
<p>Therefore, any attempt to access <code>bestFood</code> before its complete initialization would return a <code>ReferenceError</code>.</p>
<h3 id="heading-2-the-computer-parsed-mybestmeal-variable-declaration">2. The computer parsed <code>myBestMeal</code> variable declaration</h3>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myBestMeal
</code></pre>
<p>The <code>myBestMeal</code> variable declaration was the second code JavaScript analyzed.</p>
<p>Immediately after the computer read the <code>myBestMeal</code> variable declaration, JavaScript automatically kept the variable in a temporal dead zone until it got fully initialized.</p>
<p>Therefore, any attempt to access <code>myBestMeal</code> before its complete initialization would return a <code>ReferenceError</code>.</p>
<h3 id="heading-3-the-computer-initialized-the-bestfood-variable">3. The computer initialized the <code>bestFood</code> variable</h3>
<pre><code class="lang-js">bestFood = <span class="hljs-string">"Fish and Chips"</span>;
</code></pre>
<p>The computer’s third step was to initialize <code>bestFood</code> with the <code>“Fish and Chips”</code> string value.</p>
<p>Therefore, invoking <code>bestFood</code> at this point would return <code>“Fish and Chips”</code>.</p>
<h3 id="heading-4-javascript-initialized-mybestmeal-variable">4. JavaScript initialized <code>myBestMeal</code> variable</h3>
<pre><code class="lang-js">myBestMeal = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(bestFood);
  <span class="hljs-keyword">let</span> bestFood = <span class="hljs-string">"Vegetable Fried Rice"</span>;
};
</code></pre>
<p>Fourthly, JavaScript initialized <code>myBestMeal</code> with the specified function. So, if you had invoked <code>myBestMeal</code> at this point, the function would have returned.</p>
<h3 id="heading-5-the-computer-invoked-mybestmeals-function">5. The computer invoked <code>myBestMeal</code>’s function</h3>
<pre><code class="lang-js">myBestMeal();
</code></pre>
<p>The invocation of <code>myBestMeal</code>’s function was the computer’s fifth action.</p>
<p>After the invocation, the computer processed each code in the function’s block. However, the declarations had higher precedence over other code.</p>
<h3 id="heading-6-javascript-parsed-the-functions-bestfood-declaration">6. JavaScript parsed the function’s <code>bestFood</code> declaration</h3>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> bestFood <span class="hljs-comment">// This is the second bestFood declaration in the program</span>
</code></pre>
<p>JavaScript’s sixth task was to analyze the function’s <code>bestFood</code> variable declaration.</p>
<p>After the analysis, JavaScript automatically kept the variable in a temporal dead zone—until its complete initialization.</p>
<p>Therefore, any attempt to access <code>bestFood</code> before its complete initialization would return a <code>ReferenceError</code>.</p>
<h3 id="heading-7-the-computer-parsed-the-functions-consolelog-statement">7. The computer parsed the function’s <code>console.log</code> statement</h3>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(bestFood);
</code></pre>
<p>Finally, the computer read the <code>console.log</code> statement—which instructed the system to log <code>bestFood</code>’s content to the browser’s console.</p>
<p>However, remember that the computer has not fully initialized the function’s <code>bestFood</code> variable yet. As such, the variable is currently in a temporal dead zone.</p>
<p>Therefore, the system’s attempt to access the variable returned a <code>ReferenceError</code>.</p>
<p><strong>Note:</strong> After the <code>ReferenceError</code> returned, the computer stopped reading the function’s code. Therefore, JavaScript did not initialize the function’s <code>bestFood</code> variable with <code>"Vegetable Fried Rice"</code>.</p>
<h2 id="heading-wrapping-it-up">Wrapping It Up</h2>
<p>Let’s see the previous walk-through of our program in one piece:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> bestFood <span class="hljs-comment">// 1. JavaScript parsed the first bestFood declaration</span>

<span class="hljs-keyword">let</span> myBestMeal <span class="hljs-comment">// 2. the computer parsed myBestMeal variable declaration</span>

bestFood = <span class="hljs-string">"Fish and Chips"</span>; <span class="hljs-comment">// 3. the computer initialized the bestFood variable</span>

myBestMeal = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(bestFood);
  <span class="hljs-keyword">let</span> bestFood = <span class="hljs-string">"Vegetable Fried Rice"</span>;
}; <span class="hljs-comment">// 4. JavaScript initialized myBestMeal variable</span>

myBestMeal(); <span class="hljs-comment">// 5. the computer invoked myBestMeal’s function</span>

<span class="hljs-keyword">let</span> bestFood <span class="hljs-comment">// 6. JavaScript parsed the function’s bestFood declaration</span>

<span class="hljs-built_in">console</span>.log(bestFood); <span class="hljs-comment">// 7. the computer parsed the function’s console.log statement</span>

Uncaught <span class="hljs-built_in">ReferenceError</span> <span class="hljs-comment">// bestFood’s invocation returned an Error</span>
</code></pre>
<p>You can see that JavaScript processed the program’s declarations before other code.</p>
<p>The parsing of declarations before other code in a program is what we call “hoisting”.</p>
<h2 id="heading-overview">Overview</h2>
<p>This article discussed what temporal dead zone and hoisting mean in JavaScript. We also used examples to illustrate how they both work.</p>
<p>Thanks for reading!</p>
<h3 id="heading-and-heres-a-useful-reactjs-resource"><strong>And here's a useful ReactJS resource:</strong></h3>
<p>I wrote a book about React!</p>
<ul>
<li>It's beginners friendly ✔</li>
<li>It has live code snippets ✔</li>
<li>It contains scalable projects ✔</li>
<li>It has plenty of easy-to-grasp examples ✔</li>
</ul>
<p>The <a target="_blank" href="https://amzn.to/30iVPIG">React Explained Clearly</a> book is all you need to understand ReactJS.</p>
<p><a target="_blank" href="https://amzn.to/30iVPIG"><img src="https://www.freecodecamp.org/news/content/images/2022/01/Twitter-React_Explained_Clearly-CodeSweetly-Oluwatobi_Sofela.jpg" alt="React Explained Clearly Book Now Available at Amazon" width="600" height="400" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Array vs Object Destructuring in JavaScript – What’s the Difference? ]]>
                </title>
                <description>
                    <![CDATA[ The destructuring assignment in JavaScript provides a neat and DRY way to extract values from your arrays and objects. This article aims to show you exactly how array and object destructuring assignments work in JavaScript. So, without any further ad... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/array-vs-object-destructuring-in-javascript/</link>
                <guid isPermaLink="false">66ba0ddcc2c6dd9c10038dfa</guid>
                
                    <category>
                        <![CDATA[ arrays ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Wed, 10 Nov 2021 16:24:16 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/10/extract-777603_1920-Image-by-Oscar-Castillo-from-Pixabay.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The destructuring assignment in JavaScript provides a neat and DRY way to extract values from your arrays and objects.</p>
<p>This article aims to show you exactly how array and object destructuring assignments work in JavaScript.</p>
<p>So, without any further ado, let’s get started with array destructuring.</p>
<h2 id="heading-what-is-array-destructuring">What Is Array Destructuring?</h2>
<p><strong>Array destructuring</strong> is a unique technique that allows you to neatly extract an array’s value into new variables.</p>
<p>For instance, without using the array destructuring assignment technique, you would copy an array’s value into a new variable like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> profile = [<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"codesweetly.com"</span>];

<span class="hljs-keyword">const</span> firstName = profile[<span class="hljs-number">0</span>];
<span class="hljs-keyword">const</span> lastName = profile[<span class="hljs-number">1</span>];
<span class="hljs-keyword">const</span> website = profile[<span class="hljs-number">2</span>];

<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "Oluwatobi"</span>
<span class="hljs-built_in">console</span>.log(lastName); <span class="hljs-comment">// "Sofela"</span>
<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "codesweetly.com"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-mrqjsu?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Notice that the snippet above has a lot of repeated code which is not a DRY (<strong>D</strong>on’t <strong>R</strong>epeat <strong>Y</strong>ourself) way of coding.</p>
<p>Let’s now see how array destructuring makes things neater and DRYer.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> profile = [<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"codesweetly.com"</span>];

<span class="hljs-keyword">const</span> [firstName, lastName, website] = profile;

<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "Oluwatobi"</span>
<span class="hljs-built_in">console</span>.log(lastName); <span class="hljs-comment">// "Sofela"</span>
<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "codesweetly.com"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-uxrjek?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>You see, like magic, we’ve cleaned up our code by placing the three new variables (that is, <code>firstName</code>, <code>lastName</code>, and <code>website</code>) into an array object (<code>[...]</code>). Then, we assigned them the <code>profile</code> array's values.</p>
<p>In other words, we instructed the computer to extract the <code>profile</code> array’s values into the variables on the left-hand side of the <a target="_blank" href="https://www.codesweetly.com/javascript-expression#types-of-expressions-in-javascript">assignment operator</a>.</p>
<p>Therefore, JavaScript will parse the <code>profile</code> array and copy its first value (<code>"Oluwatobi"</code>) into the destructuring array’s first variable (<code>firstName</code>).</p>
<p>Likewise, the computer will extract the <code>profile</code> array’s second value (<code>"Sofela"</code>) into the destructuring array’s second variable (<code>lastName</code>).</p>
<p>Lastly, JavaScript will copy the <code>profile</code> array’s third value (<code>"codesweetly.com"</code>) into the destructuring array’s third variable (<code>website</code>).</p>
<p>Notice that the snippet above destructured the <code>profile</code> array by referencing it. However, you can also do direct destructuring of an array. Let’s see how.</p>
<h3 id="heading-how-to-do-direct-array-destructuring">How to Do Direct Array Destructuring</h3>
<p>JavaScript lets you destructure an array directly like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [firstName, lastName, website] = [
  <span class="hljs-string">"Oluwatobi"</span>, 
  <span class="hljs-string">"Sofela"</span>, 
  <span class="hljs-string">"codesweetly.com"</span>
];

<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "Oluwatobi"</span>
<span class="hljs-built_in">console</span>.log(lastName); <span class="hljs-comment">// "Sofela"</span>
<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "codesweetly.com"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-rndtx5?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Suppose you prefer to separate your variable declarations from their assignments. In that case, JavaScript has you covered. Let’s see how.</p>
<h3 id="heading-how-to-use-array-destructuring-while-separating-variable-declarations-from-their-assignments">How to Use Array Destructuring While Separating Variable Declarations from Their Assignments</h3>
<p>Whenever you use array destructuring, JavaScript allows you to separate your variable declarations from their assignments.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> firstName, lastName, website;

[firstName, lastName, website] = [<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"codesweetly.com"</span>];

<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "Oluwatobi"</span>
<span class="hljs-built_in">console</span>.log(lastName); <span class="hljs-comment">// "Sofela"</span>
<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "codesweetly.com"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-nm1ng3?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>What if you want <code>"Oluwatobi"</code> assigned to the <code>firstName</code> variable—and the rest of the array items to another variable? How you do that? Let’s find out below.</p>
<h3 id="heading-how-to-use-array-destructuring-to-assign-the-rest-of-an-array-literal-to-a-variable">How to Use Array Destructuring to Assign the Rest of an Array Literal to a Variable</h3>
<p>JavaScript allows you to use the <a target="_blank" href="https://www.codesweetly.com/javascript-rest-operator">rest operator</a> within a destructuring array to assign the rest of a regular array to a variable.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [firstName, ...otherInfo] = [<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"codesweetly.com"</span>];

<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "Oluwatobi"</span>
<span class="hljs-built_in">console</span>.log(otherInfo); <span class="hljs-comment">// ["Sofela", "codesweetly.com"]</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-w15axc?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p><strong>Note:</strong> Always use the rest operator as the last item of your destructuring array to avoid getting a <code>SyntaxError</code>.</p>
<p>Now, what if you only want to extract <code>"codesweetly.com"</code>? Let's discuss the technique you can use below.</p>
<h3 id="heading-how-to-use-array-destructuring-to-extract-values-at-any-index">How to Use Array Destructuring to Extract Values at Any Index</h3>
<p>Here’s how you can use array destructuring to extract values at any index position of a regular array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [, , website] = [<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"codesweetly.com"</span>];

<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "codesweetly.com"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-311nkt?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we used commas to skip variables at the destructuring array's first and second index positions.</p>
<p>By so doing, we were able to link the <code>website</code> variable to the third index value of the regular array on the right side of the assignment operator (that is, <code>"codesweetly.com"</code>).</p>
<p>At times, however, the value you wish to extract from an array is <code>undefined</code>. In that case, JavaScript provides a way to set default values in the destructuring array. Let’s learn more about this below.</p>
<h3 id="heading-how-default-values-work-in-an-array-destructuring-assignment">How Default Values Work in an Array Destructuring Assignment</h3>
<p>Setting a default value can be handy when the value you wish to extract from an array does not exist (or is set to <code>undefined</code>).</p>
<p>Here’s how you can set one inside a destructuring array:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [firstName = <span class="hljs-string">"Tobi"</span>, website = <span class="hljs-string">"CodeSweetly"</span>] = [<span class="hljs-string">"Oluwatobi"</span>];

<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "Oluwatobi"</span>
<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "CodeSweetly"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-r38k67?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we set <code>"Tobi"</code> and <code>"CodeSweetly"</code> as the default values of the <code>firstName</code> and <code>website</code> variables.</p>
<p>Therefore, in our attempt to extract the first index value from the right-hand side array, the computer defaulted to <code>"CodeSweetly"</code>—because only a zeroth index value exists in <code>["Oluwatobi"]</code>.</p>
<p>So, what if you need to swap <code>firstName</code>’s value with that of <code>website</code>? Again, you can use array destructuring to get the job done. Let’s see how.</p>
<h3 id="heading-how-to-use-array-destructuring-to-swap-variables-values">How to Use Array Destructuring to Swap Variables’ Values</h3>
<p>You can use the array destructuring assignment to swap the values of two or more different variables.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> firstName = <span class="hljs-string">"Oluwatobi"</span>;
<span class="hljs-keyword">let</span> website = <span class="hljs-string">"CodeSweetly"</span>;

[firstName, website] = [website, firstName];

<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "CodeSweetly"</span>
<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "Oluwatobi"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-fu7phn?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we used direct array destructuring to reassign the <code>firstName</code> and <code>website</code> variables with the values of the array literal on the right-hand side of the assignment operator.</p>
<p>As such, <code>firstName</code>’s value will change from <code>"Oluwatobi"</code> to <code>"CodeSweetly"</code>. While <code>website</code>’s content will change from <code>"CodeSweetly"</code> to <code>"Oluwatobi"</code>.</p>
<p>Keep in mind that you can also use array destructuring to extract values from a regular array to a function’s parameters. Let’s talk more about this below.</p>
<h3 id="heading-how-to-use-array-destructuring-to-extract-values-from-an-array-to-a-functions-parameters">How to Use Array Destructuring to Extract Values from an Array to a Function’s Parameters</h3>
<p>Here’s how you can use array destructuring to extract an array’s value to a function’s parameter:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define an array with two items:</span>
<span class="hljs-keyword">const</span> profile = [<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>];

<span class="hljs-comment">// Define a function with one destructuring array containing two parameters:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserBio</span>(<span class="hljs-params">[firstName, lastName]</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`My name is <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>.`</span>;
}

<span class="hljs-comment">// Invoke getUserBio while passing the profile array as an argument:</span>
getUserBio(profile);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"My name is Oluwatobi Sofela."</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-ckdkjb?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we used an array destructuring parameter to extract the <code>profile</code> array’s values into the <code>getUserBio</code>’s <code>firstName</code> and <code>lastName</code> parameters.</p>
<p><strong>Note:</strong> An array destructuring parameter is typically called a <em>destructuring parameter</em>.</p>
<p><strong>Here’s another example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Define an array with two string values and one nested array:</span>
<span class="hljs-keyword">const</span> profile = [<span class="hljs-string">"codesweetly.com"</span>, <span class="hljs-string">"Male"</span>, [<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>]];

<span class="hljs-comment">// Define a function with two destructuring arrays containing a parameter each:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserBio</span>(<span class="hljs-params">[website, , [userName]]</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${userName}</span> runs <span class="hljs-subst">${website}</span>`</span>;
}

<span class="hljs-comment">// Invoke getUserBio while passing the profile array as an argument:</span>
getUserBio(profile);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Oluwatobi runs codesweetly.com"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-gvzqak?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we used two array destructuring parameters to extract the <code>profile</code> array’s values into the <code>getUserBio</code>’s <code>website</code> and <code>userName</code> parameters.</p>
<p>There are times you may need to invoke a function containing a destructuring parameter without passing any argument to it. In that case, you will need to use a technique that prevents the browser from throwing a <code>TypeError</code>.</p>
<p>Let’s learn about the technique below.</p>
<h3 id="heading-how-to-invoke-a-function-containing-array-destructuring-parameters-without-supplying-any-argument">How to Invoke a Function Containing Array Destructuring Parameters Without Supplying Any Argument</h3>
<p>Consider the function below:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserBio</span>(<span class="hljs-params">[firstName]</span>) </span>{
  <span class="hljs-built_in">console</span>.log(
    <span class="hljs-string">"Do something else that does not need the destructuring parameter."</span>
  );
  <span class="hljs-keyword">return</span> <span class="hljs-string">`My name is <span class="hljs-subst">${firstName}</span>.`</span>;
}
</code></pre>
<p>Now, let’s invoke the <code>getUserBio</code> function without passing any argument to its destructuring parameter:</p>
<pre><code class="lang-js">getUserBio();
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/wrong-way-to-invoke-a-function-containing-an-array-destructuring-parameter-vtdrl"><strong>Try it on CodeSandBox</strong></a></p>
<p>After invoking the <code>getUserBio</code> function above, the browser will throw an error similar to <code>TypeError: undefined is not iterable</code>.</p>
<p>The <code>TypeError</code> message happens because functions containing a destructuring parameter expect you to supply at least one argument.</p>
<p>So, you can avoid such error messages by assigning a default argument to the destructuring parameter.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserBio</span>(<span class="hljs-params">[firstName] = []</span>) </span>{
  <span class="hljs-built_in">console</span>.log(
    <span class="hljs-string">"Do something else that does not need the destructuring parameter."</span>
  );
  <span class="hljs-keyword">return</span> <span class="hljs-string">`My name is <span class="hljs-subst">${firstName}</span>.`</span>;
}
</code></pre>
<p>Notice in the snippet above that we assigned an empty array as the destructuring parameter’s default argument.</p>
<p>So, let’s now invoke the <code>getUserBio</code> function without passing any argument to its destructuring parameter:</p>
<pre><code class="lang-js">getUserBio();
</code></pre>
<p>The function will output:</p>
<pre><code class="lang-js"><span class="hljs-string">"Do something else that does not need the destructuring parameter."</span>
<span class="hljs-string">"My name is undefined."</span>
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/the-correct-way-to-invoke-a-function-containing-an-array-destructuring-parameter-voo50?file=/src/index.js"><strong>Try it on CodeSandBox</strong></a></p>
<p>Keep in mind that you do not have to use an empty array as the destructuring parameter’s default argument. You can use any other value that is not <code>null</code> or <code>undefined</code>.</p>
<p>So, now that we know how array destructuring works, let's discuss object destructuring so we can see the differences.</p>
<h2 id="heading-what-is-object-destructuring-in-javascript">What Is Object Destructuring in JavaScript?</h2>
<p><strong>Object destructuring</strong> is a unique technique that allows you to neatly extract an object’s value into new variables.</p>
<p>For instance, without using the object destructuring assignment technique, we would extract an object’s value into a new variable like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> profile = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>, 
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span>, 
  <span class="hljs-attr">website</span>: <span class="hljs-string">"codesweetly.com"</span>
};

<span class="hljs-keyword">const</span> firstName = profile.firstName;
<span class="hljs-keyword">const</span> lastName = profile.lastName;
<span class="hljs-keyword">const</span> website = profile.website;

<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "Oluwatobi"</span>
<span class="hljs-built_in">console</span>.log(lastName); <span class="hljs-comment">// "Sofela"</span>
<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "codesweetly.com"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-3tyjgy?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Notice that the snippet above has a lot of repeated code which is not a DRY (<strong>D</strong>on’t <strong>R</strong>epeat <strong>Y</strong>ourself) way of coding.</p>
<p>Let’s now see how the object destructuring assignment makes things neater and DRY.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> profile = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>, 
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span>, 
  <span class="hljs-attr">website</span>: <span class="hljs-string">"codesweetly.com"</span>
};

<span class="hljs-keyword">const</span> { <span class="hljs-attr">firstName</span>: firstName, <span class="hljs-attr">lastName</span>: lastName, <span class="hljs-attr">website</span>: website } = profile;

<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "Oluwatobi"</span>
<span class="hljs-built_in">console</span>.log(lastName); <span class="hljs-comment">// "Sofela"</span>
<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "codesweetly.com"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-begth4?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>You see, like magic, we’ve cleaned up our code by placing the three new variables into a properties object (<code>{...}</code>) and assigning them the <code>profile</code> object’s values.</p>
<p>In other words, we instructed the computer to extract the <code>profile</code> object’s values into the variables on the left-hand side of the <a target="_blank" href="https://www.codesweetly.com/javascript-expression#types-of-expressions-in-javascript">assignment operator</a>.</p>
<p>Therefore, JavaScript will parse the <code>profile</code> object and copy its first value (<code>"Oluwatobi"</code>) into the destructuring object’s first variable (<code>firstName</code>).</p>
<p>Likewise, the computer will extract the <code>profile</code> object’s second value (<code>"Sofela"</code>) into the destructuring object’s second variable (<code>lastName</code>).</p>
<p>Lastly, JavaScript will copy the <code>profile</code> object’s third value (<code>"codesweetly.com"</code>) into the destructuring object’s third variable (<code>website</code>).</p>
<p>Keep in mind that in <code>{ firstName: firstName, lastName: lastName, website: website }</code>, the keys are references to the <code>profile</code> object’s properties – while the keys’ values represent the new variables.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/11/destructuring-object-anatomy-codesweetly.png" alt="Anatomy of a JavaScript object destructuring assignment" width="600" height="400" loading="lazy">
<em>The anatomy of a JavaScript object destructuring assignment</em></p>
<p>Alternatively, you can use shorthand syntax to make your code easier to read.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> profile = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>, 
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span>, 
  <span class="hljs-attr">website</span>: <span class="hljs-string">"codesweetly.com"</span>
};

<span class="hljs-keyword">const</span> { firstName, lastName, website } = profile;

<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "Oluwatobi"</span>
<span class="hljs-built_in">console</span>.log(lastName); <span class="hljs-comment">// "Sofela"</span>
<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "codesweetly.com"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-4nhtlt?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we shortened <code>{ firstName: firstName, age: age, gender: gender }</code> to <code>{ firstName, age, gender }</code>. You can learn more about the shorthand technique <a target="_blank" href="https://alligator.io/js/object-property-shorthand-es6/">here</a>.</p>
<p>Observe that the snippets above illustrated how to assign an object’s value to a variable when both the object’s property and the variable have the same name.</p>
<p>However, you can also assign a property’s value to a variable of a different name. Let’s see how.</p>
<h3 id="heading-how-to-use-object-destructuring-when-the-propertys-name-differs-from-that-of-the-variable">How to Use Object Destructuring When the Property’s Name Differs from That of the Variable</h3>
<p>JavaScript permits you to use object destructuring to extract a property’s value into a variable even if both the property and the variable’s names are different.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> profile = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>, 
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span>, 
  <span class="hljs-attr">website</span>: <span class="hljs-string">"codesweetly.com"</span>
};

<span class="hljs-keyword">const</span> { <span class="hljs-attr">firstName</span>: forename, <span class="hljs-attr">lastName</span>: surname, <span class="hljs-attr">website</span>: onlineSite } = profile;

<span class="hljs-built_in">console</span>.log(forename); <span class="hljs-comment">// "Oluwatobi"</span>
<span class="hljs-built_in">console</span>.log(surname); <span class="hljs-comment">// "Sofela"</span>
<span class="hljs-built_in">console</span>.log(onlineSite); <span class="hljs-comment">// "codesweetly.com"</span>
<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "ReferenceError: website is not defined"</span>
</code></pre>
<p><strong><a target="_blank" href="https://codesandbox.io/s/how-to-use-object-destructuring-when-the-propertys-name-differs-from-that-of-the-variable-ppohh?file=/src/index.js">Try it on CodeSandBox</a></strong></p>
<p>In the snippet above, the computer successfully extracted the <code>profile</code> object’s values into the variables named <code>forename</code>, <code>surname</code>, and <code>onlineSite</code>—even though the properties and variables are of different names.</p>
<p><strong>Note:</strong> <code>const { firstName: forename } = profile</code> is equivalent to <code>const forename = profile.firstName</code>.</p>
<p><strong>Here’s another example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> profile = {
  <span class="hljs-attr">lastName</span>: { <span class="hljs-attr">familyName</span>: <span class="hljs-string">"Sofela"</span> }
};

<span class="hljs-keyword">const</span> { <span class="hljs-attr">lastName</span>: { <span class="hljs-attr">familyName</span>: surname } } = profile;

<span class="hljs-built_in">console</span>.log(surname); <span class="hljs-comment">// "Sofela"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-nbnqcl?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, the computer successfully extracted the <code>profile</code> object’s value into the <code>surname</code> variable—even though the property and variable are of different names.</p>
<p><strong>Note:</strong> <code>const { lastName: { familyName: surname } } = profile</code> is equivalent to <code>const surname = profile.lastName.familyName</code>.</p>
<p>Notice that so far, we’ve destructured the <code>profile</code> object by referencing it. However, you can also do direct destructuring of an object. Let’s see how.</p>
<h3 id="heading-how-to-do-direct-object-destructuring">How to Do Direct Object Destructuring</h3>
<p>JavaScript permits direct destructuring of a properties object like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { firstName, lastName, website } = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>, 
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span>, 
  <span class="hljs-attr">website</span>: <span class="hljs-string">"codesweetly.com"</span>
};

<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "Oluwatobi"</span>
<span class="hljs-built_in">console</span>.log(lastName); <span class="hljs-comment">// "Sofela"</span>
<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "codesweetly.com"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-vspaeg?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Suppose you prefer to separate your variable declarations from their assignments. In that case, JavaScript has you covered. Let see how.</p>
<h3 id="heading-how-to-use-object-destructuring-while-separating-variable-declarations-from-their-assignments">How to Use Object Destructuring While Separating Variable Declarations from Their Assignments</h3>
<p>Whenever you use object destructuring, JavaScript allows you to separate your variable declarations from their assignments.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Declare three variables:</span>
<span class="hljs-keyword">let</span> firstName, lastName, website;

<span class="hljs-comment">// Extract values to the three variables above:</span>
({ firstName, lastName, website } = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>, 
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span>, 
  <span class="hljs-attr">website</span>: <span class="hljs-string">"codesweetly.com"</span>
});

<span class="hljs-comment">// Invoke the three variables:</span>
<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "Oluwatobi"</span>
<span class="hljs-built_in">console</span>.log(lastName); <span class="hljs-comment">// "Sofela"</span>
<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "codesweetly.com"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-3fmanq?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p><strong>Note:</strong></p>
<ul>
<li>Make sure that you encase the object destructuring assignment in parentheses. By so doing, the computer will know that the object destructuring is an object literal, not a block.</li>
<li>Place a semicolon (<code>;</code>) after the parentheses of an object destructuring assignment. By doing so, you will prevent the computer from interpreting the parentheses as an invocator of a function that may be on the previous line.</li>
</ul>
<p>What if you want <code>"Oluwatobi"</code> assigned to the <code>firstName</code> variable—and the rest of the object’s values to another variable? How can you do this? Let’s find out below.</p>
<h3 id="heading-how-to-use-object-destructuring-to-assign-the-rest-of-an-object-to-a-variable">How to Use Object Destructuring to Assign the Rest of an Object to a Variable</h3>
<p>JavaScript allows you to use the <a target="_blank" href="https://www.codesweetly.com/javascript-rest-operator/">rest operator</a> within a destructuring object to assign the rest of an object literal to a variable.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { firstName, ...otherInfo } = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>,
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span>,
  <span class="hljs-attr">website</span>: <span class="hljs-string">"codesweetly.com"</span>
};

<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "Oluwatobi"</span>
<span class="hljs-built_in">console</span>.log(otherInfo); <span class="hljs-comment">// {lastName: "Sofela", website: "codesweetly.com"}</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-hksus5?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p><strong>Note:</strong> Always use the rest operator as the last item of your destructuring object to avoid getting a <code>SyntaxError</code>.</p>
<p>At times, the value you wish to extract from a properties object is <code>undefined</code>. In that case, JavaScript provides a way to set default values in the destructuring object. Let’s learn more about this below.</p>
<h3 id="heading-how-default-values-work-in-an-object-destructuring-assignment">How Default Values Work in an Object Destructuring Assignment</h3>
<p>Setting a default value can be handy when the value you wish to extract from an object does not exist (or is set to <code>undefined</code>).</p>
<p>Here’s how you can set one inside a destructuring properties object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { firstName = <span class="hljs-string">"Tobi"</span>, website = <span class="hljs-string">"CodeSweetly"</span> } = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>
};

<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "Oluwatobi"</span>
<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "CodeSweetly"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-pnjh9a?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we set <code>"Tobi"</code> and <code>"CodeSweetly"</code> as the default values of the <code>firstName</code> and <code>website</code> variables.</p>
<p>Therefore, in our attempt to extract the second property’s value from the right-hand side object, the computer defaulted to <code>"CodeSweetly"</code>—because only a single property exists in <code>{firstName: "Oluwatobi"}</code>.</p>
<p>So, what if you need to swap <code>firstName</code>’s value with that of <code>website</code>? Again, you can use object destructuring to get the job done. Let’s see how below.</p>
<h3 id="heading-how-to-use-object-destructuring-to-swap-values">How to Use Object Destructuring to Swap Values</h3>
<p>You can use the object destructuring assignment to swap the values of two or more different variables.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> firstName = <span class="hljs-string">"Oluwatobi"</span>;
<span class="hljs-keyword">let</span> website = <span class="hljs-string">"CodeSweetly"</span>;

({ firstName, website } = {<span class="hljs-attr">firstName</span>: website, <span class="hljs-attr">website</span>: firstName});

<span class="hljs-built_in">console</span>.log(firstName); <span class="hljs-comment">// "CodeSweetly"</span>
<span class="hljs-built_in">console</span>.log(website); <span class="hljs-comment">// "Oluwatobi"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-fmyerw?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used direct object destructuring to reassign the <code>firstName</code> and <code>website</code> variables with the values of the object literal on the right-hand side of the assignment operator.</p>
<p>As such, <code>firstName</code>’s value will change from <code>"Oluwatobi"</code> to <code>"CodeSweetly"</code>. While <code>website</code>’s content will change from <code>"CodeSweetly"</code> to <code>"Oluwatobi"</code>.</p>
<p>Keep in mind that you can also use object destructuring to extract values from properties to a function’s parameters. Let’s talk more about this below.</p>
<h3 id="heading-how-to-use-object-destructuring-to-extract-values-from-properties-to-a-functions-parameters">How to Use Object Destructuring to Extract Values from Properties to a Function’s Parameters</h3>
<p>Here’s how you can use object destructuring to copy a property’s value to a function’s parameter:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define an object with two properties:</span>
<span class="hljs-keyword">const</span> profile = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>,
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span>,
};

<span class="hljs-comment">// Define a function with one destructuring object containing two parameters:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserBio</span>(<span class="hljs-params">{ firstName, lastName }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`My name is <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>.`</span>;
}

<span class="hljs-comment">// Invoke getUserBio while passing the profile object as an argument:</span>
getUserBio(profile);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"My name is Oluwatobi Sofela."</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-aucght?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we used an object destructuring parameter to copy the <code>profile</code> object’s values into <code>getUserBio</code>’s <code>firstName</code> and <code>lastName</code> parameters.</p>
<p><strong>Note:</strong> An object destructuring parameter is typically called a <em>destructuring parameter</em>.</p>
<p><strong>Here’s another example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Define an object with three-parent properties:</span>
<span class="hljs-keyword">const</span> profile = {
  <span class="hljs-attr">website</span>: <span class="hljs-string">"codesweetly.com"</span>,
  <span class="hljs-attr">gender</span>: <span class="hljs-string">"Male"</span>,
  <span class="hljs-attr">fullName</span>: {
    <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>,
    <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span>
  }
};

<span class="hljs-comment">// Define a function with two destructuring objects containing a parameter each:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserBio</span>(<span class="hljs-params">{ website, fullName: { firstName: userName } }</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${userName}</span> runs <span class="hljs-subst">${website}</span>`</span>;
}

<span class="hljs-comment">// Invoke getUserBio while passing the profile object as an argument:</span>
getUserBio(profile);

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-string">"Oluwatobi runs codesweetly.com"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-g2n2a6?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we used two destructuring parameters to copy the <code>profile</code> object’s values into <code>getUserBio</code>’s <code>website</code> and <code>userName</code> parameters.</p>
<p><strong>Note:</strong> If you are unclear about the destructuring parameter above, you may grasp it better by reviewing <a class="post-section-overview" href="#heading-how-to-use-object-destructuring-when-the-propertys-name-differs-from-that-of-the-variable">this section</a>.</p>
<p>There are times you may need to invoke a function containing a destructuring parameter without passing any argument to it. In that case, you will need to use a technique that prevents the browser from throwing a <code>TypeError</code>.</p>
<p>Let’s learn about the technique below.</p>
<h3 id="heading-how-to-invoke-a-function-containing-destructured-parameters-without-supplying-any-argument">How to Invoke a Function Containing Destructured Parameters Without Supplying Any Argument</h3>
<p>Consider the function below:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserBio</span>(<span class="hljs-params">{ firstName }</span>) </span>{
  <span class="hljs-built_in">console</span>.log(
    <span class="hljs-string">"Do something else that does not need the destructuring parameter."</span>
  );
  <span class="hljs-keyword">return</span> <span class="hljs-string">`My name is <span class="hljs-subst">${firstName}</span>.`</span>;
}
</code></pre>
<p>Now, let’s invoke the <code>getUserBio</code> function without passing any argument to its destructuring parameter:</p>
<pre><code class="lang-js">getUserBio();
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/wrong-way-to-invoke-a-function-containing-an-object-destructuring-parameter-c1hdx?file=/src/index.js"><strong>Try it on CodeSandBox</strong></a></p>
<p>After invoking the <code>getUserBio</code> function above, the browser will throw an error similar to <code>TypeError: (destructured parameter) is undefined</code>.</p>
<p>The <code>TypeError</code> message happens because functions containing a destructuring parameter expect you to supply at least one argument.</p>
<p>So, you can avoid such error messages by assigning a default argument to the destructuring parameter.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserBio</span>(<span class="hljs-params">{ firstName } = {}</span>) </span>{
  <span class="hljs-built_in">console</span>.log(
    <span class="hljs-string">"Do something else that does not need the destructuring parameter."</span>
  );
  <span class="hljs-keyword">return</span> <span class="hljs-string">`My name is <span class="hljs-subst">${firstName}</span>.`</span>;
}
</code></pre>
<p>Notice that in the snippet above, we assigned an empty object as the destructuring parameter’s default argument.</p>
<p>So, let’s now invoke the <code>getUserBio</code> function without passing any argument to its destructuring parameter:</p>
<pre><code class="lang-js">getUserBio();
</code></pre>
<p>The function will output:</p>
<pre><code class="lang-js"><span class="hljs-string">"Do something else that does not need the destructuring parameter."</span>
<span class="hljs-string">"My name is undefined."</span>
</code></pre>
<p><strong><a target="_blank" href="https://codesandbox.io/s/the-correct-way-to-invoke-a-function-containing-an-object-destructuring-parameter-7kvum?file=/src/index.js">Try it on CodeSandBox</a></strong></p>
<p>Keep in mind that you do not have to use an empty object as the destructuring parameter’s default argument. You can use any other value that is not <code>null</code> or <code>undefined</code>.</p>
<h2 id="heading-wrapping-it-up">Wrapping It Up</h2>
<p>Array and object destructuring work similarly. The main difference between the two destructuring assignments is this:</p>
<ul>
<li>Array destructuring extracts values from an array. But object destructuring extracts values from a JavaScript object.</li>
</ul>
<h2 id="heading-overview">Overview</h2>
<p>This article discussed how array and object destructuring works in JavaScript. We also looked at the main difference between the two destructuring assignments.</p>
<p>Thanks for reading!</p>
<h3 id="heading-and-heres-a-useful-reactjs-resource">And here's a useful ReactJS resource:</h3>
<p>I wrote a book about React! </p>
<ul>
<li>It's beginner’s friendly ✔</li>
<li>It has live code snippets ✔</li>
<li>It contains scalable projects ✔</li>
<li>It has plenty of easy-to-grasp examples ✔</li>
</ul>
<p>The <a target="_blank" href="https://amzn.to/30iVPIG">React Explained Clearly</a> book is all you need to understand ReactJS.</p>
<p><a target="_blank" href="https://amzn.to/30iVPIG">Click Here to Get Your Copy</a></p>
<p><a target="_blank" href="https://amzn.to/30iVPIG"><img src="https://www.freecodecamp.org/news/content/images/2021/11/Twitter-React_Explained_Clearly-CodeSweetly-Oluwatobi_Sofela-1.jpg" alt="React Explained Clearly Book Now Available at Amazon" width="600" height="400" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Rest vs Spread Operator – What’s the Difference? ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript uses three dots (...) for both the rest and spread operators. But these two operators are not the same. The main difference between rest and spread is that the rest operator puts the rest of some specific user-supplied values into a JavaSc... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-rest-vs-spread-operators/</link>
                <guid isPermaLink="false">66ba0e00da6e5d90e89ee186</guid>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Wed, 15 Sep 2021 22:27:26 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/09/javascript-rest-vs-spread-operators-codesweetly-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript uses three dots (<code>...</code>) for both the rest and spread operators. But these two operators are not the same.</p>
<p>The main difference between rest and spread is that the rest operator puts the rest of some specific user-supplied values into a JavaScript array. But the spread syntax expands iterables into individual elements.</p>
<p>For instance, consider this code that uses rest to enclose some values into an array:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Use rest to enclose the rest of specific user-supplied values into an array:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myBio</span>(<span class="hljs-params">firstName, lastName, ...otherInfo</span>) </span>{ 
  <span class="hljs-keyword">return</span> otherInfo;
}

<span class="hljs-comment">// Invoke myBio function while passing five arguments to its parameters:</span>
myBio(<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"CodeSweetly"</span>, <span class="hljs-string">"Web Developer"</span>, <span class="hljs-string">"Male"</span>);

<span class="hljs-comment">// The invocation above will return:</span>
[<span class="hljs-string">"CodeSweetly"</span>, <span class="hljs-string">"Web Developer"</span>, <span class="hljs-string">"Male"</span>]
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-t3kcyw?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we used the <code>...otherInfo</code> rest parameter to put <code>"CodeSweetly"</code>, <code>"Web Developer"</code>, and <code>"Male"</code> into an array.</p>
<p>Now, consider this example of a spread operator:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function with three parameters:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myBio</span>(<span class="hljs-params">firstName, lastName, company</span>) </span>{ 
  <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span> runs <span class="hljs-subst">${company}</span>`</span>;
}

<span class="hljs-comment">// Use spread to expand an array’s items into individual arguments:</span>
myBio(...[<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"CodeSweetly"</span>]);

<span class="hljs-comment">// The invocation above will return:</span>
“Oluwatobi Sofela runs CodeSweetly”
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-ppjslx?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we used the spread operator (<code>...</code>) to spread <code>["Oluwatobi", "Sofela", "CodeSweetly"]</code>’s content across <code>myBio()</code>’s parameters.</p>
<p>Don’t worry if you don’t understand the rest or spread operators yet. This article has got you covered!</p>
<p>In the following sections, we will discuss how rest and spread work in JavaScript.</p>
<p>So, without any further ado, let’s get started with the rest operator.</p>
<h2 id="heading-what-exactly-is-the-rest-operator">What Exactly Is the Rest Operator?</h2>
<p>The <strong>rest operator</strong> is used to put the rest of some specific user-supplied values into a JavaScript array.</p>
<p>So, for instance, here is the rest syntax:</p>
<pre><code class="lang-js">...yourValues
</code></pre>
<p>The three dots (<code>...</code>) in the snippet above symbolize the rest operator.</p>
<p>The text after the rest operator references the values you wish to encase inside an array. You can only use it before the last parameter in a function definition.</p>
<p>To understand the syntax better, let’s see how rest works with JavaScript functions.</p>
<h3 id="heading-how-does-the-rest-operator-work-in-a-function">How Does the Rest Operator Work in a Function?</h3>
<p>In JavaScript functions, rest gets used as a prefix of the function’s last parameter.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function with two regular parameters and one rest parameter:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myBio</span>(<span class="hljs-params">firstName, lastName, ...otherInfo</span>) </span>{ 
  <span class="hljs-keyword">return</span> otherInfo;
}
</code></pre>
<p>The rest operator (<code>...</code>) instructs the computer to add whatever <code>otherInfo</code> (arguments) supplied by the user into an array. Then, assign that array to the <code>otherInfo</code> parameter.</p>
<p>As such, we call <code>...otherInfo</code> a rest parameter.</p>
<p><strong>Note:</strong> <a target="_blank" href="https://www.codesweetly.com/javascript-arguments">Arguments</a> are optional values you may pass to a function’s parameter through an invocator.</p>
<p><strong>Here’s another example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function with two regular parameters and one rest parameter:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myBio</span>(<span class="hljs-params">firstName, lastName, ...otherInfo</span>) </span>{ 
  <span class="hljs-keyword">return</span> otherInfo;
}

<span class="hljs-comment">// Invoke myBio function while passing five arguments to its parameters:</span>
myBio(<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"CodeSweetly"</span>, <span class="hljs-string">"Web Developer"</span>, <span class="hljs-string">"Male"</span>);

<span class="hljs-comment">// The invocation above will return:</span>
[<span class="hljs-string">"CodeSweetly"</span>, <span class="hljs-string">"Web Developer"</span>, <span class="hljs-string">"Male"</span>]
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-t3kcyw?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, notice that <code>myBio</code>’s invocation passed five arguments to the function.</p>
<p>In other words, <code>"Oluwatobi"</code> and <code>"Sofela"</code> got assigned to the <code>firstName</code> and <code>lastName</code> parameters.</p>
<p>At the same time, the rest operator added the remaining arguments ( <code>"CodeSweetly"</code>, <code>"Web Developer"</code>, and <code>"Male"</code>) into an array and assigned that array to the <code>otherInfo</code> parameter.</p>
<p>Therefore, <code>myBio()</code> function correctly returned <code>["CodeSweetly", "Web Developer", "Male"]</code> as the content of the <code>otherInfo</code> rest parameter.</p>
<h3 id="heading-beware-you-cannot-use-use-strict-inside-a-function-containing-a-rest-parameter">Beware! You Cannot Use <code>“use strict”</code> Inside a Function Containing a Rest Parameter</h3>
<p>Keep in mind that you <em>cannot</em> use the <code>“use strict”</code> directive inside any function containing a rest parameter, default parameter, or <a target="_blank" href="https://www.codesweetly.com/destructuring-object#how-to-use-a-destructuring-object-to-copy-values-from-properties-to-a-functions-parameters">destructuring parameter</a>. Otherwise, the computer will throw a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Strict_Non_Simple_Params">syntax error</a>.</p>
<p>For instance, consider this example below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a function with one rest parameter:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printMyName</span>(<span class="hljs-params">...value</span>) </span>{
<span class="hljs-meta">  "use strict"</span>;
  <span class="hljs-keyword">return</span> value;
}

<span class="hljs-comment">// The definition above will return:</span>
<span class="hljs-string">"Uncaught SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list"</span>
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/you-cannot-use-use-strict-inside-a-function-containing-a-spread-parameter-cvis3"><strong>Try it on CodeSandbox</strong></a></p>
<p><code>printMyName()</code> returned a syntax error because we used the <code>“use strict”</code> directive inside a function with a rest parameter.</p>
<p>But suppose you need your function to be in strict mode while also using the rest parameter. In such a case, you can write the <code>“use strict”</code> directive outside the function.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a “use strict” directive outside your function:</span>
<span class="hljs-meta">"use strict"</span>;

<span class="hljs-comment">// Define a function with one rest parameter:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printMyName</span>(<span class="hljs-params">...value</span>) </span>{
  <span class="hljs-keyword">return</span> value;
}

<span class="hljs-comment">// Invoke the printMyName function while passing two arguments to its parameters:</span>
printMyName(<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>);

<span class="hljs-comment">// The invocation above will return:</span>
[<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>]
</code></pre>
<p><a target="_blank" href="https://codesandbox.io/s/you-can-use-use-strict-outside-a-function-containing-a-spread-parameter-spbmh"><strong>Try it on CodeSandbox</strong></a></p>
<p><strong>Note:</strong> Only place the <code>“use strict”</code> directive outside your function if it is okay for the entire script or <a target="_blank" href="https://www.codesweetly.com/javascript-lexical-scope">enclosing scope</a> to be in strict mode.</p>
<p>So now that we know how rest works in a function, we can talk about how it works in a <a target="_blank" href="https://www.codesweetly.com/destructuring-array">destructuring assignment</a>.</p>
<h3 id="heading-how-the-rest-operator-works-in-a-destructuring-assignment">How the Rest Operator Works in a Destructuring Assignment</h3>
<p>The rest operator typically gets used as a prefix of the destructuring assignment’s last variable.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a destructuring array with two regular variables and one rest variable:</span>
<span class="hljs-keyword">const</span> [firstName, lastName, ...otherInfo] = [
  <span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"CodeSweetly"</span>, <span class="hljs-string">"Web Developer"</span>, <span class="hljs-string">"Male"</span>
];

<span class="hljs-comment">// Invoke the otherInfo variable:</span>
<span class="hljs-built_in">console</span>.log(otherInfo); 

<span class="hljs-comment">// The invocation above will return:</span>
[<span class="hljs-string">"CodeSweetly"</span>, <span class="hljs-string">"Web Developer"</span>, <span class="hljs-string">"Male"</span>]
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-tckdt8?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The rest operator (<code>...</code>) instructs the computer to add the rest of the user-supplied values into an array. Then, it assigns that array to the <code>otherInfo</code> variable.</p>
<p>As such, you may call <code>...otherInfo</code> a rest variable.</p>
<p><strong>Here’s another example:</strong></p>
<pre><code class="lang-js"><span class="hljs-comment">// Define a destructuring object with two regular variables and one rest variable:</span>
<span class="hljs-keyword">const</span> { firstName, lastName, ...otherInfo } = {
  <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>,
  <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span>, 
  <span class="hljs-attr">companyName</span>: <span class="hljs-string">"CodeSweetly"</span>,
  <span class="hljs-attr">profession</span>: <span class="hljs-string">"Web Developer"</span>,
  <span class="hljs-attr">gender</span>: <span class="hljs-string">"Male"</span>
}

<span class="hljs-comment">// Invoke the otherInfo variable:</span>
<span class="hljs-built_in">console</span>.log(otherInfo);

<span class="hljs-comment">// The invocation above will return:</span>
{<span class="hljs-attr">companyName</span>: <span class="hljs-string">"CodeSweetly"</span>, <span class="hljs-attr">profession</span>: <span class="hljs-string">"Web Developer"</span>, <span class="hljs-attr">gender</span>: <span class="hljs-string">"Male"</span>}
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-fmr3dr?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, notice that the rest operator assigned a properties object — not an array — to the <code>otherInfo</code> variable.</p>
<p>In other words, whenever you use rest in a <a target="_blank" href="https://www.codesweetly.com/destructuring-object">destructuring object</a>, the rest operator will produce a properties object.</p>
<p>However, if you use rest in a <a target="_blank" href="https://www.codesweetly.com/destructuring-array">destructuring array</a> or function, the operator will yield an array literal.</p>
<p>Before we wrap up our discussion on rest, you should be aware of some differences between JavaScript <a target="_blank" href="https://www.codesweetly.com/javascript-arguments">arguments</a> and the rest parameter. So, let’s talk about that below.</p>
<h3 id="heading-arguments-vs-rest-parameters-whats-the-difference">Arguments vs Rest Parameters: What’s the Difference?</h3>
<p>Here are some of the differences between JavaScript arguments and the rest parameter:</p>
<h4 id="heading-difference-1-the-arguments-object-is-an-array-like-object-not-a-real-array">Difference 1: The <code>arguments</code> object is an array-like object — not a real array!</h4>
<p>Keep in mind that the JavaScript arguments object is not a real array. Instead, it is an <a target="_blank" href="https://www.codesweetly.com/javascript-arguments#what-is-an-arraylike-object">array-like</a> object that does not have the comprehensive features of a regular JavaScript array.</p>
<p>The rest parameter, however, is a real array object. As such, you can use all array methods on it.</p>
<p>So for instance, you can call the <code>sort()</code>, <code>map()</code>, <code>forEach()</code>, or <code>pop()</code> method on a rest parameter. But you cannot do the same on the arguments object.</p>
<h4 id="heading-difference-2-you-cannot-use-the-arguments-object-in-an-arrow-function">Difference 2: You cannot use the <code>arguments</code> object in an arrow function</h4>
<p>The <code>arguments</code> object is not available within an arrow function, so you can’t use it there. But you can use the rest parameter within all functions — including the arrow function.</p>
<h4 id="heading-difference-3-let-rest-be-your-preference">Difference 3: Let rest be your preference</h4>
<p>It is best to use rest parameters instead of the <code>arguments</code> object — especially while writing ES6 compatible code.</p>
<p>Now that we know how rest works, let's discuss the <code>spread</code> operator so we can see the differences.</p>
<h2 id="heading-what-is-the-spread-operator-and-how-does-spread-work-in-javascript">What Is the Spread Operator and How Does <code>spread</code> work in JavaScript?</h2>
<p>The <strong>spread operator</strong> (<code>...</code>) helps you expand iterables into individual elements.</p>
<p>The spread syntax works within array literals, function calls, and initialized property objects to spread the values of <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterables">iterable objects</a> into separate items. So effectively, it does the opposite thing from the rest operator.</p>
<p><strong>Note:</strong> A spread operator is effective only when used within array literals, function calls, or initialized properties objects.</p>
<p>So, what exactly does this mean? Let’s see with some examples.</p>
<h3 id="heading-spread-example-1-how-spread-works-in-an-array-literal">Spread Example 1: How Spread Works in an Array Literal</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myName = [<span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"is"</span>, <span class="hljs-string">"my"</span>];
<span class="hljs-keyword">const</span> aboutMe = [<span class="hljs-string">"Oluwatobi"</span>, ...myName, <span class="hljs-string">"name."</span>];

<span class="hljs-built_in">console</span>.log(aboutMe);

<span class="hljs-comment">// The invocation above will return:</span>
[ <span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"is"</span>, <span class="hljs-string">"my"</span>, <span class="hljs-string">"name."</span> ]
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-rd1npd?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used spread (<code>...</code>) to copy the <code>myName</code> array into <code>aboutMe</code>.</p>
<p><strong>Note:</strong></p>
<ul>
<li>Alterations to <code>myName</code> will not reflect in <code>aboutMe</code> because all the values inside <code>myName</code> are <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary#primitive-data-js">primitives</a>. Therefore, the spread operator simply copied and pasted <code>myName</code>’s content into <code>aboutMe</code> without creating any reference back to the original array.</li>
<li>As mentioned by <a target="_blank" href="https://dev.to/oluwatobiss/spread-operator-how-spread-works-in-javascript-4fdn#comment-node-767546">@nombrekeff</a> in a comment <a target="_blank" href="https://dev.to/oluwatobiss/spread-operator-how-spread-works-in-javascript-4fdn">here</a>, the spread operator only does shallow copy. So, keep in mind that supposing <code>myName</code> contained any <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary#non-primitive-data-js">non-primitive</a> value, the computer would have created a reference between <code>myName</code> and <code>aboutMe</code>. See <a class="post-section-overview" href="#heading-info-3-beware-of-how-spread-works-when-used-on-objects-containing-non-primitives">info 3</a> for more on how the spread operator works with primitive and non-primitive values.</li>
<li>Suppose we did not use the spread syntax to duplicate <code>myName</code>’s content. For instance, if we had written <code>const aboutMe = ["Oluwatobi", myName, "name."]</code>. In such a case, the computer would have assigned a reference back to <code>myName</code>. As such, any change made in the original array would reflect in the duplicated one.</li>
</ul>
<h3 id="heading-spread-example-2-how-to-use-spread-to-convert-a-string-into-individual-array-items">Spread Example 2: How to Use Spread to Convert a String into Individual Array Items</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myName = <span class="hljs-string">"Oluwatobi Sofela"</span>;

<span class="hljs-built_in">console</span>.log([...myName]);

<span class="hljs-comment">// The invocation above will return:</span>
[ <span class="hljs-string">"O"</span>, <span class="hljs-string">"l"</span>, <span class="hljs-string">"u"</span>, <span class="hljs-string">"w"</span>, <span class="hljs-string">"a"</span>, <span class="hljs-string">"t"</span>, <span class="hljs-string">"o"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"i"</span>, <span class="hljs-string">" "</span>, <span class="hljs-string">"S"</span>, <span class="hljs-string">"o"</span>, <span class="hljs-string">"f"</span>, <span class="hljs-string">"e"</span>, <span class="hljs-string">"l"</span>, <span class="hljs-string">"a"</span> ]
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-axvtye?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we used the spread syntax (<code>...</code>) within an array literal object (<code>[...]</code>) to expand <code>myName</code>’s string value into individual items.</p>
<p>As such, <code>"Oluwatobi Sofela"</code> got expanded into <code>[ "O", "l", "u", "w", "a", "t", "o", "b", "i", " ", "S", "o", "f", "e", "l", "a" ]</code>.</p>
<h3 id="heading-spread-example-3-how-the-spread-operator-works-in-a-function-call">Spread Example 3: How the Spread Operator Works in a Function Call</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">a, b, c, d</span>) </span>{
  <span class="hljs-keyword">return</span> a + b + c + d;
}

<span class="hljs-built_in">console</span>.log(addNumbers(...numbers));

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-number">16</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-nrn8f3?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we used the spread syntax to spread the <code>numbers</code> array’s content across <code>addNumbers()</code>’s parameters.</p>
<p>Suppose the <code>numbers</code> array had more than four items. In such a case, the computer will only use the first four items as <code>addNumbers()</code> argument and ignore the rest.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">10</span>, <span class="hljs-number">200</span>, <span class="hljs-number">90</span>, <span class="hljs-number">59</span>];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">a, b, c, d</span>) </span>{
  <span class="hljs-keyword">return</span> a + b + c + d;
}

<span class="hljs-built_in">console</span>.log(addNumbers(...numbers));

<span class="hljs-comment">// The invocation above will return:</span>
<span class="hljs-number">16</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-ef3ncm?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p><strong>Here’s another example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myName = <span class="hljs-string">"Oluwatobi Sofela"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">spellName</span>(<span class="hljs-params">a, b, c</span>) </span>{
  <span class="hljs-keyword">return</span> a + b + c;
}

<span class="hljs-built_in">console</span>.log(spellName(...myName));      <span class="hljs-comment">// returns: "Olu"</span>

<span class="hljs-built_in">console</span>.log(spellName(...myName[<span class="hljs-number">3</span>]));   <span class="hljs-comment">// returns: "wundefinedundefined"</span>

<span class="hljs-built_in">console</span>.log(spellName([...myName]));    <span class="hljs-comment">// returns: "O,l,u,w,a,t,o,b,i, ,S,o,f,e,l,aundefinedundefined"</span>

<span class="hljs-built_in">console</span>.log(spellName({...myName}));    <span class="hljs-comment">// returns: "[object Object]undefinedundefined"</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-pkrxjd?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<h3 id="heading-spread-example-4-how-spread-works-in-an-object-literal">Spread Example 4: How Spread Works in an Object Literal</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myNames = [<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>];
<span class="hljs-keyword">const</span> bio = { ...myNames, <span class="hljs-attr">runs</span>: <span class="hljs-string">"codesweetly.com"</span> };

<span class="hljs-built_in">console</span>.log(bio);

<span class="hljs-comment">// The invocation above will return:</span>
{ <span class="hljs-number">0</span>: <span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-number">1</span>: <span class="hljs-string">"Sofela"</span>, <span class="hljs-attr">runs</span>: <span class="hljs-string">"codesweetly.com"</span> }
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-qnmxsu?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, we used spread inside the <code>bio</code> object to expand <code>myNames</code> values into individual properties.</p>
<h3 id="heading-what-to-know-about-the-spread-operator">What to Know About the Spread Operator</h3>
<p>Keep these three essential pieces of info in mind whenever you choose to use the spread operator.</p>
<h4 id="heading-info-1-spread-operators-cant-expand-object-literals-values">Info 1: Spread operators can’t expand object literal’s values</h4>
<p>Since a properties object is not an iterable object, you cannot use the spread operator to expand its values.</p>
<p>However, you can use the spread operator to clone properties from one object into another.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myName = { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span> };
<span class="hljs-keyword">const</span> bio = { ...myName, <span class="hljs-attr">website</span>: <span class="hljs-string">"codesweetly.com"</span> };

<span class="hljs-built_in">console</span>.log(bio);

<span class="hljs-comment">// The invocation above will return:</span>
{ <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span>, <span class="hljs-attr">website</span>: <span class="hljs-string">"codesweetly.com"</span> };
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-psnsa8?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>The snippet above used the spread operator to clone <code>myName</code>’s content into the <code>bio</code> object.</p>
<p><strong>Note:</strong></p>
<ul>
<li>The spread operator can expand iterable objects’ values only.</li>
<li>An object is iterable only if it (or any object in its prototype chain) has a property with a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol">@@iterator</a> key.</li>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator">Array</a>, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/@@iterator">TypedArray</a>, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/@@iterator">String</a>, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator">Map</a>, and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/@@iterator">Set</a> are all built-in iterable types because they have the <code>@@iterator</code> property by default.</li>
<li>A properties object is not an iterable data type because it does not have the <code>@@iterator</code> property by default.</li>
<li>You can <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator#user-defined_iterables">make a properties object iterable</a> by adding <code>@@iterator</code> onto it.</li>
</ul>
<h4 id="heading-info-2-the-spread-operator-does-not-clone-identical-properties">Info 2: The spread operator does not clone identical properties</h4>
<p>Suppose you used the spread operator to clone properties from object A into object B. And suppose object B contains properties identical to those in object A. In such a case, B’s versions will override those inside A.</p>
<p><strong>Here’s an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myName = { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Tobi"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span> };
<span class="hljs-keyword">const</span> bio = { ...myName, <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-attr">website</span>: <span class="hljs-string">"codesweetly.com"</span> };

<span class="hljs-built_in">console</span>.log(bio);

<span class="hljs-comment">// The invocation above will return:</span>
{ <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span>, <span class="hljs-attr">website</span>: <span class="hljs-string">"codesweetly.com"</span> };
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-gjhjue?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Observe that the spread operator did not copy <code>myName</code>’s <code>firstName</code> property into the <code>bio</code> object because <code>bio</code> already contains a <code>firstName</code> property.</p>
<h4 id="heading-info-3-beware-of-how-spread-works-when-used-on-objects-containing-non-primitives">Info 3: Beware of how spread works when used on objects containing non-primitives!</h4>
<p>Suppose you used the spread operator on an object (or array) containing only primitive values. The computer will not create any reference between the original object and the duplicated one.</p>
<p>For instance, consider this code below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myName = [<span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"is"</span>, <span class="hljs-string">"my"</span>];
<span class="hljs-keyword">const</span> aboutMe = [<span class="hljs-string">"Oluwatobi"</span>, ...myName, <span class="hljs-string">"name."</span>];

<span class="hljs-built_in">console</span>.log(aboutMe);

<span class="hljs-comment">// The invocation above will return:</span>
[<span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"is"</span>, <span class="hljs-string">"my"</span>, <span class="hljs-string">"name."</span>]
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-rd1npd?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Observe that every item in <code>myName</code> is a primitive value. Therefore, when we used the spread operator to clone <code>myName</code> into <code>aboutMe</code>, the computer did not create any reference between the two arrays.</p>
<p>As such, any alteration you make to <code>myName</code> will not reflect in <code>aboutMe</code>, and vice versa.</p>
<p>As an example, let’s add more content to <code>myName</code>:</p>
<pre><code class="lang-js">myName.push(<span class="hljs-string">"real"</span>);
</code></pre>
<p>Now, let’s check the current state of <code>myName</code> and <code>aboutMe</code>:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(myName); <span class="hljs-comment">// ["Sofela", "is", "my", "real"]</span>

<span class="hljs-built_in">console</span>.log(aboutMe); <span class="hljs-comment">// ["Oluwatobi", "Sofela", "is", "my", "name."]</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-ujs6ny?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Notice that <code>myName</code>’s updated content did not reflect in <code>aboutMe</code> — because spread created no reference between the original array and the duplicated one.</p>
<h5 id="heading-what-if-myname-contains-non-primitive-items">What if <code>myName</code> contains non-primitive items?</h5>
<p>Suppose <code>myName</code> contained non-primitives. In that case, spread will create a reference between the original non-primitive and the cloned one.</p>
<p><strong>Here is an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myName = [[<span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"is"</span>, <span class="hljs-string">"my"</span>]];
<span class="hljs-keyword">const</span> aboutMe = [<span class="hljs-string">"Oluwatobi"</span>, ...myName, <span class="hljs-string">"name."</span>];

<span class="hljs-built_in">console</span>.log(aboutMe);

<span class="hljs-comment">// The invocation above will return:</span>
[ <span class="hljs-string">"Oluwatobi"</span>, [<span class="hljs-string">"Sofela"</span>, <span class="hljs-string">"is"</span>, <span class="hljs-string">"my"</span>], <span class="hljs-string">"name."</span> ]
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-ombp5w?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Observe that <code>myName</code> contains a non-primitive value.</p>
<p>Therefore, using the spread operator to clone <code>myName</code>’s content into <code>aboutMe</code> caused the computer to create a reference between the two arrays.</p>
<p>As such, any alteration you make to <code>myName</code>’s copy will reflect in <code>aboutMe</code>’s version, and vice versa.</p>
<p>As an example, let’s add more content to <code>myName</code>:</p>
<pre><code class="lang-js">myName[<span class="hljs-number">0</span>].push(<span class="hljs-string">"real"</span>);
</code></pre>
<p>Now, let’s check the current state of <code>myName</code> and <code>aboutMe</code>:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(myName); <span class="hljs-comment">// [["Sofela", "is", "my", "real"]]</span>

<span class="hljs-built_in">console</span>.log(aboutMe); <span class="hljs-comment">// ["Oluwatobi", ["Sofela", "is", "my", "real"], "name."]</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-qpyy8n?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>Notice that <code>myName</code>’s updated content is reflected in <code>aboutMe</code> — because spread created a reference between the original array and the duplicated one.</p>
<p><strong>Here’s another example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myName = { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span> };
<span class="hljs-keyword">const</span> bio = { ...myName };

myName.firstName = <span class="hljs-string">"Tobi"</span>;

<span class="hljs-built_in">console</span>.log(myName); <span class="hljs-comment">// { firstName: "Tobi", lastName: "Sofela" }</span>

<span class="hljs-built_in">console</span>.log(bio); <span class="hljs-comment">// { firstName: "Oluwatobi", lastName: "Sofela" }</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-tbmtgm?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, <code>myName</code>’s update did not reflect in <code>bio</code> because we used the spread operator on an object that contains primitive values only.</p>
<p><strong>Note:</strong> A developer would call <code>myName</code> a <strong>shallow object</strong> because it contains only primitive items.</p>
<p><strong>Here’s one more example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myName = { 
  <span class="hljs-attr">fullName</span>: { <span class="hljs-attr">firstName</span>: <span class="hljs-string">"Oluwatobi"</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">"Sofela"</span> }
};

<span class="hljs-keyword">const</span> bio = { ...myName };

myName.fullName.firstName = <span class="hljs-string">"Tobi"</span>;

<span class="hljs-built_in">console</span>.log(myName); <span class="hljs-comment">// { fullName: { firstName: "Tobi", lastName: "Sofela" } }</span>

<span class="hljs-built_in">console</span>.log(bio); <span class="hljs-comment">// { fullName: { firstName: "Tobi", lastName: "Sofela" } }</span>
</code></pre>
<p><a target="_blank" href="https://stackblitz.com/edit/web-platform-9uce9g?file=script.js"><strong>Try it on StackBlitz</strong></a></p>
<p>In the snippet above, <code>myName</code>’s update is reflected in <code>bio</code> because we used the spread operator on an object that contains a non-primitive value.</p>
<p><strong>Note:</strong></p>
<ul>
<li>We call <code>myName</code> a <strong>deep object</strong> because it contains a non-primitive item.</li>
<li>You do <strong>shallow copy</strong> when you create references while cloning one object into another. For instance, <code>...myName</code> produces a shallow copy of the <code>myName</code> object because whatever alteration you make in one will reflect in the other.</li>
<li>You do <strong>deep copy</strong> when you clone objects without creating references. For instance, I could deep copy <code>myName</code> into <code>bio</code> by doing <code>const bio = JSON.parse(JSON.stringify(myName))</code>. By doing so, the computer will clone <code>myName</code> into <code>bio</code> without creating any reference.</li>
<li>You can break off the reference between the two objects by replacing the <code>fullName</code> object inside <code>myName</code> or <code>bio</code> with a new object. For instance, doing <code>myName.fullName = { firstName: "Tobi", lastName: "Sofela" }</code> would disconnect the pointer between <code>myName</code> and <code>bio</code>.</li>
</ul>
<h2 id="heading-wrapping-it-up">Wrapping it up</h2>
<p>This article discussed the differences between the rest and spread operators. We also used examples to see how each operator works.</p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
