<?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[ Joan Ayebola - 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[ Joan Ayebola - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 19 May 2026 22:44:28 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/joanayebola/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Secure Authentication System with JWT and Refresh Tokens ]]>
                </title>
                <description>
                    <![CDATA[ Every app that handles user accounts needs a way to confirm who’s who. That’s what authentication is for, making sure the person using an app is the person they claim to be. But doing this securely is harder than it sounds. Traditional methods often ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-secure-authentication-system-with-jwt-and-refresh-tokens/</link>
                <guid isPermaLink="false">6925f655569c4dde127d2f88</guid>
                
                    <category>
                        <![CDATA[ authentication ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JWT ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Tue, 25 Nov 2025 18:32:53 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1764095460886/51b9c653-fa95-42f0-8c51-37f6d6805da4.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Every app that handles user accounts needs a way to confirm who’s who. That’s what authentication is for, making sure the person using an app is the person they claim to be. But doing this securely is harder than it sounds.</p>
<p>Traditional methods often rely on server sessions and cookies. Those work, but they don’t always scale well, especially when you’re building APIs or mobile apps that talk to multiple services. This is why JWTs, or JSON Web Tokens, are useful. They’re small, self-contained tokens that can carry user data safely between a client and a server.</p>
<p>JWTs make it easy to verify users without constantly checking a database – but they also expire fast to reduce risk. To keep users logged in without forcing them to sign in again every few minutes, we use something called a refresh token. It’s a separate, long-lived token that can request new access tokens when the old ones expire.</p>
<p>In this guide, we’ll walk through how to build a secure authentication system using JWTs and refresh tokens. You’ll learn how to generate tokens, validate them, handle expiry, and keep everything safe from common security threats.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-understanding-jwts-json-web-tokens">Understanding JWTs (JSON Web Tokens)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-setting-up-the-project">Setting Up the Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-implement-jwt-authentication">How to Implement JWT Authentication</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-verify-jwts-and-protect-routes">How to Verify JWTs and Protect Routes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-refresh-tokens-and-rotation">Refresh Tokens and Rotation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-understanding-jwts-json-web-tokens">Understanding JWTs (JSON Web Tokens)</h2>
<p>A JWT, short for JSON Web Token, is a compact way to share information between a client and a server. It’s often used to prove that a user is who they say they are. The token is created on the server after a user logs in and is then sent back to the client. The client then includes this token with each request, so the server knows who is making the call.</p>
<p>A JWT has three parts: a header, a payload, and a signature.</p>
<ul>
<li><p>The <strong>header</strong> usually tells the system which algorithm was used to sign the token.</p>
</li>
<li><p>The <strong>payload</strong> contains the data, such as the user’s ID or role.</p>
</li>
<li><p>The <strong>signature</strong> is the part that keeps everything secure. It’s created by hashing the header and payload with a secret key.</p>
</li>
</ul>
<p>Once created, a JWT looks like a long string of random characters separated by dots. When the client sends it back to the server, the server verifies the signature using the same secret key. If it matches, the request is trusted.</p>
<p>One of the main benefits of JWTs is that they are stateless. The server doesn’t need to store session data. Everything needed to verify the user is already inside the token. This makes them fast and easy to use in modern APIs and microservices.</p>
<p>JWTs do have a downside: they cannot be revoked easily once issued. If a token is stolen, the attacker can use it until it expires. This is why short token lifetimes matter. It’s also why refresh tokens exist.</p>
<p>In the next section, we’ll finish the basic JWT setup. After that, we’ll add refresh tokens in <strong>“Refresh Tokens and Rotation.”</strong> That part shows how to handle expiry without making users log in again.</p>
<h2 id="heading-setting-up-the-project">Setting Up the Project</h2>
<p>Before writing any code, let’s set up a simple backend where we can build and test our authentication system. For this guide, we’ll use Node.js with Express, since it’s lightweight and easy to follow. You can use any stack later once you understand the flow.</p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>Make sure you have:</p>
<ul>
<li><p>Node.js and npm installed</p>
</li>
<li><p>A text editor (VS Code works great)</p>
</li>
<li><p>Basic knowledge of JavaScript and APIs</p>
</li>
</ul>
<h3 id="heading-1-initialize-the-project">1. Initialize the Project</h3>
<p>Create a new folder and open it in your terminal.</p>
<pre><code class="lang-bash">mkdir jwt-auth-demo
<span class="hljs-built_in">cd</span> jwt-auth-demo
npm init -y
</code></pre>
<p>This creates a <code>package.json</code> file that will track your dependencies.</p>
<h3 id="heading-2-install-dependencies">2. Install Dependencies</h3>
<p>You’ll need a few packages to get started:</p>
<ul>
<li><p><code>express</code>: the web framework</p>
</li>
<li><p><code>jsonwebtoken</code>: to create and verify tokens</p>
</li>
<li><p><code>bcryptjs</code>: to hash passwords</p>
</li>
<li><p><code>dotenv</code>: to manage environment variables</p>
</li>
</ul>
<p>Install them all at once like this:</p>
<pre><code class="lang-bash">npm install express jsonwebtoken bcryptjs dotenv
</code></pre>
<p>If you want auto-reloading while developing, install nodemon as a dev dependency:</p>
<pre><code class="lang-bash">npm install --save-dev nodemon
</code></pre>
<h3 id="heading-3-project-structure">3. Project Structure</h3>
<p>Here’s a clean structure to keep things organized:</p>
<pre><code class="lang-plaintext">jwt-auth-demo/
│
├── server.js
├── .env
├── package.json
│
├── config/
│   └── db.js
│
├── middleware/
│   └── auth.js
│
├── routes/
│   └── auth.js
│
└── models/
    └── user.js
</code></pre>
<h3 id="heading-4-basic-express-setup">4. Basic Express Setup</h3>
<p>In <code>server.js</code>, start with a minimal Express server.</p>
<pre><code class="lang-js"><span class="hljs-built_in">require</span>(<span class="hljs-string">'dotenv'</span>).config();
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> app = express();

app.use(express.json());

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.send(<span class="hljs-string">'JWT Auth API running'</span>);
});

<span class="hljs-keyword">const</span> PORT = process.env.PORT || <span class="hljs-number">5000</span>;
app.listen(PORT, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server running on port <span class="hljs-subst">${PORT}</span>`</span>));
</code></pre>
<p>You can now run it using:</p>
<pre><code class="lang-bash">node server.js
</code></pre>
<p>or, if you’re using nodemon:</p>
<pre><code class="lang-bash">npx nodemon server.js
</code></pre>
<p>If everything is set up correctly, visiting <code>http://localhost:5000</code> should display <strong>“JWT Auth API running”:</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760559643076/8fb7dcbf-50ca-44bc-b2a3-32273d82957f.png" alt="Screenshot of a terminal running nodemon server.js next to a browser window showing the text “JWT Auth API running” at http://localhost:5000, confirming the server started correctly." class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-implement-jwt-authentication"><strong>How to Implement JWT Authentication</strong></h2>
<p>Now that your server is up, let’s add real authentication. We’ll start with user registration, password hashing, and login. Each user will get a token after logging in, which they can use to access protected routes.</p>
<h3 id="heading-1-set-up-the-user-model">1. Set Up the User Model</h3>
<p>We’ll store users in a simple database. For this demo, let’s use MongoDB with Mongoose, since it’s quick to set up and easy to scale later.</p>
<p>Install the required packages:</p>
<pre><code class="lang-bash">npm install mongoose
</code></pre>
<p>Then create <code>models/user.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mongoose'</span>);

<span class="hljs-keyword">const</span> userSchema = <span class="hljs-keyword">new</span> mongoose.Schema({
  <span class="hljs-attr">username</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>, <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">unique</span>: <span class="hljs-literal">true</span> },
  <span class="hljs-attr">email</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>, <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">unique</span>: <span class="hljs-literal">true</span> },
  <span class="hljs-attr">password</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>, <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span> }
});

<span class="hljs-built_in">module</span>.exports = mongoose.model(<span class="hljs-string">'User'</span>, userSchema);
</code></pre>
<p>We store users with a unique email and a hashed password. The database never sees the raw password. Hashing makes stolen data harder to use.</p>
<h3 id="heading-2-connect-to-mongodb">2. Connect to MongoDB</h3>
<p>Inside <code>config/db.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mongoose'</span>);

<span class="hljs-keyword">const</span> connectDB = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> mongoose.connect(process.env.MONGO_URI);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'MongoDB connected'</span>);
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-built_in">console</span>.error(err.message);
    process.exit(<span class="hljs-number">1</span>);
  }
};

<span class="hljs-built_in">module</span>.exports = connectDB;
</code></pre>
<p><code>mongoose.connect</code> reads the connection string from <code>.env</code>. If the connection fails, we exit the process so we don’t continue in a broken state.</p>
<p>Update your <code>server.js</code> to include the connection:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> connectDB = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./config/db'</span>);
connectDB();
</code></pre>
<p>And don’t forget to add your MongoDB URI in the <code>.env</code> file:</p>
<pre><code class="lang-plaintext">MONGO_URI=mongodb+srv://yourusername:yourpassword@cluster.mongodb.net/auth
JWT_SECRET=your_jwt_secret_key
</code></pre>
<h3 id="heading-3-create-registration-and-login-routes">3. Create Registration and Login Routes</h3>
<p>In <code>routes/auth.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> bcrypt = <span class="hljs-built_in">require</span>(<span class="hljs-string">'bcryptjs'</span>);
<span class="hljs-keyword">const</span> jwt = <span class="hljs-built_in">require</span>(<span class="hljs-string">'jsonwebtoken'</span>);
<span class="hljs-keyword">const</span> User = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../models/user'</span>);

<span class="hljs-keyword">const</span> router = express.Router();

<span class="hljs-comment">// Register a new user</span>
router.post(<span class="hljs-string">'/register'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> { username, email, password } = req.body;

    <span class="hljs-keyword">const</span> existingUser = <span class="hljs-keyword">await</span> User.findOne({ email });
    <span class="hljs-keyword">if</span> (existingUser) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">400</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'User already exists'</span> });

    <span class="hljs-keyword">const</span> hashedPassword = <span class="hljs-keyword">await</span> bcrypt.hash(password, <span class="hljs-number">10</span>);

    <span class="hljs-keyword">const</span> newUser = <span class="hljs-keyword">new</span> User({ username, email, <span class="hljs-attr">password</span>: hashedPassword });
    <span class="hljs-keyword">await</span> newUser.save();

    res.status(<span class="hljs-number">201</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'User created successfully'</span> });
  } <span class="hljs-keyword">catch</span> (err) {
    res.status(<span class="hljs-number">500</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Server error'</span> });
  }
});

<span class="hljs-comment">// Login and issue JWT</span>
router.post(<span class="hljs-string">'/login'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> { email, password } = req.body;

    <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> User.findOne({ email });
    <span class="hljs-keyword">if</span> (!user) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">400</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Invalid credentials'</span> });

    <span class="hljs-keyword">const</span> isMatch = <span class="hljs-keyword">await</span> bcrypt.compare(password, user.password);
    <span class="hljs-keyword">if</span> (!isMatch) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">400</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Invalid credentials'</span> });

    <span class="hljs-keyword">const</span> payload = { <span class="hljs-attr">id</span>: user._id, <span class="hljs-attr">email</span>: user.email };

    <span class="hljs-keyword">const</span> token = jwt.sign(payload, process.env.JWT_SECRET, { <span class="hljs-attr">expiresIn</span>: <span class="hljs-string">'15m'</span> });

    res.json({ token });
  } <span class="hljs-keyword">catch</span> (err) {
    res.status(<span class="hljs-number">500</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Server error'</span> });
  }
});

<span class="hljs-built_in">module</span>.exports = router;
</code></pre>
<p>Add it to your server in <code>server.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> authRoutes = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./routes/auth'</span>);
app.use(<span class="hljs-string">'/api/auth'</span>, authRoutes);
</code></pre>
<h3 id="heading-4-test-it-out">4. Test It Out</h3>
<p>You can now test these routes using Postman or Insomnia.</p>
<p>Send a <code>POST</code> request to <code>/api/auth/register</code> with a JSON body:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"username"</span>: <span class="hljs-string">"demoUser"</span>,
  <span class="hljs-attr">"email"</span>: <span class="hljs-string">"demo@email.com"</span>,
  <span class="hljs-attr">"password"</span>: <span class="hljs-string">"mypassword"</span>
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760713863394/c13ddbd5-ebb1-47d1-9b6d-06bc0f33eb7d.png" alt="Screenshot of a Postman request sending a POST call to http://localhost:3000/api/auth/register with a JSON body containing a username, email, and password. The response area shows a 201 Created status and the message “User created successfully.&quot;" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The register route checks for an existing user by email. It hashes the password with a cost factor of 10 and then returns a 201 on success. We don’t log the password or include it in the response.</p>
<p>Then log in at <code>/api/auth/login</code> to receive a JWT.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760713960135/58eeaa4e-d652-4509-ad6e-756baf19ff8c.png" alt="Screenshot of a Postman request sending a POST call to http://localhost:3000/api/auth/login with a JSON body containing a username, email, and password. The response panel shows a 200 OK status and a JSON object with a generated JWT token." class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The login route finds the user by email and compares the password with bcrypt.compare. If it matches, we sign a token with a small payload: the user ID and email. The JWT_SECRET signs the token so the server can verify it later. The expiresIn: '15m' setting keeps the token short-lived to limit risk. The response only includes the token. User data can be fetched from a protected route.</p>
<p>Once you get the token, copy it, you’ll use it to access protected routes later.</p>
<h2 id="heading-how-to-verify-jwts-and-protect-routes">How to Verify JWTs and Protect Routes</h2>
<p>Now that login returns a token, we should verify it on each request that needs auth. We will write a small middleware that checks the <code>Authorization</code> header, validates the token, and adds the user info to the request.</p>
<h3 id="heading-1-create-the-auth-middleware">1. Create the Auth Middleware</h3>
<p>Create <code>middleware/auth.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> jwt = <span class="hljs-built_in">require</span>(<span class="hljs-string">'jsonwebtoken'</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">auth</span>(<span class="hljs-params">req, res, next</span>) </span>{
  <span class="hljs-keyword">const</span> authHeader = req.headers.authorization || <span class="hljs-string">''</span>;
  <span class="hljs-keyword">const</span> [scheme, token] = authHeader.split(<span class="hljs-string">' '</span>);

  <span class="hljs-keyword">if</span> (scheme !== <span class="hljs-string">'Bearer'</span> || !token) {
    <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Missing or invalid Authorization header'</span> });
  }

  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = { <span class="hljs-attr">id</span>: decoded.id, <span class="hljs-attr">email</span>: decoded.email };
    next();
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-keyword">if</span> (err.name === <span class="hljs-string">'TokenExpiredError'</span>) {
      <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Access token expired'</span> });
    }
    <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Invalid token'</span> });
  }
}

<span class="hljs-built_in">module</span>.exports = auth;
</code></pre>
<p>What it does:</p>
<ul>
<li><p>Reads the <code>Authorization</code> header.</p>
</li>
<li><p>Checks for the <code>Bearer &lt;token&gt;</code> format.</p>
</li>
<li><p>Verifies the token with the secret.</p>
</li>
<li><p>Attaches a simple <code>user</code> object to <code>req</code> for later use.</p>
</li>
</ul>
<h3 id="heading-2-create-the-protected-route">2. Create the Protected Route</h3>
<p>Create a small profile route that returns the current user. Add <code>routes/profile.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> auth = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../middleware/auth'</span>);
<span class="hljs-keyword">const</span> User = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../models/user'</span>);

<span class="hljs-keyword">const</span> router = express.Router();

router.get(<span class="hljs-string">'/me'</span>, auth, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> User.findById(req.user.id).select(<span class="hljs-string">'-password'</span>);
    <span class="hljs-keyword">if</span> (!user) {
      <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">404</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'User not found'</span> });
    }
    res.json({ user });
  } <span class="hljs-keyword">catch</span> (err) {
    res.status(<span class="hljs-number">500</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Server error'</span> });
  }
});

<span class="hljs-built_in">module</span>.exports = router;
</code></pre>
<p>Wire it in <code>server.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> profileRoutes = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./routes/profile'</span>);
app.use(<span class="hljs-string">'/api/profile'</span>, profileRoutes);
</code></pre>
<p>Now a <code>GET /api/profile/me</code> call will only work with a valid token.</p>
<h3 id="heading-3-handle-token-expiry-clearly">3. Handle Token Expiry Clearly</h3>
<p>Short access tokens reduce damage if they leak. We set <code>expiresIn: '15m'</code> during login. When a token expires, the middleware returns a 401 with <code>Access token expired</code>.</p>
<p>We won’t refresh the token here because refresh requires its own endpoint, storage, and rotation rules. You’ll add that in <strong>“Refresh Tokens and Rotation.”</strong> For now, the 401 proves that the expiry is enforced.</p>
<h3 id="heading-4-testing-the-flow">4. Testing the Flow</h3>
<p>In this section, we’ll test that the server blocks requests without a valid token and allows requests with a valid token.</p>
<p>Log in at <code>/api/auth/login</code> and copy the token. Then call <code>/api/profile/me</code> with:</p>
<pre><code class="lang-typescript">Authorization: Bearer &lt;paste_token_here&gt;
</code></pre>
<p>You should see the current user without the password field.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1760715340324/13779fe0-304c-460b-87ac-c86133eea2a4.png" alt="Screenshot of a Postman GET request to http://localhost:3000/api/profile/me using a valid JWT. The response shows a 200 OK status and returns the user’s _id, username, and email, confirming that the protected route works when a proper token is included." width="600" height="400" loading="lazy"></p>
<p>Then remove the header or change the token and call again. You should get a 401.</p>
<p>Next, wait for the token to expire or change <code>expiresIn</code> to a very short value for a quick test. Call again and confirm you get <code>Access token expired</code>.</p>
<h4 id="heading-tips-for-debugging">Tips for debugging</h4>
<ul>
<li><p>401 with “Missing or invalid Authorization header” means the header format is wrong. Use <code>Authorization: Bearer &lt;token&gt;</code>.</p>
</li>
<li><p>401 with “Invalid token” means the token string is wrong, signed with the wrong secret, or corrupted.</p>
</li>
<li><p>401 with “Access token expired” means the expiry check works. You will fix the client experience with the refresh endpoint later.</p>
</li>
<li><p>If all calls fail, confirm your <code>JWT_SECRET</code> is set in <code>.env</code> and that the server was restarted after changes.</p>
</li>
</ul>
<h3 id="heading-5-optional-cookie-support">5. Optional Cookie Support</h3>
<p>You can store tokens in HTTP-only cookies. The browser sends them automatically. Scripts cannot read HTTP-only cookies, which reduces the risk from XSS.</p>
<p>Install and enable cookies:</p>
<pre><code class="lang-plaintext">npm install cookie-parser
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// server.js</span>
<span class="hljs-keyword">const</span> cookieParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cookie-parser'</span>);
app.use(cookieParser());
</code></pre>
<p>Read the access token from a cookie as a fallback:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// middleware/auth.js</span>
<span class="hljs-keyword">const</span> jwt = <span class="hljs-built_in">require</span>(<span class="hljs-string">'jsonwebtoken'</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">auth</span>(<span class="hljs-params">req, res, next</span>) </span>{
  <span class="hljs-keyword">const</span> header = req.headers.authorization || <span class="hljs-string">''</span>;
  <span class="hljs-keyword">const</span> [scheme, tokenFromHeader] = header.split(<span class="hljs-string">' '</span>);
  <span class="hljs-keyword">const</span> tokenFromCookie = req.cookies?.access_token;

  <span class="hljs-keyword">const</span> token = scheme === <span class="hljs-string">'Bearer'</span> &amp;&amp; tokenFromHeader ? tokenFromHeader : tokenFromCookie;

  <span class="hljs-keyword">if</span> (!token) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'No token provided'</span> });

  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = { <span class="hljs-attr">id</span>: decoded.id, <span class="hljs-attr">email</span>: decoded.email };
    next();
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-keyword">const</span> msg = err.name === <span class="hljs-string">'TokenExpiredError'</span> ? <span class="hljs-string">'Access token expired'</span> : <span class="hljs-string">'Invalid token'</span>;
    <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).json({ <span class="hljs-attr">message</span>: msg });
  }
}

<span class="hljs-built_in">module</span>.exports = auth;
</code></pre>
<p>How this works:</p>
<ul>
<li><p>The access token can live in a cookie named <code>access_token</code>.</p>
</li>
<li><p>Mark the cookie as <code>httpOnly</code> and <code>secure</code> in production.</p>
</li>
<li><p>Set <code>sameSite: 'strict'</code> to reduce CSRF risk.</p>
</li>
<li><p>For APIs used by browsers, cookies simplify sending tokens. For SPAs that call many domains, an <code>Authorization</code> header may be simpler.</p>
</li>
</ul>
<p>In the next section, we’ll use the same cookie approach for the refresh token. That section explains why refresh belongs in a cookie and how rotation blocks replay.</p>
<h2 id="heading-refresh-tokens-and-rotation">Refresh Tokens and Rotation</h2>
<p>Access tokens are short-lived and used on every request. They prove the user identity quickly. Refresh tokens live longer and are used only to get new access tokens when the old ones expire. This split keeps day-to-day requests fast and limits the damage if a token leaks.</p>
<p>We will store the refresh token in an HTTP-only cookie. This reduces exposure to scripts and keeps the flow smooth.</p>
<h3 id="heading-1-install-and-setup">1. Install and Setup</h3>
<p>We already have <code>cookie-parser</code>. We won’t add anything new for now, but we will use <a target="_blank" href="https://nodejs.org/api/crypto.html">Node’s built-in <code>crypto</code> module</a> to hash the refresh token before storing it. As a reminder, hashing means the raw token is never saved. If the database leaks, attackers cannot use the hashes to log in.</p>
<p>Create <code>models/refreshToken.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mongoose = <span class="hljs-built_in">require</span>(<span class="hljs-string">'mongoose'</span>);

<span class="hljs-keyword">const</span> refreshTokenSchema = <span class="hljs-keyword">new</span> mongoose.Schema({
  <span class="hljs-attr">user</span>: { <span class="hljs-attr">type</span>: mongoose.Schema.Types.ObjectId, <span class="hljs-attr">ref</span>: <span class="hljs-string">'User'</span>, <span class="hljs-attr">index</span>: <span class="hljs-literal">true</span> },
  <span class="hljs-attr">tokenHash</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>, <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">unique</span>: <span class="hljs-literal">true</span> },
  <span class="hljs-attr">jti</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>, <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">index</span>: <span class="hljs-literal">true</span> },
  <span class="hljs-attr">expiresAt</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">Date</span>, <span class="hljs-attr">required</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">index</span>: <span class="hljs-literal">true</span> },
  <span class="hljs-attr">revokedAt</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">Date</span>, <span class="hljs-attr">default</span>: <span class="hljs-literal">null</span> },
  <span class="hljs-attr">replacedBy</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">String</span>, <span class="hljs-attr">default</span>: <span class="hljs-literal">null</span> }, <span class="hljs-comment">// new jti when rotated</span>
  <span class="hljs-attr">createdAt</span>: { <span class="hljs-attr">type</span>: <span class="hljs-built_in">Date</span>, <span class="hljs-attr">default</span>: <span class="hljs-built_in">Date</span>.now },
  <span class="hljs-attr">ip</span>: <span class="hljs-built_in">String</span>,
  <span class="hljs-attr">userAgent</span>: <span class="hljs-built_in">String</span>
});

<span class="hljs-built_in">module</span>.exports = mongoose.model(<span class="hljs-string">'RefreshToken'</span>, refreshTokenSchema);
</code></pre>
<h3 id="heading-2-token-helpers">2. Token Helpers</h3>
<p>Create <code>utils/tokens.js</code> for clean, reusable logic.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> jwt = <span class="hljs-built_in">require</span>(<span class="hljs-string">'jsonwebtoken'</span>);
<span class="hljs-keyword">const</span> crypto = <span class="hljs-built_in">require</span>(<span class="hljs-string">'crypto'</span>);
<span class="hljs-keyword">const</span> RefreshToken = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../models/refreshToken'</span>);

<span class="hljs-keyword">const</span> ACCESS_TTL = <span class="hljs-string">'15m'</span>;
<span class="hljs-keyword">const</span> REFRESH_TTL_SEC = <span class="hljs-number">60</span> * <span class="hljs-number">60</span> * <span class="hljs-number">24</span> * <span class="hljs-number">7</span>; <span class="hljs-comment">// 7 days</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hashToken</span>(<span class="hljs-params">token</span>) </span>{
  <span class="hljs-keyword">return</span> crypto.createHash(<span class="hljs-string">'sha256'</span>).update(token).digest(<span class="hljs-string">'hex'</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createJti</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> crypto.randomBytes(<span class="hljs-number">16</span>).toString(<span class="hljs-string">'hex'</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">signAccessToken</span>(<span class="hljs-params">user</span>) </span>{
  <span class="hljs-keyword">const</span> payload = { <span class="hljs-attr">id</span>: user._id.toString(), <span class="hljs-attr">email</span>: user.email };
  <span class="hljs-keyword">return</span> jwt.sign(payload, process.env.JWT_SECRET, { <span class="hljs-attr">expiresIn</span>: ACCESS_TTL });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">signRefreshToken</span>(<span class="hljs-params">user, jti</span>) </span>{
  <span class="hljs-keyword">const</span> payload = { <span class="hljs-attr">id</span>: user._id.toString(), jti };
  <span class="hljs-keyword">const</span> token = jwt.sign(payload, process.env.REFRESH_TOKEN_SECRET, { <span class="hljs-attr">expiresIn</span>: REFRESH_TTL_SEC });
  <span class="hljs-keyword">return</span> token;
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">persistRefreshToken</span>(<span class="hljs-params">{ user, refreshToken, jti, ip, userAgent }</span>) </span>{
  <span class="hljs-keyword">const</span> tokenHash = hashToken(refreshToken);
  <span class="hljs-keyword">const</span> expiresAt = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-built_in">Date</span>.now() + REFRESH_TTL_SEC * <span class="hljs-number">1000</span>);
  <span class="hljs-keyword">await</span> RefreshToken.create({ <span class="hljs-attr">user</span>: user._id, tokenHash, jti, expiresAt, ip, userAgent });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setRefreshCookie</span>(<span class="hljs-params">res, refreshToken</span>) </span>{
  <span class="hljs-keyword">const</span> isProd = process.env.NODE_ENV === <span class="hljs-string">'production'</span>;
  res.cookie(<span class="hljs-string">'refresh_token'</span>, refreshToken, {
    <span class="hljs-attr">httpOnly</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">secure</span>: isProd,
    <span class="hljs-attr">sameSite</span>: <span class="hljs-string">'strict'</span>,
    <span class="hljs-attr">path</span>: <span class="hljs-string">'/api/auth/refresh'</span>,
    <span class="hljs-attr">maxAge</span>: REFRESH_TTL_SEC * <span class="hljs-number">1000</span>
  });
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">rotateRefreshToken</span>(<span class="hljs-params">oldDoc, user, req, res</span>) </span>{
  <span class="hljs-comment">// revoke old</span>
  oldDoc.revokedAt = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
  <span class="hljs-keyword">const</span> newJti = createJti();
  oldDoc.replacedBy = newJti;
  <span class="hljs-keyword">await</span> oldDoc.save();

  <span class="hljs-comment">// issue new</span>
  <span class="hljs-keyword">const</span> newAccess = signAccessToken(user);
  <span class="hljs-keyword">const</span> newRefresh = signRefreshToken(user, newJti);
  <span class="hljs-keyword">await</span> persistRefreshToken({
    user,
    <span class="hljs-attr">refreshToken</span>: newRefresh,
    <span class="hljs-attr">jti</span>: newJti,
    <span class="hljs-attr">ip</span>: req.ip,
    <span class="hljs-attr">userAgent</span>: req.headers[<span class="hljs-string">'user-agent'</span>] || <span class="hljs-string">''</span>
  });
  setRefreshCookie(res, newRefresh);
  <span class="hljs-keyword">return</span> { <span class="hljs-attr">accessToken</span>: newAccess };
}

<span class="hljs-built_in">module</span>.exports = {
  hashToken,
  createJti,
  signAccessToken,
  signRefreshToken,
  persistRefreshToken,
  setRefreshCookie,
  rotateRefreshToken
};
</code></pre>
<p>In this code,</p>
<ul>
<li><p>signAccessToken creates a short token with the user ID and email.</p>
</li>
<li><p>signRefreshToken creates a long-lived token with a jti value. The jti lets us rotate and track tokens.</p>
</li>
<li><p>persistRefreshToken hashes the refresh token and stores metadata like expiry and device info.</p>
</li>
<li><p>setRefreshCookie writes the HTTP-only cookie so the browser sends it to the refresh endpoint automatically.</p>
</li>
<li><p>rotateRefreshToken revokes the old token, issues a new pair, and saves the new record. Rotation blocks replay if an old refresh token is stolen.</p>
</li>
</ul>
<h3 id="heading-3-issue-refresh-token-on-login">3. Issue Refresh Token on Login</h3>
<p>Update your <code>routes/auth.js</code> login handler to create and store a refresh token, then set the cookie.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> bcrypt = <span class="hljs-built_in">require</span>(<span class="hljs-string">'bcryptjs'</span>);
<span class="hljs-keyword">const</span> jwt = <span class="hljs-built_in">require</span>(<span class="hljs-string">'jsonwebtoken'</span>);
<span class="hljs-keyword">const</span> User = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../models/user'</span>);
<span class="hljs-keyword">const</span> RefreshToken = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../models/refreshToken'</span>);
<span class="hljs-keyword">const</span> {
  createJti,
  signAccessToken,
  signRefreshToken,
  persistRefreshToken,
  setRefreshCookie
} = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../utils/tokens'</span>);

<span class="hljs-keyword">const</span> router = express.Router();

router.post(<span class="hljs-string">'/login'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> { email, password } = req.body;

    <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> User.findOne({ email });
    <span class="hljs-keyword">if</span> (!user) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">400</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Invalid credentials'</span> });

    <span class="hljs-keyword">const</span> isMatch = <span class="hljs-keyword">await</span> bcrypt.compare(password, user.password);
    <span class="hljs-keyword">if</span> (!isMatch) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">400</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Invalid credentials'</span> });

    <span class="hljs-keyword">const</span> accessToken = signAccessToken(user);

    <span class="hljs-keyword">const</span> jti = createJti();
    <span class="hljs-keyword">const</span> refreshToken = signRefreshToken(user, jti);

    <span class="hljs-keyword">await</span> persistRefreshToken({
      user,
      refreshToken,
      jti,
      <span class="hljs-attr">ip</span>: req.ip,
      <span class="hljs-attr">userAgent</span>: req.headers[<span class="hljs-string">'user-agent'</span>] || <span class="hljs-string">''</span>
    });

    setRefreshCookie(res, refreshToken);

    res.json({ accessToken });
  } <span class="hljs-keyword">catch</span> (err) {
    res.status(<span class="hljs-number">500</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Server error'</span> });
  }
});

<span class="hljs-built_in">module</span>.exports = router;
</code></pre>
<p>On login, we issue both tokens. The access token goes to the JSON response. The refresh token goes to an HTTP-only cookie scoped to <code>/api/auth/refresh</code>. This keeps the refresh token away from frontend code while still letting the browser send it to the refresh endpoint.</p>
<h3 id="heading-4-the-refresh-endpoint">4. The Refresh Endpoint</h3>
<p>Create an endpoint that reads the refresh cookie, verifies it, checks the database entry, and rotates it. If all checks pass, it returns a new access token and sets a new refresh cookie.</p>
<p>Add to <code>routes/auth.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { hashToken, rotateRefreshToken } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'../utils/tokens'</span>);

router.post(<span class="hljs-string">'/refresh'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> token = req.cookies?.refresh_token;
    <span class="hljs-keyword">if</span> (!token) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'No refresh token'</span> });

    <span class="hljs-keyword">let</span> decoded;
    <span class="hljs-keyword">try</span> {
      decoded = jwt.verify(token, process.env.REFRESH_TOKEN_SECRET);
    } <span class="hljs-keyword">catch</span> (err) {
      <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Invalid or expired refresh token'</span> });
    }

    <span class="hljs-keyword">const</span> tokenHash = hashToken(token);
    <span class="hljs-keyword">const</span> doc = <span class="hljs-keyword">await</span> RefreshToken.findOne({ tokenHash, <span class="hljs-attr">jti</span>: decoded.jti }).populate(<span class="hljs-string">'user'</span>);

    <span class="hljs-keyword">if</span> (!doc) {
      <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Refresh token not recognized'</span> });
    }
    <span class="hljs-keyword">if</span> (doc.revokedAt) {
      <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Refresh token revoked'</span> });
    }
    <span class="hljs-keyword">if</span> (doc.expiresAt &lt; <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>()) {
      <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Refresh token expired'</span> });
    }

    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> rotateRefreshToken(doc, doc.user, req, res);
    <span class="hljs-keyword">return</span> res.json({ <span class="hljs-attr">accessToken</span>: result.accessToken });
  } <span class="hljs-keyword">catch</span> (err) {
    res.status(<span class="hljs-number">500</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Server error'</span> });
  }
});
</code></pre>
<p>The refresh endpoint verifies the cookie, checks the database record, confirms it is not expired or revoked, then rotates it. Rotation sets <code>revokedAt</code> on the old record and creates a new one with a fresh <code>jti</code>. The response returns a new access token and sets a new refresh cookie.</p>
<h3 id="heading-5-logout-and-revoke">5. Logout and Revoke</h3>
<p>On logout, revoke the current refresh token and clear the cookie.</p>
<pre><code class="lang-js">router.post(<span class="hljs-string">'/logout'</span>, <span class="hljs-keyword">async</span> (req, res) =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> token = req.cookies?.refresh_token;
    <span class="hljs-keyword">if</span> (token) {
      <span class="hljs-keyword">const</span> tokenHash = hashToken(token);
      <span class="hljs-keyword">const</span> doc = <span class="hljs-keyword">await</span> RefreshToken.findOne({ tokenHash });
      <span class="hljs-keyword">if</span> (doc &amp;&amp; !doc.revokedAt) {
        doc.revokedAt = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
        <span class="hljs-keyword">await</span> doc.save();
      }
    }
    res.clearCookie(<span class="hljs-string">'refresh_token'</span>, { <span class="hljs-attr">path</span>: <span class="hljs-string">'/api/auth/refresh'</span> });
    res.json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Logged out'</span> });
  } <span class="hljs-keyword">catch</span> (err) {
    res.status(<span class="hljs-number">500</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Server error'</span> });
  }
});
</code></pre>
<p>Logout revokes the matching refresh token if present and clears the cookie. This ends the session cleanly on the server side and the client side.</p>
<h3 id="heading-6-client-flow">6. Client Flow</h3>
<p>Here is how the browser app should behave:</p>
<ul>
<li><p>Keep the access token in memory. Do not put it in localStorage.</p>
</li>
<li><p>Call protected APIs with the <code>Authorization</code> header or let cookies handle it if you chose the cookie approach for access.</p>
</li>
<li><p>If a call fails with <code>Access token expired</code>, call <code>/api/auth/refresh</code>. The browser sends the refresh cookie automatically.</p>
</li>
<li><p>Replace the in-memory access token with the new one.</p>
</li>
<li><p>Retry the original request.</p>
</li>
<li><p>On logout, call <code>/api/auth/logout</code> and clear any local state.</p>
</li>
</ul>
<h3 id="heading-7-security-notes">7. Security Notes</h3>
<p>There are some key steps you can take to make sure everything is secure:</p>
<h4 id="heading-separate-secrets">Separate secrets</h4>
<p>Use a different secret for access and refresh tokens. If the access secret leaks, refresh tokens still use a different key. Set <code>JWT_SECRET</code> and <code>REFRESH_TOKEN_SECRET</code> in <code>.env</code>.</p>
<h4 id="heading-https-only">HTTPS only</h4>
<p>Serve production traffic over HTTPS. Cookies marked <code>secure: true</code> only travel over HTTPS. This protects tokens in transit.</p>
<h4 id="heading-rotate-on-every-refresh">Rotate on every refresh</h4>
<p>Issue a new refresh token and revoke the old one each time you refresh. Rotation makes a stolen old token useless after the next refresh.</p>
<h4 id="heading-hash-refresh-tokens-in-the-database">Hash refresh tokens in the database</h4>
<p>Store a SHA-256 hash, not the raw token. This way a database leak does not give attackers the actual token string.</p>
<h4 id="heading-scope-and-flags-for-cookies">Scope and flags for cookies</h4>
<p>Use <code>httpOnly: true</code>, <code>secure: true</code> in production, <code>sameSite: 'strict'</code>, and a narrow <code>path</code> such as <code>/api/auth/refresh</code>. These flags reduce XSS and CSRF risk and limit where the cookie is sent.</p>
<h4 id="heading-short-access-ttl-and-moderate-refresh-ttl">Short access TTL and moderate refresh TTL</h4>
<p>Keep access tokens short, such as 15 minutes. Use a refresh lifetime like 7 days. This keeps risk low without annoying users.</p>
<h4 id="heading-device-awareness">Device awareness</h4>
<p>Store <code>ip</code> and <code>userAgent</code>. If patterns change in a suspicious way, you can revoke or challenge the session.</p>
<h4 id="heading-auditing-and-limits">Auditing and limits</h4>
<p>Log refresh events and consider rate limits on the refresh endpoint. This helps detect abuse.’</p>
<p>Add to <code>.env</code>:</p>
<pre><code class="lang-plaintext">REFRESH_TOKEN_SECRET=your_refresh_secret_key
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You now have a working authentication system that uses JWTs and refresh tokens to keep users logged in safely. The access token handles quick verification. The refresh token quietly renews access when it expires. Together, they strike a balance between security and convenience.</p>
<p>You built user registration, login, protected routes, and a full refresh flow. You also learned how to rotate refresh tokens, store them securely, and handle logout cleanly. Each step adds another layer of safety that keeps your app and users protected.</p>
<p>From here, you can expand this setup to match your real project. You can add role-based permissions, track user sessions by device, or move the logic into a dedicated authentication service. What matters most is understanding the flow and keeping tokens short-lived and well-guarded.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Incremental Static Regeneration (ISR) Works in Next.js ]]>
                </title>
                <description>
                    <![CDATA[ When you build a website, you often have two main choices for how pages are created: statically or dynamically. Static pages are created once when you build your project. They’re fast because the server doesn’t have to do any extra work when someone ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-incremental-static-regeneration-isr-works-in-nextjs/</link>
                <guid isPermaLink="false">68139db5555c3ab781a6e0a1</guid>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Thu, 01 May 2025 16:13:41 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1746114577532/94c5118c-f931-415a-932e-45b7e24b99f6.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When you build a website, you often have two main choices for how pages are created: statically or dynamically.</p>
<p>Static pages are created once when you build your project. They’re fast because the server doesn’t have to do any extra work when someone visits the page.</p>
<p>Dynamic pages are created on the fly. Every time a user asks for a page, the server builds it fresh. This can be slower, but it means the content is always up-to-date.</p>
<p>Both options have benefits and drawbacks. Static pages are very fast, but they can show old content if something changes after the build. Dynamic pages are always fresh, but they can be slow because the server has to work harder.</p>
<p>This is where Incremental Static Regeneration (ISR) comes in. ISR gives you the best of both worlds: the speed of static pages with the freshness of dynamic pages.</p>
<p>In this article, we will explore what ISR is, how it works in Next.js, and how you can use it to make your websites faster and smarter.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-incremental-static-regeneration-isr">What is Incremental Static Regeneration (ISR)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-isr-works-behind-the-scenes">How ISR Works Behind the Scenes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-does-isr-trigger-a-new-page-generation">When Does ISR Trigger a New Page Generation?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-common-use-cases-for-isr">Common Use Cases for ISR</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-best-practices-for-using-isr">Best Practices for Using ISR</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-potential-pitfalls-and-how-to-avoid-them">Potential Pitfalls and How to Avoid Them</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-advanced-tips-on-demand-isr">Advanced Tips: On-Demand ISR</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-what-is-incremental-static-regeneration-isr">What is Incremental Static Regeneration (ISR)?</h2>
<p>Incremental Static Regeneration (ISR) is a feature in Next.js that lets you update static pages after you have built your site.</p>
<p>In the past, if you built a static site and needed to change something, you had to rebuild the whole site from scratch. This could take a lot of time, especially for large websites.</p>
<p>ISR solves this problem. With ISR, you can tell Next.js to rebuild a page in the background after a certain amount of time, or whenever you ask it to. The user still sees a fast static page, but the page can also update itself behind the scenes without you having to rebuild everything manually.</p>
<p>In simple words, pages are pre-rendered and served like static files. After a set time, Next.js can regenerate the page with fresh data and users always get fast, reliable pages.</p>
<h2 id="heading-how-isr-works-behind-the-scenes">How ISR Works Behind the Scenes</h2>
<p>To understand ISR, let’s first look at the three ways you can build pages in Next.js:</p>
<ul>
<li><p><strong>Static Generation (SSG):</strong> Pages are built once when you deploy. They never change unless you rebuild the whole site.</p>
</li>
<li><p><strong>Server-Side Rendering (SSR):</strong> Pages are built fresh on every request. This can slow things down because the server is doing work every time.</p>
</li>
<li><p><strong>Incremental Static Regeneration (ISR):</strong> Pages are built at request time <em>only if needed</em> after a certain amount of time has passed. Otherwise, users get the already-built page instantly.</p>
</li>
</ul>
<h3 id="heading-how-isr-actually-works"><strong>How ISR Actually Works:</strong></h3>
<p>When you use ISR:</p>
<ol>
<li><p>A user visits your page.</p>
</li>
<li><p>If the page is already built and not expired, Next.js serves the cached static page.</p>
</li>
<li><p>If the page has expired based on the time you set, Next.js rebuilds the page in the background while still serving the old page.</p>
</li>
<li><p>The next user who visits gets the fresh new version automatically.</p>
</li>
</ol>
<p>You control when pages expire by setting a time limit, using the <code>revalidate</code> key inside your <code>getStaticProps</code> function.</p>
<p>Here is the basic setup for ISR:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// pages/posts/[id].js</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getStaticProps</span>(<span class="hljs-params">context</span>) </span>{
  <span class="hljs-keyword">const</span> { id } = context.params;

  <span class="hljs-keyword">const</span> post = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://example.com/posts/<span class="hljs-subst">${id}</span>`</span>).then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.json());

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">props</span>: {
      post,
    },
    <span class="hljs-attr">revalidate</span>: <span class="hljs-number">60</span>, <span class="hljs-comment">// Regenerate the page after 60 seconds</span>
  };
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getStaticPaths</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> posts = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://example.com/posts'</span>).then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.json());

  <span class="hljs-keyword">const</span> paths = posts.map(<span class="hljs-function">(<span class="hljs-params">post</span>) =&gt;</span> ({
    <span class="hljs-attr">params</span>: { <span class="hljs-attr">id</span>: post.id.toString() },
  }));

  <span class="hljs-keyword">return</span> { paths, <span class="hljs-attr">fallback</span>: <span class="hljs-string">'blocking'</span> };
}
</code></pre>
<p><strong>What this does:</strong></p>
<ul>
<li><p>The page is built and cached the first time someone visits it.</p>
</li>
<li><p>After 60 seconds, if someone visits again, Next.js will rebuild the page in the background with new data.</p>
</li>
<li><p>Users always get a page immediately. They never have to wait.</p>
</li>
</ul>
<h2 id="heading-when-does-isr-trigger-a-new-page-generation">When Does ISR Trigger a New Page Generation?</h2>
<p>Now that you know what ISR is, let’s look at when and how a page actually gets regenerated.</p>
<p>Here is the flow:</p>
<ol>
<li><p>A user requests a page.</p>
</li>
<li><p>Next.js checks if a cached (already built) page exists.</p>
</li>
<li><p>If the page is still "fresh" (inside the <code>revalidate</code> time), it simply serves the cached page.</p>
</li>
<li><p>If the page is "stale" (outside the <code>revalidate</code> time), it <strong>serves the old cached page</strong> immediately but also starts rebuilding the page in the background.</p>
</li>
<li><p>Once the rebuild is done, the next user gets the new updated page.</p>
</li>
</ol>
<p><strong>Important:</strong><br>No one ever waits. ISR always serves something instantly, either the fresh page or the previous version.</p>
<pre><code class="lang-plaintext">User visits page --&gt; Is page fresh?
         |
    Yes  |  No
    Serve cached page  Serve cached page + Start background regeneration
                           |
                  Regeneration finished
                           |
                  Next user sees updated page
</code></pre>
<h3 id="heading-quick-example">Quick Example</h3>
<p>Let’s say you set <code>revalidate: 30</code> seconds for your page.</p>
<ul>
<li><p>At 12:00:00 PM → Page is built and cached.</p>
</li>
<li><p>At 12:00:10 PM → A user visits. Page is served from cache (still fresh).</p>
</li>
<li><p>At 12:00:35 PM → Another user visits. Cache is stale, so Next.js serves the old page but triggers a rebuild.</p>
</li>
<li><p>At 12:00:36 PM → Rebuild finishes. New page is ready.</p>
</li>
<li><p>At 12:00:40 PM → Next visitor gets the new fresh page.</p>
</li>
</ul>
<h4 id="heading-in-short"><strong>In short:</strong></h4>
<p>The page is always available fast, and it quietly updates itself without users even noticing.</p>
<h2 id="heading-common-use-cases-for-isr">Common Use Cases for ISR</h2>
<p>You might be wondering, when you should actually use ISR?</p>
<p>Here are the most common situations where ISR is the perfect choice:</p>
<h3 id="heading-1-blogs-and-news-sites">1. Blogs and News Sites</h3>
<p>If you run a blog or a news website, new articles are added often. You want your readers to see fresh content, but you also want the pages to load fast.</p>
<p>With ISR:</p>
<ul>
<li><p>Articles are built as static pages.</p>
</li>
<li><p>When you publish a new article, it quietly updates after a short time.</p>
</li>
<li><p>Readers always get fast loading speeds.</p>
</li>
</ul>
<p><strong>Example:</strong><br>A tech blog updates every few hours. You set <code>revalidate: 3600</code> (1 hour) so pages refresh with new content once every hour.</p>
<h3 id="heading-2-e-commerce-product-pages">2. E-commerce Product Pages</h3>
<p>In online stores, product information like prices, availability, and descriptions change often. You want the data to be pretty fresh, but you also need fast page loads for good sales.</p>
<p>With ISR:</p>
<ul>
<li><p>Product pages load instantly.</p>
</li>
<li><p>If something changes (like a sale), the page quietly updates without hurting the shopping experience.</p>
</li>
</ul>
<p><strong>Example:</strong><br>You set <code>revalidate: 300</code> (5 minutes) for your products so that changes show up quickly without slowing down the store.</p>
<h3 id="heading-3-dashboards-and-user-generated-content">3. Dashboards and User-Generated Content</h3>
<p>If your site has dashboards, reviews, forums, or user profiles that do not change every second, ISR can be a smart choice.</p>
<p>With ISR:</p>
<ul>
<li><p>You can show updated posts, comments, or stats without making the server work too hard.</p>
</li>
<li><p>The content refreshes at intervals you decide.</p>
</li>
</ul>
<p><strong>Example:</strong><br>A review site refreshes its "Top Products" list every day using <code>revalidate: 86400</code> (24 hours).</p>
<h4 id="heading-in-short-1">In short:</h4>
<p>If your page changes sometimes (not every second) and you want great speed and fresh content, use ISR.</p>
<h2 id="heading-best-practices-for-using-isr">Best Practices for Using ISR</h2>
<p>To get the best results with ISR, you need to set it up correctly. Here are some important tips to make sure everything works smoothly.</p>
<h3 id="heading-1-choose-the-right-revalidate-time">1. Choose the Right <code>revalidate</code> Time</h3>
<p>Think about how often your content really changes.</p>
<ul>
<li><p>If your content changes <strong>hourly</strong>, you might set <code>revalidate: 3600</code> (which is 1 hour).</p>
</li>
<li><p>If your content changes <strong>daily</strong>, you might set <code>revalidate: 86400</code> (which is 24 hours).</p>
</li>
<li><p>If your content changes <strong>every few minutes</strong>, you might set <code>revalidate: 300</code> (which is 5 minutes).</p>
</li>
</ul>
<p><strong>Tip:</strong><br>Pick a <code>revalidate</code> time that balances newness and server load. Shorter times mean fresher data but can put more pressure on your server.</p>
<h3 id="heading-2-handle-errors-efficiently">2. Handle Errors Efficiently</h3>
<p>Sometimes, your data source (like an API) might fail when regenerating a page.</p>
<p>To avoid breaking your page:</p>
<ul>
<li><p>Always use a try-catch block in your <code>getStaticProps</code>.</p>
</li>
<li><p>Show a fallback message or a simple error page if the fetch fails.</p>
</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getStaticProps</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://example.com/data'</span>).then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.json());

    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">props</span>: { data },
      <span class="hljs-attr">revalidate</span>: <span class="hljs-number">60</span>,
    };
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Failed to fetch data:'</span>, error);

    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">props</span>: { <span class="hljs-attr">data</span>: <span class="hljs-literal">null</span> },
      <span class="hljs-attr">revalidate</span>: <span class="hljs-number">60</span>,
    };
  }
}
</code></pre>
<h3 id="heading-3-think-about-seo">3. Think About SEO</h3>
<p>Since ISR serves static pages fast, it is great for SEO.</p>
<p>Just remember:</p>
<ul>
<li><p>Always return meaningful content even if data fetching fails.</p>
</li>
<li><p>Avoid showing "Loading..." states when using ISR. The page should feel complete to both users and search engines.</p>
</li>
</ul>
<h2 id="heading-potential-pitfalls-and-how-to-avoid-them">Potential Pitfalls and How to Avoid Them</h2>
<p>Even though ISR is amazing, there are a few things that can trip you up if you are not careful. Here is what to watch out for.</p>
<h3 id="heading-1-stale-data-issues">1. Stale Data Issues</h3>
<p>Sometimes users might see old data if the page has not revalidated yet. This happens because ISR serves the cached version until a new one is built.</p>
<p><strong>How to handle it:</strong></p>
<ul>
<li><p>Set a <code>revalidate</code> time that makes sense for your content.</p>
</li>
<li><p>If your content is very sensitive (like stock prices), you might want to use Server-Side Rendering (SSR) instead of ISR.</p>
</li>
</ul>
<h3 id="heading-2-deployment-misconfigurations">2. Deployment Misconfigurations</h3>
<p>ISR needs server support to work correctly. If you are hosting your site on platforms like Vercel or Netlify, they handle this for you.</p>
<p>But if you use a custom server or different hosting, make sure:</p>
<ul>
<li><p>You have serverless functions or backend support running.</p>
</li>
<li><p>You do not turn your site into static-only hosting by mistake (like plain S3 buckets without any backend).</p>
</li>
</ul>
<p><strong>Tip:</strong><br>Always check your hosting provider’s docs to confirm they support <strong>Next.js ISR</strong> properly.</p>
<h3 id="heading-3-big-rebuilds-can-cause-load-spikes">3. Big Rebuilds Can Cause Load Spikes</h3>
<p>If your <code>revalidate</code> is too short and you have thousands of pages, the server might get flooded with background regeneration requests.</p>
<p><strong>How to handle it:</strong></p>
<ul>
<li><p>Be smart with your <code>revalidate</code> values.</p>
</li>
<li><p>For very big sites, consider On-Demand ISR (where you control when pages rebuild manually – we’ll talk about this next).</p>
</li>
</ul>
<h2 id="heading-advanced-tips-on-demand-isr">Advanced Tips: On-Demand ISR</h2>
<p>Normally, with ISR, pages regenerate after a set time that you define with <code>revalidate</code>.</p>
<p>But sometimes you want full control. You want to regenerate a page immediately after something happens, like:</p>
<ul>
<li><p>A new blog post is published</p>
</li>
<li><p>A product is updated</p>
</li>
<li><p>A user submits new content</p>
</li>
</ul>
<p>This is where On-Demand ISR comes in.</p>
<p>With On-Demand ISR, you manually trigger a page to rebuild using an API route. No waiting for the timer – you decide when it happens.</p>
<h3 id="heading-how-to-set-up-on-demand-isr">How to Set Up On-Demand ISR</h3>
<p>You need two simple things:</p>
<ol>
<li><p>An API Route that tells Next.js to revalidate a page.</p>
</li>
<li><p>A secret token to protect your API so not just anyone can trigger it.</p>
</li>
</ol>
<h3 id="heading-example-basic-api-route-for-on-demand-isr">Example: Basic API Route for On-Demand ISR</h3>
<p>Create a file like this:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// pages/api/revalidate.js</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handler</span>(<span class="hljs-params">req, res</span>) </span>{
  <span class="hljs-comment">// Secret token check for security</span>
  <span class="hljs-keyword">if</span> (req.query.secret !== process.env.MY_SECRET_TOKEN) {
    <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">401</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Invalid token'</span> });
  }

  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> pathToRevalidate = req.query.path;

    <span class="hljs-keyword">await</span> res.revalidate(pathToRevalidate);

    <span class="hljs-keyword">return</span> res.json({ <span class="hljs-attr">revalidated</span>: <span class="hljs-literal">true</span> });
  } <span class="hljs-keyword">catch</span> (err) {
    <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">500</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Error revalidating'</span> });
  }
}
</code></pre>
<h3 id="heading-how-to-trigger-it">How to Trigger It</h3>
<p>You can make a <strong>POST</strong> request to your API route like this:</p>
<pre><code class="lang-plaintext">POST /api/revalidate?secret=YOUR_TOKEN&amp;path=/your-page-path
</code></pre>
<p>For example:</p>
<pre><code class="lang-plaintext">POST /api/revalidate?secret=MY_SECRET_TOKEN&amp;path=/posts/my-new-post
</code></pre>
<p>Next.js will immediately rebuild <code>/posts/my-new-post</code>, no need to wait for the timer.</p>
<h3 id="heading-important">Important:</h3>
<ul>
<li><p>Always use a secret token and store it safely (like in <code>.env</code> files).</p>
</li>
<li><p>Make sure only trusted systems (like your CMS or admin panel) can call the revalidate API.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Incremental Static Regeneration (ISR) is one of the best features in Next.js. It gives you the speed of static pages and the newness of dynamic content at the same time.</p>
<p>With ISR:</p>
<ul>
<li><p>Your pages load instantly.</p>
</li>
<li><p>Your content stays up-to-date without full rebuilds.</p>
</li>
<li><p>Your website feels smooth, modern, and professional.</p>
</li>
</ul>
<p>If you use ISR wisely, you can build websites that are faster and smarter without making things complicated.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Less Common HTML Elements and How to Use Them in Your Code ]]>
                </title>
                <description>
                    <![CDATA[ HTML has a lot of tags that many people use every day, like <div>, <p>, and <a>. But there are also some hidden gems that often go unnoticed. These tags can help make websites more engaging, accessible, and meaningful without much extra effort. In th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/less-common-html-elements-and-how-to-use-them/</link>
                <guid isPermaLink="false">67292117f26a058bcaa2e19d</guid>
                
                    <category>
                        <![CDATA[ HTML5 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Accessibility ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Mon, 04 Nov 2024 19:31:35 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730747551049/73b334f4-7b4a-448a-bfae-8b95cffe6119.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>HTML has a lot of tags that many people use every day, like <code>&lt;div&gt;</code>, <code>&lt;p&gt;</code>, and <code>&lt;a&gt;</code>. But there are also some hidden gems that often go unnoticed. These tags can help make websites more engaging, accessible, and meaningful without much extra effort.</p>
<p>In this article, we’ll discuss a group of unique HTML elements that can enhance your web pages. They offer specific functions for formatting text, improving readability, and adding interactive features.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-the-tag-short-inline-quotes">The <code>&lt;q&gt;</code> Tag: Short Inline Quotes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-tag-strikethrough-text">The <code>&lt;s&gt;</code> Tag: Strikethrough Text</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-tag-highlighted-text">The <code>&lt;mark&gt;</code> Tag: Highlighted Text</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-tag-annotating-east-asian-language-text">The <code>&lt;ruby&gt;</code> Tag: Annotating East Asian Language Text</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-tag-semantic-time-and-date">The <code>&lt;time&gt;</code> Tag: Semantic Time and Date</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-tag-bi-directional-text-isolation">The <code>&lt;bdi&gt;</code> Tag: Bi-Directional Text Isolation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-tag-defining-terms">The <code>&lt;dfn&gt;</code> Tag: Defining Terms</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-tag-line-break-opportunities">The <code>&lt;wbr&gt;</code> Tag: Line Break Opportunities</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-tag-inserted-text">The <code>&lt;ins&gt;</code> Tag: Inserted Text</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-tag-deleted-text">The <code>&lt;del&gt;</code> Tag: Deleted Text</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-the-tag-short-inline-quotes">The <code>&lt;q&gt;</code> Tag: Short Inline Quotes</h2>
<p>The <code>&lt;q&gt;</code> tag is used to add short quotes inside a paragraph. It helps make quotes look different and easier to spot, without breaking up the flow of the text. This tag automatically adds quotation marks around the content.</p>
<h3 id="heading-description-and-syntax">Description and Syntax</h3>
<p>The basic structure of the <code>&lt;q&gt;</code> tag is simple:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>She said, <span class="hljs-tag">&lt;<span class="hljs-name">q</span>&gt;</span>This is amazing!<span class="hljs-tag">&lt;/<span class="hljs-name">q</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>This would display as:<br><em>She said, “This is amazing!”</em></p>
<h3 id="heading-how-it-differs-from-the-element">How It Differs From the <code>&lt;blockquote&gt;</code> Element</h3>
<p>The <code>&lt;q&gt;</code> tag is for short quotes inside a sentence. On the other hand, the <code>&lt;blockquote&gt;</code> element is used for longer quotes that usually need their own space or paragraph.</p>
<p>For example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">blockquote</span>&gt;</span>
  "This is a long quote that needs its own space. It is different from a short quote."
<span class="hljs-tag">&lt;/<span class="hljs-name">blockquote</span>&gt;</span>
</code></pre>
<p>This block will appear with indentation and is meant to highlight a bigger chunk of quoted text.</p>
<h3 id="heading-use-cases-adding-quotations-within-paragraphs">Use Cases: Adding Quotations Within Paragraphs</h3>
<p>The <code>&lt;q&gt;</code> tag is perfect for cases where you need to mention a quote in a sentence without separating it too much. For instance, when quoting someone in an article or blog post:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The professor said, <span class="hljs-tag">&lt;<span class="hljs-name">q</span>&gt;</span>Practice makes perfect<span class="hljs-tag">&lt;/<span class="hljs-name">q</span>&gt;</span>, during the class.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>In this case, the <code>&lt;q&gt;</code> tag keeps the quote small and inside the same paragraph.</p>
<center>
<p>The professor said, <q>Practice makes perfect</q>, during the class.</p>
</center>

<h3 id="heading-browser-compatibility-and-styling-tips">Browser Compatibility and Styling Tips</h3>
<p>Most modern browsers automatically add quotation marks to the content inside a <code>&lt;q&gt;</code> tag. But you can change how it looks using CSS if needed. Here’s how you can style it:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">q</span> {
  <span class="hljs-attribute">quotes</span>: <span class="hljs-string">"«"</span> <span class="hljs-string">"»"</span>;
  <span class="hljs-attribute">font-style</span>: italic;
}
</code></pre>
<p>This code will change the quotes to French-style marks (« and ») and make the quote italic.</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/YzmNWGd" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p>Most browsers support the <code>&lt;q&gt;</code> tag, so you don’t have to worry about compatibility issues for modern users. But older browsers may need extra care, so always test if your audience uses older versions.</p>
<h2 id="heading-the-tag-strikethrough-text">The <code>&lt;s&gt;</code> Tag: Strikethrough Text</h2>
<p>The <code>&lt;s&gt;</code> tag is used to show text that is no longer correct, relevant, or has been removed. It puts a line through the middle of the text, which we call a "strikethrough." This tag is often used to indicate something that has been edited or updated.</p>
<h3 id="heading-explanation-and-usage">Explanation and Usage</h3>
<p>The <code>&lt;s&gt;</code> tag is simple to use. Wrap it around the text you want to strike through:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This product was <span class="hljs-tag">&lt;<span class="hljs-name">s</span>&gt;</span>$50<span class="hljs-tag">&lt;/<span class="hljs-name">s</span>&gt;</span> now only $30!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>This will display as:<br><em>This product was <s>$50</s> now only $30!</em></p>
<h3 id="heading-common-use-cases-indicating-removed-or-irrelevant-content">Common Use Cases: Indicating Removed or Irrelevant Content</h3>
<p>The <code>&lt;s&gt;</code> tag is great for showing price changes, edits, or content that is no longer valid. For example:</p>
<p><strong>Price updates</strong>:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">s</span>&gt;</span>$75<span class="hljs-tag">&lt;/<span class="hljs-name">s</span>&gt;</span> $50 (Limited Offer!)<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<center>
<p><s>$75</s> $50 (Limited Offer!)</p>
</center>

<p><strong>Corrections or changes</strong>:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">s</span>&gt;</span>Old website address<span class="hljs-tag">&lt;/<span class="hljs-name">s</span>&gt;</span> New website address<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<center>
<p><s>Old website address</s> New website address</p>
</center>

<p><strong>Content that’s no longer relevant</strong>:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This feature is <span class="hljs-tag">&lt;<span class="hljs-name">s</span>&gt;</span>no longer available<span class="hljs-tag">&lt;/<span class="hljs-name">s</span>&gt;</span>.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<center>
<p>This feature is <s>no longer available</s>.</p>
</center>

<h3 id="heading-styling-possibilities-with-css">Styling Possibilities With CSS</h3>
<p>You can customize how the strikethrough looks using CSS. For example, you can change the color of the line or the text:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">s</span> {
  <span class="hljs-attribute">text-decoration</span>: line-through;
  <span class="hljs-attribute">color</span>: red;
}
</code></pre>
<p>In this case, the text will have a red line through it, giving more emphasis to the fact it’s been crossed out.</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/VwoPjWg" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<h3 id="heading-semantic-meaning-versus-visual-decoration">Semantic Meaning Versus Visual Decoration</h3>
<p>The <code>&lt;s&gt;</code> tag holds some semantic meaning. It usually represents content that was once valid but is now incorrect or outdated. It’s more than just a style change. For example, it’s perfect for showing changes in legal documents, corrections in blog posts, or updates to prices.</p>
<p>On the other hand, if you're using strikethrough just for visual decoration without meaning that the text is wrong, it’s better to use CSS directly, like this:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">span</span><span class="hljs-selector-class">.strike</span> {
  <span class="hljs-attribute">text-decoration</span>: line-through;
}
</code></pre>
<p>And then apply it in your HTML:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This text is <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"strike"</span>&gt;</span>crossed out<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span> just for fun!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>This approach is purely for styling and doesn’t carry the same meaning as the <code>&lt;s&gt;</code> tag.</p>
<h2 id="heading-the-tag-highlighted-text">The <code>&lt;mark&gt;</code> Tag: Highlighted Text</h2>
<p>The <code>&lt;mark&gt;</code> tag is used to highlight text. It helps draw attention to certain parts of your content, making them stand out. By default, browsers highlight text with a yellow background when the <code>&lt;mark&gt;</code> tag is used.</p>
<h3 id="heading-purpose-of-the-tag">Purpose of the <code>&lt;mark&gt;</code> Tag</h3>
<p>The <code>&lt;mark&gt;</code> tag is great when you want to emphasize something important. It's often used to show search results, recent changes, or any text that needs special attention.</p>
<p>Here’s an example of how it works:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is a <span class="hljs-tag">&lt;<span class="hljs-name">mark</span>&gt;</span>highlighted<span class="hljs-tag">&lt;/<span class="hljs-name">mark</span>&gt;</span> word.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>This will display as:<br><em>This is a</em> <strong><em>highlighted</em></strong> <em>word.</em></p>
<h3 id="heading-best-practices-for-using-for-emphasis-or-search-results">Best Practices for Using <code>&lt;mark&gt;</code> for Emphasis or Search Results</h3>
<p><strong>Highlighting key terms</strong>: If you want to emphasize important words or phrases in an article or blog post, the <code>&lt;mark&gt;</code> tag is a simple way to do that:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The most important concept here is <span class="hljs-tag">&lt;<span class="hljs-name">mark</span>&gt;</span>efficiency<span class="hljs-tag">&lt;/<span class="hljs-name">mark</span>&gt;</span>.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<center>
<p>The most important concept here is <mark>efficiency</mark>.</p>
</center>

<p><strong>Search results</strong>: When showing search results on a webpage, using the <code>&lt;mark&gt;</code> tag to highlight the matching terms makes it easier for users to find what they’re looking for:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Your search for <span class="hljs-tag">&lt;<span class="hljs-name">mark</span>&gt;</span>HTML<span class="hljs-tag">&lt;/<span class="hljs-name">mark</span>&gt;</span> found these results:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<center>
<p>Your search for <mark>HTML</mark> found these results:</p>
</center>

<p><strong>Recent updates</strong>: You can also use the <code>&lt;mark&gt;</code> tag to show new updates or changes in your content:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>We have recently added the <span class="hljs-tag">&lt;<span class="hljs-name">mark</span>&gt;</span>new feature<span class="hljs-tag">&lt;/<span class="hljs-name">mark</span>&gt;</span> to the app.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<center>
<p>We have recently added the <mark>new feature</mark> to the app.</p>
</center>

<h3 id="heading-how-to-style-highlighted-text-effectively">How to Style Highlighted Text Effectively</h3>
<p>While the default color for <code>&lt;mark&gt;</code> is yellow, you can change it with CSS to match your website’s design. Here’s an example of how to customize the highlighted text:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">mark</span> {
  <span class="hljs-attribute">background-color</span>: lightblue;
  <span class="hljs-attribute">color</span>: black;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">2px</span>;
}
</code></pre>
<p>This will give the text a light blue background with black text.</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/poMRbde" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p>If you want the text to stand out even more, you can add a border or change the font style:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">mark</span> {
  <span class="hljs-attribute">background-color</span>: yellow;
  <span class="hljs-attribute">color</span>: black;
  <span class="hljs-attribute">font-weight</span>: bold;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">4px</span>;
}
</code></pre>
<p>This would make the highlighted text look more polished and noticeable.</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/OJKWXzV" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<h3 id="heading-browser-support-and-accessibility-considerations">Browser Support and Accessibility Considerations</h3>
<p>The <code>&lt;mark&gt;</code> tag is supported across all modern browsers, so you won’t face any compatibility issues. Just make sure the background color you choose provides enough contrast for readability, especially for users with visual impairments.</p>
<p>Using a light background with dark text is a good rule of thumb. Testing the color contrast ensures that the highlighted content remains accessible to everyone, including those using screen readers.</p>
<h2 id="heading-the-tag-annotating-east-asian-language-text">The <code>&lt;ruby&gt;</code> Tag: Annotating East Asian Language Text</h2>
<p>The <code>&lt;ruby&gt;</code> tag is used to add small annotations to text, often seen in East Asian languages like Japanese or Chinese. These annotations help readers with pronunciation or meaning, especially when the characters are complex or unfamiliar.</p>
<h3 id="heading-definition-and-use-cases-for">Definition and Use Cases for <code>&lt;ruby&gt;</code></h3>
<p>In languages like Japanese, it's common to use a small guide above or beside characters to show how they should be pronounced. The <code>&lt;ruby&gt;</code> tag pairs the main text with a small annotation, usually in a simpler script.</p>
<p>Here’s a basic example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">ruby</span>&gt;</span>漢 <span class="hljs-tag">&lt;<span class="hljs-name">rt</span>&gt;</span>かん<span class="hljs-tag">&lt;/<span class="hljs-name">rt</span>&gt;</span> 字 <span class="hljs-tag">&lt;<span class="hljs-name">rt</span>&gt;</span>じ<span class="hljs-tag">&lt;/<span class="hljs-name">rt</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">ruby</span>&gt;</span>
</code></pre>
<p>This shows the Japanese kanji characters <em>漢字</em> with their pronunciation (furigana) displayed above or beside them as <em>かんじ</em> (kanji).</p>
<center>
<ruby>漢 <rt>かん</rt> 字 <rt>じ</rt></ruby>
</center>

<h3 id="heading-the-importance-of-the-and-sub-elements">The Importance of the <code>&lt;rp&gt;</code> and <code>&lt;rt&gt;</code> Sub-Elements</h3>
<p>The <code>&lt;rt&gt;</code> element is used inside the <code>&lt;ruby&gt;</code> tag to define the annotation (like pronunciation) for the main text. It stands for "ruby text."</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">ruby</span>&gt;</span>漢 <span class="hljs-tag">&lt;<span class="hljs-name">rt</span>&gt;</span>かん<span class="hljs-tag">&lt;/<span class="hljs-name">rt</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">ruby</span>&gt;</span>
</code></pre>
<p>This will display <em>漢</em> with <em>かん</em> (kan) above it as the annotation.</p>
<center>
<ruby>漢 <rt>かん</rt></ruby>
</center>

<p>The <code>&lt;rp&gt;</code> element, short for "ruby parenthesis," is used as a fallback for browsers that don’t support the <code>&lt;ruby&gt;</code> tag. It wraps extra characters, such as parentheses, around the ruby text to show that it’s an annotation:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">ruby</span>&gt;</span>漢 <span class="hljs-tag">&lt;<span class="hljs-name">rp</span>&gt;</span>(<span class="hljs-tag">&lt;/<span class="hljs-name">rp</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">rt</span>&gt;</span>かん<span class="hljs-tag">&lt;/<span class="hljs-name">rt</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">rp</span>&gt;</span>)<span class="hljs-tag">&lt;/<span class="hljs-name">rp</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">ruby</span>&gt;</span>
</code></pre>
<p>If the browser doesn’t support ruby annotations, it will display the pronunciation inside parentheses, like this:<br><em>漢 (かん)</em>.</p>
<h3 id="heading-practical-examples-ruby-annotations-for-language-learning">Practical Examples: Ruby Annotations for Language Learning</h3>
<p>The <code>&lt;ruby&gt;</code> tag is a helpful tool for language learners. It can display the pronunciation for unfamiliar words or characters directly above or beside them. This makes it easier for beginners to read and learn new vocabulary.</p>
<p>For example, let’s say you want to help someone learn the Chinese word for "person":</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">ruby</span>&gt;</span>人 <span class="hljs-tag">&lt;<span class="hljs-name">rt</span>&gt;</span>rén<span class="hljs-tag">&lt;/<span class="hljs-name">rt</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">ruby</span>&gt;</span>
</code></pre>
<p>This would show <em>人</em> with the pronunciation <em>rén</em> above it.</p>
<center>
<ruby>人 <rt>rén</rt></ruby>
</center>

<p>For longer sentences:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">ruby</span>&gt;</span>我 <span class="hljs-tag">&lt;<span class="hljs-name">rt</span>&gt;</span>wǒ<span class="hljs-tag">&lt;/<span class="hljs-name">rt</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">ruby</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">ruby</span>&gt;</span>是 <span class="hljs-tag">&lt;<span class="hljs-name">rt</span>&gt;</span>shì<span class="hljs-tag">&lt;/<span class="hljs-name">rt</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">ruby</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">ruby</span>&gt;</span>学生 <span class="hljs-tag">&lt;<span class="hljs-name">rt</span>&gt;</span>xuéshēng<span class="hljs-tag">&lt;/<span class="hljs-name">rt</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">ruby</span>&gt;</span>.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>This helps students see both the characters and the correct pronunciation.</p>
<center>
<p><ruby>我 <rt>wǒ</rt></ruby> <ruby>是 <rt>shì</rt></ruby> <ruby>学生 <rt>xuéshēng</rt></ruby>.</p>
</center>

<h3 id="heading-cross-browser-compatibility-and-rendering-considerations">Cross-Browser Compatibility and Rendering Considerations</h3>
<p>The <code>&lt;ruby&gt;</code> tag is supported across most modern browsers, but older ones might not render it correctly. That's where the <code>&lt;rp&gt;</code> element comes in handy, making sure the annotations are still readable if the browser doesn’t support ruby text.</p>
<p>For accessibility, make sure the annotations have enough space around them so that they are easy to read. You can also use CSS to adjust how the annotations look:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">ruby</span> <span class="hljs-selector-tag">rt</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">0.75em</span>;
  <span class="hljs-attribute">color</span>: gray;
}
</code></pre>
<p>This will make the ruby text smaller and in a different color to keep it visually separate from the main content.</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/YzmNWLb" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p>Using <code>&lt;ruby&gt;</code> is a great way to improve readability for language learners or readers unfamiliar with certain scripts. Just remember to check browser support and add fallbacks for a better user experience across different devices.</p>
<h2 id="heading-the-tag-semantic-time-and-date">The <code>&lt;time&gt;</code> Tag: Semantic Time and Date</h2>
<p>The <code>&lt;time&gt;</code> tag is used to mark dates or times in a machine-readable format. It helps search engines, browsers, and other tools recognize time-related information more clearly, which is useful for improving visibility in search results or for better data parsing.</p>
<h3 id="heading-using-the-tag-for-machine-readable-dates-and-times">Using the <code>&lt;time&gt;</code> Tag for Machine-Readable Dates and Times</h3>
<p>When you use the <code>&lt;time&gt;</code> tag, it allows you to provide dates or times that are easy for both people and computers to read. This is especially helpful on blogs, news articles, or event pages.</p>
<p>Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Published on <span class="hljs-tag">&lt;<span class="hljs-name">time</span> <span class="hljs-attr">datetime</span>=<span class="hljs-string">"2024-10-01"</span>&gt;</span>October 1, 2024<span class="hljs-tag">&lt;/<span class="hljs-name">time</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>The text "October 1, 2024" is what users will see, but the <code>datetime</code> attribute provides a machine-readable version of the date. Search engines can now easily interpret this date.</p>
<center>
<p>Published on <time>October 1, 2024</time></p>
</center>

<p>You can also use the <code>&lt;time&gt;</code> tag to display times:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The event starts at <span class="hljs-tag">&lt;<span class="hljs-name">time</span> <span class="hljs-attr">datetime</span>=<span class="hljs-string">"13:00"</span>&gt;</span>1:00 PM<span class="hljs-tag">&lt;/<span class="hljs-name">time</span>&gt;</span>.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>This makes it clear to both users and machines when the event takes place.</p>
<center>
<p>The event starts at <time>1:00 PM</time>.</p>
</center>

<h3 id="heading-how-improves-seo-and-data-parsing-for-event-details">How <code>&lt;time&gt;</code> Improves SEO and Data Parsing for Event Details</h3>
<p>Search engines rely on structured data to understand content better. The <code>&lt;time&gt;</code> tag gives them a clearer idea of when events, publications, or deadlines happen, improving the relevance of search results. For example, search engines can better display the publication date of a blog post or the time of an event.</p>
<p>For an event page, the following example provides both human-friendly and machine-friendly time information:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Join us for the workshop on <span class="hljs-tag">&lt;<span class="hljs-name">time</span> <span class="hljs-attr">datetime</span>=<span class="hljs-string">"2024-12-15"</span>&gt;</span>December 15, 2024<span class="hljs-tag">&lt;/<span class="hljs-name">time</span>&gt;</span> at <span class="hljs-tag">&lt;<span class="hljs-name">time</span> <span class="hljs-attr">datetime</span>=<span class="hljs-string">"15:30"</span>&gt;</span>3:30 PM<span class="hljs-tag">&lt;/<span class="hljs-name">time</span>&gt;</span>.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>Search engines and web crawlers can then extract this data and use it to create rich snippets in search results, helping the event get noticed.</p>
<h3 id="heading-examples-of-usage-in-articles-blogs-and-event-pages">Examples of Usage in Articles, Blogs, and Event Pages</h3>
<p>Here are some practical examples of how you can use the <code>&lt;time&gt;</code> tag:</p>
<ol>
<li><p><strong>Blog posts</strong>: You can display when an article was published or last updated:</p>
<pre><code class="lang-html"> <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Last updated on <span class="hljs-tag">&lt;<span class="hljs-name">time</span> <span class="hljs-attr">datetime</span>=<span class="hljs-string">"2024-09-28"</span>&gt;</span>September 28, 2024<span class="hljs-tag">&lt;/<span class="hljs-name">time</span>&gt;</span>.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
</li>
<li><p><strong>Event listings</strong>: Event websites can use the <code>&lt;time&gt;</code> tag to list when an event will take place:</p>
<pre><code class="lang-html"> <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Our next meetup will be on <span class="hljs-tag">&lt;<span class="hljs-name">time</span> <span class="hljs-attr">datetime</span>=<span class="hljs-string">"2024-11-10"</span>&gt;</span>November 10, 2024<span class="hljs-tag">&lt;/<span class="hljs-name">time</span>&gt;</span> at <span class="hljs-tag">&lt;<span class="hljs-name">time</span> <span class="hljs-attr">datetime</span>=<span class="hljs-string">"18:00"</span>&gt;</span>6:00 PM<span class="hljs-tag">&lt;/<span class="hljs-name">time</span>&gt;</span>.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
</li>
<li><p><strong>Deadlines</strong>: When presenting important deadlines, use the <code>&lt;time&gt;</code> tag for clarity:</p>
<pre><code class="lang-html"> <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Submit your application before <span class="hljs-tag">&lt;<span class="hljs-name">time</span> <span class="hljs-attr">datetime</span>=<span class="hljs-string">"2024-10-30T23:59"</span>&gt;</span>October 30, 2024, 11:59 PM<span class="hljs-tag">&lt;/<span class="hljs-name">time</span>&gt;</span>.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
</li>
</ol>
<p>In all of these examples, the <code>datetime</code> attribute ensures that computers can read the time information correctly, while users see a more readable version.</p>
<h3 id="heading-browser-support-and-accessibility">Browser Support and Accessibility</h3>
<p>The <code>&lt;time&gt;</code> tag is widely supported across modern browsers. It also improves accessibility because screen readers can interpret the date and time more accurately, giving a better experience for users with disabilities.</p>
<h2 id="heading-the-tag-bi-directional-text-isolation">The <code>&lt;bdi&gt;</code> Tag: Bi-Directional Text Isolation</h2>
<p>The <code>&lt;bdi&gt;</code> tag stands for "bi-directional isolation" and is used to prevent text direction problems on multilingual websites. This tag is especially helpful when working with content that includes both left-to-right (LTR) and right-to-left (RTL) languages.</p>
<h3 id="heading-tags-role-in-multilingual-sites"><code>&lt;bdi&gt;</code> Tag’s Role in Multilingual Sites</h3>
<p>When mixing languages with different text directions, like English (LTR) and Arabic (RTL), the natural flow of text can sometimes get messy. The <code>&lt;bdi&gt;</code> tag helps keep the layout of the text clean, ensuring that each portion of text displays correctly, no matter the direction of the language.</p>
<p>For example, if you want to display user input (like a username) next to other text, and you don’t know which language the username will be in, you can use <code>&lt;bdi&gt;</code> to make sure it doesn’t mess with the flow.</p>
<h3 id="heading-how-to-use-for-preventing-text-direction-issues">How to Use <code>&lt;bdi&gt;</code> for Preventing Text Direction Issues</h3>
<p>The <code>&lt;bdi&gt;</code> tag wraps around the part of the text you want to isolate, and it prevents the text direction from being affected by surrounding content.</p>
<p>Here’s a simple example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>User <span class="hljs-tag">&lt;<span class="hljs-name">bdi</span>&gt;</span>اسم<span class="hljs-tag">&lt;/<span class="hljs-name">bdi</span>&gt;</span> has logged in.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>If the username is in Arabic (which reads RTL), the <code>&lt;bdi&gt;</code> tag ensures the rest of the sentence (which is in English and reads LTR) doesn’t get disrupted. Without the <code>&lt;bdi&gt;</code> tag, the sentence could display incorrectly due to the mix of text directions.</p>
<p>Another example with numbers:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Invoice number: <span class="hljs-tag">&lt;<span class="hljs-name">bdi</span>&gt;</span>#1234<span class="hljs-tag">&lt;/<span class="hljs-name">bdi</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>If the invoice number includes text or numbers in different directions, the <code>&lt;bdi&gt;</code> tag makes sure the formatting stays correct.</p>
<h3 id="heading-examples-of">Examples of <code>&lt;bdi&gt;</code></h3>
<p>The <code>&lt;bdi&gt;</code> tag is commonly used in multilingual applications, user-generated content platforms, and websites that handle multiple languages at once. For instance, websites that allow users to input data, such as names or addresses, might use <code>&lt;bdi&gt;</code> to ensure proper text alignment.</p>
<p>Here’s an example on a forum:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">bdi</span>&gt;</span>مستخدم<span class="hljs-tag">&lt;/<span class="hljs-name">bdi</span>&gt;</span> liked your post!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>Without <code>&lt;bdi&gt;</code>, the text might display awkwardly, but with it, both the Arabic username and the English text display properly.</p>
<h3 id="heading-browser-compatibility">Browser Compatibility</h3>
<p>The <code>&lt;bdi&gt;</code> tag is supported in all modern browsers, including Chrome, Firefox, Safari, and Edge. It’s a lightweight solution, doesn’t require special styling, and helps keep your content layout neat when dealing with multilingual text.</p>
<h2 id="heading-the-tag-defining-terms">The <code>&lt;dfn&gt;</code> Tag: Defining Terms</h2>
<p>The <code>&lt;dfn&gt;</code> tag is used to mark the first instance of a term that is being defined within a webpage. It helps readers quickly recognize that a particular word or phrase is a definition, improving the clarity of your content, especially in technical writing.</p>
<h3 id="heading-how-to-use-for-marking-definitions">How to Use <code>&lt;dfn&gt;</code> for Marking Definitions</h3>
<p>The <code>&lt;dfn&gt;</code> tag is simple to use. You wrap it around the word or phrase that you want to define. Typically, the term appears near the explanation of its meaning.</p>
<p>Example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The <span class="hljs-tag">&lt;<span class="hljs-name">dfn</span>&gt;</span>DOM<span class="hljs-tag">&lt;/<span class="hljs-name">dfn</span>&gt;</span> (Document Object Model) is a programming interface for web documents.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>Here, the <code>&lt;dfn&gt;</code> tag highlights that "DOM" is the term being defined.</p>
<center>
<p>The <dfn>DOM</dfn> (Document Object Model) is a programming interface for web documents.</p>
</center>

<h3 id="heading-best-practices-for-providing-in-article-explanations">Best Practices for Providing In-Article Explanations</h3>
<p>When using the <code>&lt;dfn&gt;</code> tag, make sure the term you are defining is followed closely by its explanation. This keeps things clear and helps readers connect the term with its meaning right away.</p>
<p>It's also a good idea to only use <code>&lt;dfn&gt;</code> the first time a term is introduced, as repeating it multiple times can confuse the reader.</p>
<p>For example, in a technical article about HTML:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The <span class="hljs-tag">&lt;<span class="hljs-name">dfn</span>&gt;</span>API<span class="hljs-tag">&lt;/<span class="hljs-name">dfn</span>&gt;</span> (Application Programming Interface) allows different software applications to communicate with each other. Once defined, an API can simplify many web development tasks.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>In this case, "API" is defined when it's first mentioned, and later uses of "API" don’t need the <code>&lt;dfn&gt;</code> tag anymore.</p>
<h3 id="heading-how-improves-the-clarity-of-technical-content">How <code>&lt;dfn&gt;</code> Improves the Clarity of Technical Content</h3>
<p>Using the <code>&lt;dfn&gt;</code> tag in technical writing is a great way to make content easier to follow. It clearly signals to readers when you're introducing a new term, which is especially useful when explaining complex ideas. This helps improve readability and allows users to grasp key concepts faster.</p>
<p>By marking definitions with <code>&lt;dfn&gt;</code>, search engines and other tools may also be able to better interpret your content, making it more accessible. For example, technical glossaries or educational websites can use <code>&lt;dfn&gt;</code> to make their terms stand out.</p>
<h3 id="heading-example-of">Example of <code>&lt;dfn&gt;</code></h3>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The <span class="hljs-tag">&lt;<span class="hljs-name">dfn</span>&gt;</span>URL<span class="hljs-tag">&lt;/<span class="hljs-name">dfn</span>&gt;</span> (Uniform Resource Locator) is the address used to access a resource on the web.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>In this sentence, the reader is introduced to the term "URL," followed by a clear explanation. This method of introducing terms with the <code>&lt;dfn&gt;</code> tag helps make technical content much easier to read and understand, especially for those unfamiliar with the topic.</p>
<h2 id="heading-the-tag-line-break-opportunities">The <code>&lt;wbr&gt;</code> Tag: Line Break Opportunities</h2>
<p>The <code>&lt;wbr&gt;</code> tag is used to suggest where a word or URL can be split to create a line break if needed. This is useful when dealing with long words, URLs, or any text that could break the layout of a webpage.</p>
<h3 id="heading-what-the-tag-is-and-why-its-essential-for-long-words-or-urls">What the <code>&lt;wbr&gt;</code> Tag Is and Why it’s Essential for Long Words or URLs</h3>
<p>Sometimes, long words or URLs can mess up the design of a webpage by causing horizontal scrolling or breaking the layout. The <code>&lt;wbr&gt;</code> tag gives the browser a hint on where to break the word, but only if necessary. This helps keep the text readable and prevents overflow.</p>
<p>For example, if you have a long URL, you can place the <code>&lt;wbr&gt;</code> tag to tell the browser where it can break the text:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Visit our website at https://www.example<span class="hljs-tag">&lt;<span class="hljs-name">wbr</span>&gt;</span>.com/super/long-url-that-might-break-layout<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>If the browser needs to break the URL, it will do so after the <code>&lt;wbr&gt;</code>, ensuring the design remains intact.</p>
<h3 id="heading-best-practices-for-controlling-word-wrapping-and-text-overflow">Best Practices for Controlling Word Wrapping and Text Overflow</h3>
<p>The <code>&lt;wbr&gt;</code> tag should be used in places where text might cause overflow issues, such as long technical terms, email addresses, or URLs. But don’t overuse it, as unnecessary breaks can make the text harder to read.</p>
<p>Here’s another example with a long word:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This word is too long: anti<span class="hljs-tag">&lt;<span class="hljs-name">wbr</span>&gt;</span>disestablishmentarianism.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>If the word gets too long for the line, the browser will split it after "anti-" without affecting readability.</p>
<p>In combination with CSS, you can also control word wrapping and text overflow for better results:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">word-wrap</span>: break-word;
  <span class="hljs-attribute">overflow-wrap</span>: break-word;
}
</code></pre>
<p>This CSS ensures that the text will wrap neatly when necessary, and using <code>&lt;wbr&gt;</code> can give more control over where those breaks happen.</p>
<h3 id="heading-browser-support-for-and-potential-challenges">Browser Support for <code>&lt;wr&gt;</code> and Potential Challenges</h3>
<p>The <code>&lt;wbr&gt;</code> tag is supported in all major browsers, including Chrome, Firefox, Safari, and Edge. It’s lightweight and doesn’t need any special styling to work.</p>
<p>But one thing to watch for is that overuse of the tag can make text breaks appear unnatural if the content is resized or viewed on different screen sizes.</p>
<p>For example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Contact us at longemail<span class="hljs-tag">&lt;<span class="hljs-name">wbr</span>&gt;</span>@example<span class="hljs-tag">&lt;<span class="hljs-name">wbr</span>&gt;</span>.com for more information.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>In this case, you can avoid long email addresses causing layout problems, but the email might appear broken at different places depending on the screen width.</p>
<p>Use <code>&lt;wbr&gt;</code> when you anticipate long strings of text that may not naturally break, keeping your design clean and functional across devices.</p>
<h2 id="heading-the-tag-inserted-text">The <code>&lt;ins&gt;</code> Tag: Inserted Text</h2>
<p>The <code>&lt;ins&gt;</code> tag is used to show text that has been added to a document. This is often helpful when tracking edits, updates, or changes in documents. It also comes with a default underline to highlight the new content.</p>
<h3 id="heading-what-is-the-tag-and-how-does-it-compare-to-the-tag">What Is the <code>&lt;ins&gt;</code> Tag and How Does it Compare to the <code>&lt;s&gt;</code> Tag?</h3>
<p>The <code>&lt;ins&gt;</code> tag is designed for marking inserted content, while the <code>&lt;s&gt;</code> tag is used for text that has been removed or is no longer relevant. Both tags are useful when you need to show changes in a document, like updates or revisions.</p>
<p>Example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is the <span class="hljs-tag">&lt;<span class="hljs-name">ins</span>&gt;</span>new text<span class="hljs-tag">&lt;/<span class="hljs-name">ins</span>&gt;</span> that was added.<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>This is the <span class="hljs-tag">&lt;<span class="hljs-name">s</span>&gt;</span>old text<span class="hljs-tag">&lt;/<span class="hljs-name">s</span>&gt;</span> that is no longer valid.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>Here, the <code>&lt;ins&gt;</code> tag highlights what has been added, and the <code>&lt;s&gt;</code> tag shows what has been crossed out as outdated.</p>
<center>
<p>This is the new text that was added.</p>
<p>This is the <s>old text</s> that is no longer valid.</p>
</center>

<h3 id="heading-usage-in-tracking-document-edits-or-versioning">Usage in Tracking Document Edits or Versioning</h3>
<p>The <code>&lt;ins&gt;</code> tag is commonly used when managing documents that need version control or where edits should be visible. For example, you can use it in collaborative writing platforms or legal documents to show which parts have been added.</p>
<p>Example of a document with changes:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The contract was updated to include <span class="hljs-tag">&lt;<span class="hljs-name">ins</span>&gt;</span>an extra clause<span class="hljs-tag">&lt;/<span class="hljs-name">ins</span>&gt;</span> on data privacy.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>This makes it clear to the reader that the section about "data privacy" was recently added.</p>
<p>In software development or content management, you might use the <code>&lt;ins&gt;</code> tag to show text that has been newly introduced in version-controlled files, making it easier to track edits and revisions over time.</p>
<h3 id="heading-styling-options-to-emphasize-changes">Styling Options to Emphasize Changes</h3>
<p>The default appearance of the <code>&lt;ins&gt;</code> tag is underlined, but you can customize it using CSS for better emphasis, especially if you want the changes to stand out more.</p>
<p>Here’s how you can style the <code>&lt;ins&gt;</code> tag with different visual effects:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">ins</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#d4edda</span>;
  <span class="hljs-attribute">color</span>: green;
  <span class="hljs-attribute">text-decoration</span>: none; <span class="hljs-comment">/* Removes default underline */</span>
}
</code></pre>
<p>This will give the inserted text a green color and a light green background, making it more noticeable.</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/wvVgWRz" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p>You can also add different styles like a bold font or a border:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">ins</span> {
  <span class="hljs-attribute">font-weight</span>: bold;
  <span class="hljs-attribute">border-bottom</span>: <span class="hljs-number">2px</span> solid green;
}
</code></pre>
<p>These styling options make it easier for users to identify what has been added or changed, improving the readability and transparency of document edits.</p>
<p>Overall, the <code>&lt;ins&gt;</code> tag is a simple but effective way to track inserted content, making it very useful for both technical documents and collaborative platforms where revisions need to be clearly visible.</p>
<h2 id="heading-the-tag-deleted-text">The <code>&lt;del&gt;</code> Tag: Deleted Text</h2>
<p>The <code>&lt;del&gt;</code> tag is used to show text that has been deleted or removed from a document. This tag strikes through the text by default, making it easy to identify what has been removed. It’s especially helpful in situations where tracking changes or revisions is necessary.</p>
<h3 id="heading-purpose-and-usage-of-the-tag-for-strikethrough-text">Purpose and Usage of the <code>&lt;del&gt;</code> Tag for Strikethrough Text</h3>
<p>The main job of the <code>&lt;del&gt;</code> tag is to visually show that some content has been removed. It’s common in documents, articles, or code where changes need to be made visible to the reader. The deleted text will usually have a strikethrough, indicating that it’s no longer relevant or valid.</p>
<p>Example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This product costs <span class="hljs-tag">&lt;<span class="hljs-name">del</span>&gt;</span>$50<span class="hljs-tag">&lt;/<span class="hljs-name">del</span>&gt;</span> $40 now.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>In this example, the price change is clear. The old price ($50) is struck through, and the new price ($40) follows right after.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728749690070/6c971036-90b9-4bcb-9d74-1c13bd770750.png" alt="6c971036-90b9-4bcb-9d74-1c13bd770750" class="image--center mx-auto" width="322" height="55" loading="lazy"></p>
<h3 id="heading-how-it-can-be-combined-with-for-tracking-revisions">How It Can Be Combined With <code>&lt;ins&gt;</code> for Tracking Revisions</h3>
<p>The <code>&lt;del&gt;</code> tag can be paired with the <code>&lt;ins&gt;</code> tag to show both removed and newly added content, making it perfect for tracking edits or revisions. This is very useful in collaborative writing, legal documents, or any situation where changes must be recorded clearly.</p>
<p>Example of tracking revisions:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The meeting has been moved <span class="hljs-tag">&lt;<span class="hljs-name">del</span>&gt;</span>Monday<span class="hljs-tag">&lt;/<span class="hljs-name">del</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">ins</span>&gt;</span>Tuesday<span class="hljs-tag">&lt;/<span class="hljs-name">ins</span>&gt;</span>.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>Here, it’s easy to see that "Monday" was replaced with "Tuesday," and the reader knows exactly what changed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1728749828530/ee3f84d5-9e56-4f27-8ce3-6eac5a79a144.png" alt="ee3f84d5-9e56-4f27-8ce3-6eac5a79a144" class="image--center mx-auto" width="466" height="58" loading="lazy"></p>
<h3 id="heading-best-practices-for-displaying-and-styling-deleted-content">Best Practices for Displaying and Styling Deleted Content</h3>
<p>By default, the <code>&lt;del&gt;</code> tag applies a strikethrough to the text, but you can style it further with CSS to make it more noticeable or match your design needs.</p>
<p>Here’s an example of customizing the appearance of deleted text:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">del</span> {
  <span class="hljs-attribute">color</span>: red;
  <span class="hljs-attribute">text-decoration</span>: line-through;
}
</code></pre>
<p>This makes deleted text appear red, drawing more attention to it. You can also combine it with additional formatting, like fading out the text:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">del</span> {
  <span class="hljs-attribute">color</span>: gray;
  <span class="hljs-attribute">opacity</span>: <span class="hljs-number">0.7</span>;
}
</code></pre>
<p>This style reduces the emphasis on deleted content, making it less distracting but still visible to readers.</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/xxvgWNQ" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p>The <code>&lt;del&gt;</code> tag provides a simple and effective way to track and display changes, especially when combined with the <code>&lt;ins&gt;</code> tag. It’s essential for keeping documents transparent and clear for anyone reviewing edits or updates.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Making use of these unique HTML elements expands what’s possible on the web, which helps to create more meaningful and accessible content. Tags like <code>&lt;q&gt;</code>, <code>&lt;s&gt;</code>, <code>&lt;mark&gt;</code>, <code>&lt;ruby&gt;</code>, <code>&lt;time&gt;</code>, <code>&lt;bdi&gt;</code>, <code>&lt;dfn&gt;</code>, <code>&lt;wbr&gt;</code>, <code>&lt;ins&gt;</code>, and <code>&lt;del&gt;</code> each bring their own advantages for specific tasks. These elements do more than just style text; they add context, enhance user experiences, and improve document structure.</p>
<p>Using these tags correctly not only makes your web pages clearer but also boosts compatibility across devices and search engines. As you apply these elements, think about how each one serves both the visual presentation and the information structure. They offer simple but powerful ways to make websites richer and easier to understand while benefiting a wide range of users.</p>
<p>If you have any questions or suggestions, feel free to reach out on <a target="_blank" href="https://ng.linkedin.com/in/joan-ayebola">LinkedIn</a>. If you enjoyed this content, consider <a target="_blank" href="https://www.buymeacoffee.com/joanayebola">buying me a coffee</a> to support the creation of more developer-friendly contents.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn HTTP Methods like GET, POST, and DELETE – a Handbook with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ When you interact with websites or apps, a lot happens behind the scenes. A key part of this process is how your browser or app talks to a server. HTTPS methods define what action needs to happen – it could be fetching data, sending information, or m... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-http-methods-like-get-post-and-delete-a-handbook-with-code-examples/</link>
                <guid isPermaLink="false">66fd572dc6e14d69030944f7</guid>
                
                    <category>
                        <![CDATA[ httpmethods ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ http ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Wed, 02 Oct 2024 14:22:37 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727797253693/e0d1ebfc-2071-4f2e-8e8b-d47c8f55844e.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When you interact with websites or apps, a lot happens behind the scenes. A key part of this process is how your browser or app talks to a server. HTTPS methods define what action needs to happen – it could be fetching data, sending information, or making changes to existing content.</p>
<p>Each method serves a specific purpose to keep web communication clear, secure, and organized.</p>
<p>In this article, we will break down the most common HTTPS methods and explain how they function to make online interactions work smoothly.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-get-method">GET Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-post-method">POST Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-put-method">PUT Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-patch-method">PATCH Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-delete-method">DELETE Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-head-method">HEAD Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-options-method">OPTIONS Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-trace-method">TRACE Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-connect-method">CONNECT Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-get-method">GET Method</h2>
<p>The GET method is one of the most common HTTP methods and is used to request data from a server. Think of it as asking for information without changing anything.</p>
<p>When you visit a webpage, your browser sends a GET request to the server asking for the content of the page. The server then responds with the data (such as HTML, images, or other files) that the browser displays.</p>
<p>One important thing about GET is that it doesn't make any changes to the data. It simply "reads" or retrieves the information. For example, when you browse through social media or search for products online, the app or website uses GET to display data without altering it.</p>
<p>Another key point is that GET requests send parameters in the URL itself. This means any data you're asking for is visible in the browser's address bar. For example, if you're searching for a product on an online store, the search term is included in the URL.</p>
<h3 id="heading-example-of-a-get-request">Example of a GET Request</h3>
<p>Here’s a simple example of a GET request in JavaScript using the Fetch API:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://api.example.com/products?category=shoes'</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
</code></pre>
<p>In this example, the GET request is made to the URL <a target="_blank" href="https://api.example.com/products"><code>https://api.example.com/products</code></a> with a query parameter <code>category=shoes</code>, asking the server to return products in the shoes category.</p>
<h3 id="heading-use-cases-of-the-get-method">Use Cases of the GET Method</h3>
<p>GET is mainly used to fetch information, and there are many common scenarios where it's applied:</p>
<ol>
<li><p><strong>Loading a Webpage</strong>: Every time you type a URL into your browser or click a link, you're making a GET request. The browser asks the server for the webpage, and the server sends back the content to display.</p>
<ul>
<li>Example: <code>GET /index.html HTTP/1.1</code></li>
</ul>
</li>
<li><p><strong>Fetching Data from APIs</strong>: When developers build applications, they often use APIs (Application Programming Interfaces) to get data from external servers. For instance, a weather app uses a GET request to fetch the current temperature from a weather API.</p>
<ul>
<li>Example:</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    fetch(<span class="hljs-string">'https://api.weather.com/current?city=Lagos'</span>)
       .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
       .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data));
</code></pre>
<ol start="3">
<li><p><strong>Search Queries</strong>: When you search for something on Google or other search engines, a GET request is made. The search term you entered is included in the URL, and the server returns a list of matching results.</p>
<ul>
<li>Example: <code>GET /search?q=JavaScript</code></li>
</ul>
</li>
<li><p><strong>Retrieving Files</strong>: Whether you're downloading an image, viewing a PDF, or playing a video, GET is used to fetch those files from a server.</p>
<ul>
<li>Example: <code>GET /files/image.jpg</code></li>
</ul>
</li>
</ol>
<h3 id="heading-best-practices-for-get-requests">Best Practices for GET Requests</h3>
<p>To use GET requests effectively, it's important to follow some good practices to ensure smooth and secure data handling:</p>
<ol>
<li><p><strong>Use GET Only for Retrieving Data</strong>: GET requests are meant to fetch data, not to send sensitive information like passwords or personal data. Since the parameters in a GET request are included in the URL, anyone can see them. For example, if you're logging into a website, you shouldn't use GET to send your password, because it would show up in the URL.</p>
<ul>
<li>Example of what <strong>not</strong> to do:</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    fetch(<span class="hljs-string">'https://example.com/login?username=john&amp;password=secret'</span>);
</code></pre>
<ol start="2">
<li><p><strong>Keep URLs Short and Clean</strong>: Since GET requests include data in the URL, long URLs can become problematic. There is also a limit to how much data can be included in a GET request URL (depending on the browser and server), so avoid putting too much information there. If you need to send a lot of data, consider using a POST request instead.</p>
</li>
<li><p><strong>Enable Caching for Performance</strong>: GET requests are often cached by browsers, meaning the browser can store the response and reuse it without contacting the server again. This improves performance, especially for static content that doesn’t change often, like images or style sheets. To take advantage of this, ensure your server sends proper cache-control headers, so frequently requested data can be loaded faster.</p>
<ul>
<li>Example of setting cache headers:</li>
</ul>
</li>
</ol>
<pre><code class="lang-http">    Cache-Control: max-age=3600
</code></pre>
<ol start="4">
<li><p><strong>Avoid Making GET Requests for Actions That Change Data</strong>: Since GET is a "safe" method, it should only be used for actions that don't modify data. If you want to create, update, or delete data, use methods like POST, PUT, or DELETE. For instance, if you accidentally use GET to delete a resource, someone could remove it just by clicking a link or refreshing the page, which is not safe.</p>
<ul>
<li>Example of <strong>not</strong> using GET for deletion:</li>
</ul>
</li>
</ol>
<pre><code class="lang-http">    GET /delete/user/123
</code></pre>
<ol start="5">
<li><strong>Be Cautious with Sensitive Data</strong>: Since GET requests are part of the URL, they can be logged or saved in a browser’s history. Avoid sending sensitive information like passwords, credit card details, or private data in a GET request. Always use methods like POST for handling such information, which keeps it hidden.</li>
</ol>
<h2 id="heading-post-method">POST Method</h2>
<p>The POST method is used to send data to a server. Unlike the GET method, which only retrieves data, POST allows you to submit information that the server can use to process or store. POST is commonly used in forms, where users input data such as usernames, passwords, or contact details.</p>
<p>When a POST request is made, the data is sent in the body of the request rather than in the URL. This makes POST ideal for sending larger or more sensitive information, such as passwords, because the data is hidden and doesn’t appear in the browser's address bar.</p>
<p>For example, when you sign up for a website or submit a comment on a blog, the POST method is used to send your information to the server, which processes it and stores it in a database.</p>
<h3 id="heading-example-of-a-post-request">Example of a POST Request</h3>
<p>Here’s an example of a POST request using the Fetch API to send form data to a server:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> formData = {
  <span class="hljs-attr">username</span>: <span class="hljs-string">'john_doe'</span>,
  <span class="hljs-attr">password</span>: <span class="hljs-string">'mypassword123'</span>
};

fetch(<span class="hljs-string">'https://example.com/login'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(formData)
})
.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
.then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Success:'</span>, data))
.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
</code></pre>
<p>In this example, the POST request sends <code>username</code> and <code>password</code> as JSON data in the body of the request, making it a secure way to handle sensitive information like passwords.</p>
<h3 id="heading-differences-between-get-and-post">Differences Between GET and POST</h3>
<p>Although GET and POST are used to communicate with a server, they serve different purposes and handle data in different ways:</p>
<h4 id="heading-data-transmission">Data Transmission:</h4>
<ul>
<li><p><strong>GET</strong>: Data is included in the URL, making it visible in the address bar. This limits how much data can be sent.</p>
</li>
<li><p><strong>POST</strong>: Data is sent in the body of the request, which allows for sending larger amounts of information. This also keeps sensitive information hidden from the URL.</p>
</li>
</ul>
<h4 id="heading-purpose">Purpose:</h4>
<ul>
<li><p><strong>GET</strong>: Used for retrieving data. It doesn’t change or modify anything on the server.</p>
</li>
<li><p><strong>POST</strong>: Used to send data that may change or add to the server's resources, such as adding a new user to a database or submitting a form.</p>
</li>
</ul>
<h4 id="heading-caching">Caching:</h4>
<ul>
<li><p><strong>GET</strong>: GET requests can be cached. This means that the browser may save the response, making future requests faster.</p>
</li>
<li><p><strong>POST</strong>: POST requests are not cached, as they often involve new or updated data that shouldn't be reused.</p>
</li>
</ul>
<h4 id="heading-idempotence">Idempotence:</h4>
<ul>
<li><p><strong>GET</strong>: Sending the same GET request multiple times doesn’t change the result. It will return the same data every time.</p>
</li>
<li><p><strong>POST</strong>: Sending the same POST request multiple times may result in different outcomes. For example, submitting a form twice could create duplicate entries.</p>
</li>
</ul>
<h3 id="heading-common-scenarios-for-using-post">Common Scenarios for Using POST</h3>
<p>POST is ideal in situations where you need to send data to the server, often for processing or storage. Here are some common use cases:</p>
<ol>
<li><p><strong>Submitting Forms</strong>: Whenever you fill out and submit a form online, such as signing up for a newsletter or entering your details in a registration form, the POST method is used to send that information to the server. The server then processes the data, stores it, or performs another action based on it.</p>
<ul>
<li>Example:</li>
</ul>
</li>
</ol>
<pre><code class="lang-html">    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"https://example.com/register"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"POST"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Sign Up<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<ol start="2">
<li><p><strong>User Authentication</strong>: When you log in to a website using a username and password, POST is often used to send your credentials securely to the server. The server checks the information and grants access to your account if the credentials match.</p>
</li>
<li><p><strong>Uploading Files</strong>: POST is also used for uploading files, such as images, documents, or videos. Since the POST method allows sending large amounts of data, it’s perfect for uploading files that need to be processed or stored on the server.</p>
<ul>
<li>Example using a form for file uploads:</li>
</ul>
</li>
</ol>
<pre><code class="lang-html">    <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"https://example.com/upload"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"POST"</span> <span class="hljs-attr">enctype</span>=<span class="hljs-string">"multipart/form-data"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"file"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"file"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Upload File<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<ol start="4">
<li><p><strong>Creating New Resources</strong>: POST is often used in APIs to create new resources. For example, when you add a new product to an online store, the POST method is used to send the product details to the server, which adds the product to the store's database.</p>
<ul>
<li>Example of sending product data:</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> product = {
      <span class="hljs-attr">name</span>: <span class="hljs-string">'New Sneakers'</span>,
      <span class="hljs-attr">price</span>: <span class="hljs-number">59.99</span>,
      <span class="hljs-attr">category</span>: <span class="hljs-string">'Footwear'</span>
    };

    fetch(<span class="hljs-string">'https://example.com/api/products'</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">'POST'</span>,
      <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
      },
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(product)
    })
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
    .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Product added:'</span>, data));
</code></pre>
<ol start="5">
<li><p><strong>Sending Data to an API</strong>: POST is widely used in APIs when you need to send data that will be processed or stored. For example, an app that tracks your fitness progress may use POST to send your workout details to a server, where it’s stored and analyzed.</p>
</li>
<li><p><strong>Making Purchases Online</strong>: When you make an online purchase, POST is used to send the payment details to the server for processing. The server processes the transaction and updates the system with your order information.</p>
</li>
</ol>
<h2 id="heading-put-method">PUT Method</h2>
<p>The <strong>PUT</strong> method is used to update or replace an existing resource on the server. It sends data to the server and tells it to create a new resource if none exists or replace the current one if it does. The key idea with PUT is that you are telling the server exactly what the resource should look like.</p>
<p>For example, imagine a user profile on a website. If you use PUT to update your profile, the server will replace the entire profile with the new data you provide. Every part of the profile will match exactly what you send, so if some details are missing, they will be overwritten with the new data.</p>
<h3 id="heading-example-of-a-put-request">Example of a PUT Request</h3>
<p>Here’s an example of a PUT request using the Fetch API to update user data:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> updatedProfile = {
  <span class="hljs-attr">username</span>: <span class="hljs-string">'john_doe_updated'</span>,
  <span class="hljs-attr">email</span>: <span class="hljs-string">'john_updated@example.com'</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>
};

fetch(<span class="hljs-string">'https://example.com/users/123'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'PUT'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(updatedProfile)
})
.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
.then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Updated:'</span>, data))
.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
</code></pre>
<p>In this example, the PUT request updates the user profile with new data. The profile will be replaced with <code>username</code>, <code>email</code>, and <code>age</code> values. If any data is missing, such as <code>phoneNumber</code>, it will be removed from the profile.</p>
<h3 id="heading-when-to-use-put">When to Use PUT</h3>
<p>PUT is mainly used when you want to update or replace a resource with specific, complete data. Here are some common situations where PUT is appropriate:</p>
<ol>
<li><p><strong>Updating a Resource</strong>: When you need to make changes to an existing resource, PUT is used to send a new version of the entire resource. For example, updating a blog post, product details, or user information would require sending a complete replacement of the resource using PUT.</p>
<ul>
<li>Example:</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> updatedPost = {
      <span class="hljs-attr">title</span>: <span class="hljs-string">'New Title for My Blog'</span>,
      <span class="hljs-attr">content</span>: <span class="hljs-string">'Updated blog content here...'</span>,
      <span class="hljs-attr">author</span>: <span class="hljs-string">'John Doe'</span>
    };

    fetch(<span class="hljs-string">'https://example.com/blog/45'</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">'PUT'</span>,
      <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
      },
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(updatedPost)
    });
</code></pre>
<ol start="2">
<li><p><strong>Creating a Resource if None Exists</strong>: If you send a PUT request to a specific URL that doesn't have a resource yet, the server will create one using the data you provide. This is useful when you're working with resources that need to be fully defined upfront.</p>
<ul>
<li>Example of creating a product if it doesn’t exist:</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> newProduct = {
      <span class="hljs-attr">id</span>: <span class="hljs-number">101</span>,
      <span class="hljs-attr">name</span>: <span class="hljs-string">'New Sneakers'</span>,
      <span class="hljs-attr">price</span>: <span class="hljs-number">59.99</span>,
      <span class="hljs-attr">category</span>: <span class="hljs-string">'Footwear'</span>
    };

    fetch(<span class="hljs-string">'https://example.com/products/101'</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">'PUT'</span>,
      <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
      },
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(newProduct)
    });
</code></pre>
<ol start="3">
<li><p><strong>Working with APIs</strong>: When interacting with APIs, PUT is often used when you need to make updates to a resource like a user profile, product details, or any other structured data. For example, a to-do list app might allow you to use PUT to update an existing task with new information.</p>
<ul>
<li>Example of updating a task:</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> updatedTask = {
      <span class="hljs-attr">title</span>: <span class="hljs-string">'Updated Task Title'</span>,
      <span class="hljs-attr">completed</span>: <span class="hljs-literal">true</span>
    };

    fetch(<span class="hljs-string">'https://example.com/tasks/67'</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">'PUT'</span>,
      <span class="hljs-attr">headers</span>: {
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
      },
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(updatedTask)
    });
</code></pre>
<h3 id="heading-put-vs-post-key-differences">PUT vs. POST: Key Differences</h3>
<p>Though both PUT and POST can send data to a server, they have different purposes and behaviors:</p>
<h4 id="heading-purpose-1">Purpose:</h4>
<ul>
<li><p><strong>PUT</strong>: Primarily used for updating or replacing an existing resource. If the resource doesn’t exist, PUT can also create it.</p>
</li>
<li><p><strong>POST</strong>: Mainly used to create new resources or submit data that needs to be processed. POST doesn’t replace existing resources but adds new ones.</p>
</li>
</ul>
<h4 id="heading-data-handling">Data Handling:</h4>
<ul>
<li><p><strong>PUT</strong>: Replaces the entire resource with the new data. If a part of the resource is missing in the request, that part gets removed or replaced.</p>
</li>
<li><p><strong>POST</strong>: Adds or updates resources without replacing the entire thing. For example, when submitting a form, POST adds new data to the server without deleting what’s already there.</p>
</li>
</ul>
<h4 id="heading-idempotence-1">Idempotence:</h4>
<ul>
<li><p><strong>PUT</strong>: Is idempotent, so sending the same PUT request multiple times will always result in the same outcome. No matter how many times you update a resource using PUT, the result will be the same.</p>
</li>
<li><p><strong>POST</strong>: Is not idempotent, so submitting the same POST request multiple times could create duplicate resources or have different results.</p>
</li>
</ul>
<h4 id="heading-use-cases">Use Cases:</h4>
<ul>
<li><p><strong>PUT</strong>: Best used for updates and full replacements of resources. For instance, if you’re updating product details in an online store, PUT ensures that all the details are replaced with the new ones you send.</p>
</li>
<li><p><strong>POST</strong>: Suited for creating new entries or sending data that requires processing. For example, submitting an online order or filling out a contact form uses POST.</p>
</li>
</ul>
<h2 id="heading-patch-method">PATCH Method</h2>
<p>The <strong>PATCH</strong> method is used to make partial updates to a resource on the server. Unlike the PUT method, which replaces the entire resource, PATCH allows you to update specific parts of a resource without sending the complete data again. This makes PATCH ideal for scenarios where you only want to tweak certain details without affecting other parts of the resource.</p>
<p>For example, if you have a user profile and want to update only the phone number, PATCH enables you to send just the new phone number while leaving the rest of the profile unchanged. This approach is more efficient and reduces the risk of unintended data loss.</p>
<h3 id="heading-partial-updates-with-patch">Partial Updates with PATCH</h3>
<p>PATCH is designed for making targeted changes to a resource. Here’s how it works:</p>
<ul>
<li><p><strong>Targeted Changes</strong>: When you use PATCH, you specify only the fields you want to update. For instance, if a user updates their email address, you send a PATCH request containing just the new email, and everything else stays the same on the server.</p>
</li>
<li><p><strong>Efficiency</strong>: PATCH is more efficient than PUT because it allows you to send only the data that’s being changed. This can reduce bandwidth usage, especially when updating large resources where only a small part needs modification.</p>
</li>
<li><p><strong>Does Not Overwrite</strong>: Unlike PUT, PATCH does not replace the entire resource. It only updates the fields that are provided in the request, ensuring that other fields remain intact.</p>
</li>
</ul>
<h3 id="heading-example-of-a-patch-request">Example of a PATCH Request</h3>
<p>Here’s a basic example of how you might use the PATCH method to update a specific field, such as changing a user's email address:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> updatedEmail = {
  <span class="hljs-attr">email</span>: <span class="hljs-string">'new_email@example.com'</span>
};

fetch(<span class="hljs-string">'https://example.com/users/123'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'PATCH'</span>,
  <span class="hljs-attr">headers</span>: {
    <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>
  },
  <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(updatedEmail)
})
.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
.then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Email updated:'</span>, data))
.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
</code></pre>
<p>In this example, only the <code>email</code> field is being updated. The rest of the user profile, such as the username or address, remains unchanged.</p>
<h3 id="heading-when-to-use-patch-instead-of-put">When to Use PATCH Instead of PUT</h3>
<p>There are specific scenarios where PATCH is more appropriate than PUT:</p>
<ol>
<li><p><strong>Updating Specific Fields</strong>: If you need to update only a part of a resource, like changing a user’s email, adding a tag to a blog post, or modifying a single attribute, PATCH is a better choice. It allows you to send only the fields that need updating, making the request more efficient.</p>
<ul>
<li>Example: Updating a user's phone number.</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> updatedPhone = { <span class="hljs-attr">phoneNumber</span>: <span class="hljs-string">'123-456-7890'</span> };

    fetch(<span class="hljs-string">'https://example.com/users/123'</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">'PATCH'</span>,
      <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> },
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(updatedPhone)
    });
</code></pre>
<ol start="2">
<li><p><strong>Avoiding Unintended Data Loss</strong>: When using PUT, leaving out any fields could result in the server removing or overwriting those fields. PATCH avoids this risk by only updating the specific fields provided, ensuring no accidental data loss.</p>
<ul>
<li>Example: If you only want to update a user’s username but don’t want to overwrite other fields like their address or preferences, PATCH ensures only the username is updated.</li>
</ul>
</li>
<li><p><strong>Performance Considerations</strong>: PATCH is more efficient for large resources. For instance, if you're managing a database with extensive records and need to change a small portion, PATCH reduces the data sent to the server, improving performance and speeding up the process.</p>
<ul>
<li>Example: Updating the status of a large order without modifying the entire order details.</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> updatedStatus = { <span class="hljs-attr">status</span>: <span class="hljs-string">'shipped'</span> };

    fetch(<span class="hljs-string">'https://example.com/orders/987'</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">'PATCH'</span>,
      <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> },
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(updatedStatus)
    });
</code></pre>
<ol start="4">
<li><p><strong>Frequent Updates</strong>: In applications where data changes frequently, PATCH makes it easier to update specific parts of a resource without affecting the entire structure. For instance, in an e-commerce platform, users might regularly update their shipping address or payment method, and PATCH can handle those frequent changes without requiring the entire user profile to be re-sent.</p>
<ul>
<li>Example: Updating the delivery address for an order.</li>
</ul>
</li>
</ol>
<pre><code class="lang-javascript">    <span class="hljs-keyword">const</span> updatedAddress = {
      <span class="hljs-attr">shippingAddress</span>: <span class="hljs-string">'123 New Street, New City, Country'</span>
    };

    fetch(<span class="hljs-string">'https://example.com/orders/987'</span>, {
      <span class="hljs-attr">method</span>: <span class="hljs-string">'PATCH'</span>,
      <span class="hljs-attr">headers</span>: { <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span> },
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(updatedAddress)
    });
</code></pre>
<h3 id="heading-key-differences-between-put-and-patch">Key Differences Between PUT and PATCH</h3>
<p>Here’s a quick comparison of PATCH and PUT to clarify when each method is more appropriate:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>PUT</td><td>PATCH</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Purpose</strong></td><td>Replaces the entire resource.</td><td>Partially updates a resource.</td></tr>
<tr>
<td><strong>Data Handling</strong></td><td>Requires the entire resource to be sent.</td><td>Sends only the fields that need to be updated.</td></tr>
<tr>
<td><strong>Efficiency</strong></td><td>Less efficient for large resources.</td><td>More efficient for small, specific updates.</td></tr>
<tr>
<td><strong>Idempotence</strong></td><td>Idempotent (same result if repeated).</td><td>Not necessarily idempotent (depends on the request).</td></tr>
<tr>
<td><strong>Risk of Data Loss</strong></td><td>Can overwrite fields if data is missing.</td><td>Does not overwrite existing fields unless specified.</td></tr>
</tbody>
</table>
</div><p><strong>PATCH</strong> is particularly valuable when you want to make partial updates, avoid overwriting other data, and improve the efficiency of your requests.</p>
<h2 id="heading-delete-method">DELETE Method</h2>
<p>The DELETE method is used to remove a resource from the server. When a DELETE request is made, the server deletes the specified resource, meaning it’s no longer accessible or available. This method is used for tasks like deleting a user account, removing a product from an online store, or clearing old data from a database.</p>
<p>Unlike GET or POST, DELETE doesn’t require sending a body in the request—just the URL of the resource you want to remove is enough. For example, to delete a specific blog post, a DELETE request is sent to the URL of that post, and the server takes care of removing it.</p>
<h3 id="heading-how-delete-works">How DELETE Works</h3>
<p>To delete a resource, you typically only need to provide the URL of the resource you want to remove. Unlike POST or PUT requests, DELETE requests generally don’t require a body.</p>
<h4 id="heading-example">Example:</h4>
<p>If you want to delete a specific blog post, you can send a DELETE request to its URL:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://example.com/posts/123'</span>, {
  <span class="hljs-attr">method</span>: <span class="hljs-string">'DELETE'</span>
})
.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
.then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Resource deleted:'</span>, data))
.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
</code></pre>
<p>This tells the server to remove the blog post with ID <code>123</code>.</p>
<h3 id="heading-safely-using-delete">Safely Using DELETE</h3>
<p>DELETE requests can have a significant impact, so it’s important to use them carefully to avoid accidentally removing valuable data. Below are some key considerations for safely handling DELETE requests:</p>
<ul>
<li><p><strong>Permanent Action</strong>: Once a DELETE request is processed, the resource is typically gone. In some cases, systems might implement "soft delete" functionality, where the resource is hidden but not completely removed. However, most use a "hard delete," where the resource is fully erased. Soft deletes can be useful for recovery purposes, allowing data to be restored if needed.</p>
</li>
<li><p><strong>Authentication</strong>: DELETE requests should be restricted to authorized users. Before performing a DELETE action, the server should validate that the user has permission to delete the resource. For example, only the owner of a user account should be able to delete it, not another user.</p>
</li>
<li><p><strong>Confirmation</strong>: Many applications prompt users to confirm their intention before processing a DELETE action. This extra step ensures users don't accidentally delete important data, especially for irreversible actions like account deletion.</p>
</li>
</ul>
<h4 id="heading-example-of-a-confirmation-step">Example of a Confirmation Step:</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (confirm(<span class="hljs-string">"Are you sure you want to delete this post?"</span>)) {
  fetch(<span class="hljs-string">'https://example.com/posts/123'</span>, {
    <span class="hljs-attr">method</span>: <span class="hljs-string">'DELETE'</span>
  })
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Post deleted'</span>))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error:'</span>, error));
}
</code></pre>
<ul>
<li><strong>Reversibility (Soft Delete)</strong>: For important data, it’s often useful to implement a <strong>soft delete</strong>, which doesn’t completely remove the data but marks it as deleted in the database. This allows the data to be restored later if needed. For example, many email systems keep deleted messages in a "Trash" folder until they are permanently removed.</li>
</ul>
<h3 id="heading-best-practices-for-handling-delete-requests">Best Practices for Handling DELETE Requests</h3>
<ol>
<li><p><strong>Require Authentication</strong>: Only authenticated users should be able to perform DELETE actions. This prevents unauthorized users from deleting resources they don't own. For example, users should only be allowed to delete their own data, not that of others.</p>
<ul>
<li><strong>Example</strong>: In a content management system (CMS), ensure that only the author of a post or an admin can delete it.</li>
</ul>
</li>
<li><p><strong>Use Confirmation Steps</strong>: For critical actions, confirm the user’s intent before proceeding. This is especially important for actions that cannot be undone, such as deleting an account or permanently removing a file.</p>
<ul>
<li><strong>Example</strong>: Show a prompt that says, "Are you sure you want to delete your account? This action cannot be undone."</li>
</ul>
</li>
<li><p><strong>Log Deletions</strong>: Keep a record of DELETE requests, including who initiated the request and when it occurred. Logging is important for accountability, troubleshooting, and data recovery in case of accidental deletions.</p>
<ul>
<li><strong>Example</strong>: In an e-commerce system, log details when a product is removed from the catalog, such as the user who initiated the request and the time of deletion.</li>
</ul>
</li>
<li><p><strong>Soft Delete for Critical Data</strong>: Implement a soft delete mechanism for data that may need to be restored later. This is particularly useful in scenarios like user accounts, where a user might want to recover their data after deletion.</p>
<ul>
<li><strong>Example</strong>: When a user "deletes" their account, it’s marked as inactive or hidden, rather than fully erased, allowing the user to recover it later.</li>
</ul>
</li>
<li><p><strong>Handle Errors Gracefully</strong>: If a DELETE request fails, the server should return an appropriate error message. For example, if the resource doesn’t exist or the user isn’t authorized to delete it, the server should respond with a message like "Resource not found" or "Unauthorized action."</p>
<ul>
<li><strong>Example</strong>: A DELETE request for a non-existent user could return a <code>404 Not Found</code> response.</li>
</ul>
</li>
<li><p><strong>Double-Check URL Targeting</strong>: Before sending a DELETE request, ensure the URL points to the correct resource. Accidentally targeting the wrong resource could result in unintended data loss.</p>
<ul>
<li><strong>Example</strong>: If you are managing a to-do list and want to delete a single task, ensure the URL points specifically to that task and not to the entire list.</li>
</ul>
</li>
<li><p><strong>Communicate Results to the User</strong>: After a successful DELETE request, inform the user that the resource has been deleted. This can be done through a message or notification confirming the action.</p>
<ul>
<li><strong>Example</strong>: Show a message like "Item successfully deleted" after a product or post has been removed from the system.</li>
</ul>
</li>
</ol>
<h3 id="heading-delete-response">DELETE Response</h3>
<p>Typically, a successful DELETE request returns one of the following status codes:</p>
<ul>
<li><p><strong>200 OK</strong>: Indicates that the deletion was successful and includes a response body (for example, a message confirming the deletion).</p>
</li>
<li><p><strong>204 No Content</strong>: The request was successful, but no content is returned in the response body. This is common when the resource is deleted, and there’s nothing to send back.</p>
</li>
<li><p><strong>404 Not Found</strong>: Indicates that the resource to be deleted does not exist.</p>
</li>
</ul>
<h3 id="heading-example-of-a-delete-request-response">Example of a DELETE Request Response</h3>
<p>If the DELETE request is successful and the resource is removed, a server might respond with a <code>204 No Content</code> status:</p>
<pre><code class="lang-http">HTTP/1.1 <span class="hljs-number">204</span> No Content
</code></pre>
<p>This response tells the client that the resource was successfully deleted but doesn’t return any additional data.</p>
<h2 id="heading-head-method">HEAD Method</h2>
<p>The HEAD method is similar to the GET method but with a key difference: it only retrieves the headers of a resource, not the actual content.</p>
<p>When you send a HEAD request, the server responds with the same headers as a GET request, but without sending the body of the resource (like text, images, or files). This makes HEAD useful for checking information about a resource, such as its size or last modified date, without downloading the entire content.</p>
<p>For example, if you're managing a large file and want to check its size before downloading, you can use a HEAD request to get this information from the server without actually fetching the file itself.</p>
<h3 id="heading-how-head-compares-to-get">How HEAD Compares to GET</h3>
<ul>
<li><p><strong>Same Headers, No Content</strong>: The HEAD request provides the same headers you’d receive with a GET request, such as <code>Content-Type</code>, <code>Content-Length</code>, <code>Last-Modified</code>, and so on. However, the response contains no body—just the metadata.</p>
</li>
<li><p><strong>Faster Requests</strong>: Because no body is included, HEAD requests are faster and consume less bandwidth than GET requests. This is helpful when you're only interested in details about the resource, not the content itself.</p>
</li>
</ul>
<h3 id="heading-use-cases-for-head">Use Cases for HEAD</h3>
<ol>
<li><p><strong>Checking Resource Availability</strong>: You can use a HEAD request to check whether a resource (such as a webpage or file) exists without fetching the content. For example, if a URL returns a status code like <code>200 OK</code>, you know the resource is there. A <code>404 Not Found</code> status code would indicate that it’s not available.</p>
</li>
<li><p><strong>Testing Links</strong>: If you manage a website with numerous external links, a HEAD request can test whether those links are still valid, saving you from loading the entire page. If a HEAD request returns an error code, you know the link is broken.</p>
</li>
<li><p><strong>Fetching File Metadata</strong>: If you’re dealing with large files, you might want to check their size before downloading. A HEAD request allows you to gather metadata like the file size (<code>Content-Length</code>) and type (<code>Content-Type</code>) without retrieving the entire file.</p>
</li>
<li><p><strong>Optimizing Caching</strong>: Browsers and applications can use HEAD requests to check if a resource has been updated since it was cached. The server returns headers like <code>Last-Modified</code> or <code>ETag</code>, and if these values haven’t changed, the cached version can be used, saving bandwidth and time.</p>
</li>
<li><p><strong>API Efficiency</strong>: HEAD requests can be useful in APIs when a client needs to verify that data exists without downloading the entire response. For example, a request could check whether a record exists in a database without fetching the full details.</p>
</li>
<li><p><strong>Server Health Monitoring</strong>: HEAD requests can be used to measure server performance. By testing the speed of a response without downloading content, developers can monitor server response times, check for issues, or determine if the server is up.</p>
</li>
</ol>
<h3 id="heading-best-practices-for-using-head">Best Practices for Using HEAD</h3>
<ul>
<li><p><strong>Efficient Testing</strong>: HEAD is ideal for validating resources or testing API endpoints without downloading unnecessary data.</p>
</li>
<li><p><strong>Caching</strong>: HEAD requests help with cache validation, ensuring that a resource is up-to-date without consuming bandwidth.</p>
</li>
<li><p><strong>No Side Effects</strong>: Like GET, HEAD should be safe and idempotent, meaning it should not alter the state of the resource. It’s used purely for retrieving information.</p>
</li>
</ul>
<h2 id="heading-options-method">OPTIONS Method</h2>
<p>The OPTIONS method is used to find out what actions are allowed on a specific resource. It allows a client (like a browser or an API) to ask the server, "What operations can I perform on this resource?" In response, the server lists the HTTP methods it supports for that resource, such as GET, POST, PUT, DELETE, and so on.</p>
<p>OPTIONS doesn’t perform any operation on the resource itself. Instead, it provides information about what the client can do. This makes it useful when you want to check what actions are allowed before actually making a request that changes or retrieves data.</p>
<p>For example, if you’re working with an API and want to see if it supports a DELETE method on a particular endpoint, you can send an OPTIONS request to get that information without affecting the resource.</p>
<h3 id="heading-retrieving-supported-methods">Retrieving Supported Methods</h3>
<ol>
<li><p><strong>Sending an OPTIONS Request</strong>: The client sends an OPTIONS request to a server, typically targeting a specific URL. This request serves as an inquiry about what actions are permitted on the resource at that endpoint.</p>
</li>
<li><p><strong>Server’s Response</strong>: The server responds with an <code>Allow</code> header that lists the available HTTP methods for the resource. For example, it might return <code>Allow: GET, POST, DELETE</code>, meaning those methods can be used.</p>
</li>
<li><p><strong>Testing for Methods</strong>: If you're unsure whether a particular method (like PATCH or DELETE) is supported by a server, you can send an OPTIONS request first to check. This avoids attempting methods that the server doesn’t support, which could result in errors.</p>
</li>
</ol>
<h4 id="heading-example-1">Example:</h4>
<pre><code class="lang-http"><span class="hljs-keyword">OPTIONS</span> <span class="hljs-string">/api/resource</span> HTTP/1.1
<span class="hljs-attribute">Host</span>: example.com
</code></pre>
<p>Server Response:</p>
<pre><code class="lang-http">HTTP/1.1 <span class="hljs-number">200</span> OK
<span class="hljs-attribute">Allow</span>: GET, POST, DELETE
</code></pre>
<h3 id="heading-how-options-is-used-in-cross-origin-resource-sharing-cors">How OPTIONS is Used in Cross-Origin Resource Sharing (CORS)</h3>
<p>One of the most common uses of the OPTIONS method is in handling <strong>Cross-Origin Resource Sharing (CORS)</strong>. CORS is a security feature that ensures resources on one domain aren’t accessed improperly by web pages from another domain.</p>
<h4 id="heading-cors-and-preflight-requests">CORS and Preflight Requests</h4>
<p>When a browser needs to make a cross-origin request (for example, a request from <a target="_blank" href="http://domainA.com"><code>domainA.com</code></a> to <a target="_blank" href="http://api.domainB.com"><code>api.domainB.com</code></a>), the browser first sends an <strong>OPTIONS request</strong>, known as a <strong>preflight request</strong>, to the target server. The preflight request checks whether the actual request is allowed under the server’s CORS policy.</p>
<ol>
<li><p><strong>Preflight Request</strong>: The browser sends an OPTIONS request before the actual request (such as a POST or PUT). This request asks the server which methods are allowed, which domains can access the resource, and whether specific headers or credentials are permitted.</p>
</li>
<li><p><strong>Server’s Response</strong>: The server responds with CORS headers, such as <code>Access-Control-Allow-Methods</code>, <code>Access-Control-Allow-Origin</code>, and <code>Access-Control-Allow-Headers</code>. This tells the browser whether the request can proceed and what methods or domains are allowed.</p>
<p> Example Response:</p>
<pre><code class="lang-http"> HTTP/1.1 204 No Content
 Access-Control-Allow-Origin: https://domainA.com
 Access-Control-Allow-Methods: GET, POST
 Access-Control-Allow-Headers: Content-Type
</code></pre>
</li>
<li><p><strong>Ensuring Security</strong>: CORS and the preflight OPTIONS request ensure that cross-origin requests are only allowed when the server permits it. Without this security step, websites could make unauthorized requests to other domains.</p>
</li>
<li><p><strong>Handling Complex Requests</strong>: If a request includes custom headers, uses HTTP methods other than simple ones like GET or POST, or sends credentials like cookies, the browser automatically sends an OPTIONS preflight request. If the server denies the request (that is, returns headers disallowing the action), the browser blocks the request.</p>
</li>
</ol>
<h4 id="heading-simplified-workflow">Simplified Workflow:</h4>
<ul>
<li><p><strong>Browser</strong>: "Can I make this request to <a target="_blank" href="http://api.domainB.com"><code>api.domainB.com</code></a>?"</p>
</li>
<li><p><strong>Server</strong>: "Yes, you can use <code>GET</code> and <code>POST</code>, but only from <a target="_blank" href="http://domainA.com"><code>domainA.com</code></a> and with these headers."</p>
</li>
<li><p><strong>Browser</strong>: Proceeds with the actual request if the response permits.</p>
</li>
</ul>
<h3 id="heading-use-cases-for-the-options-method">Use Cases for the OPTIONS Method</h3>
<ul>
<li><p><strong>Discovering Available Methods</strong>: Useful for developers to check which HTTP methods a resource supports before performing an operation.</p>
</li>
<li><p><strong>CORS Preflight</strong>: Critical in web security to ensure that cross-origin requests are properly authorized.</p>
</li>
<li><p><strong>Improving API Efficiency</strong>: APIs can expose the supported methods for a resource via OPTIONS, making it easier for clients to understand what operations can be performed.</p>
</li>
</ul>
<p>The OPTIONS method is thus essential in web applications for managing request permissions and improving security, particularly in cross-domain scenarios.</p>
<h2 id="heading-trace-method">TRACE Method</h2>
<p>The TRACE method is used to debug web applications and test how requests pass through networks. When you send a TRACE request, it triggers a loopback, where the server sends back the exact request it received, without any changes. This helps developers see if anything is modified as the request travels through different systems, like firewalls or proxies, before reaching the server.</p>
<p>In simple terms, TRACE allows you to trace the path your request takes from your client (like a browser or API tool) to the server and back. This method can be useful for identifying issues during the transmission of a request.</p>
<h3 id="heading-understanding-loopback-diagnostics">Understanding Loopback Diagnostics</h3>
<p>Loopback diagnostics refers to the process of seeing how data is handled as it moves across networks, using TRACE to check if the original request remains intact. Here’s how it works:</p>
<ol>
<li><p><strong>Sending a TRACE Request</strong>: You send a TRACE request to a server. This request is usually small, containing basic information like the method, URL, and headers. It doesn't carry any extra data or payload like POST or PUT methods.</p>
</li>
<li><p><strong>Server’s Response</strong>: Instead of responding with a resource, the server sends back the exact request it received. This includes the HTTP method, the URL, headers, and anything else in the original request. The server doesn’t modify or process the request—it just returns it exactly as it was received.</p>
</li>
<li><p><strong>Tracing the Path</strong>: When the TRACE response comes back, it allows you to see the entire path the request took, including any changes made to the request headers or content. This is useful for diagnosing issues such as:</p>
<ul>
<li><p><strong>Proxy Servers</strong>: If your request passes through one or more proxy servers before reaching the destination, TRACE can show if those proxies have altered the request headers or content.</p>
</li>
<li><p><strong>Network Firewalls</strong>: Some network firewalls might add or modify headers as your request passes through them. TRACE helps reveal these modifications.</p>
</li>
<li><p><strong>Error Tracking</strong>: If a request fails to behave as expected, TRACE can help track where something went wrong in the transmission.</p>
</li>
</ul>
</li>
<li><p><strong>Effective Debugging</strong>: TRACE is especially helpful when debugging web applications or APIs. If your application is experiencing errors due to routing, proxies, or server configurations, TRACE lets you see the unaltered request, making it easier to pinpoint the issue.</p>
</li>
</ol>
<h3 id="heading-security-concerns-with-trace">Security Concerns with TRACE</h3>
<p>Although TRACE can be useful for debugging, it is generally considered a security risk and is often disabled on most servers for several reasons:</p>
<ol>
<li><p><strong>XSS Attacks (Cross-Site Scripting)</strong>: TRACE can expose sensitive information such as cookies or authentication tokens in the headers. Malicious actors could exploit TRACE to capture these details, leading to security breaches, especially if a vulnerability like cross-site scripting (XSS) is present. This makes TRACE a potential target for attackers trying to steal user data.</p>
</li>
<li><p><strong>Request Modification Exposure</strong>: Since TRACE shows all modifications made to a request, it can also reveal how internal proxies and firewalls handle requests. This could give attackers insight into the internal workings of a network, making it easier for them to plan further attacks.</p>
</li>
<li><p><strong>Disabling TRACE for Safety</strong>: For these reasons, TRACE is often disabled on most web servers to prevent abuse. In many modern web applications, more secure methods exist for debugging requests and tracing network paths, so TRACE is rarely necessary in everyday use.</p>
</li>
<li><p><strong>Safer Alternatives</strong>: Developers can use safer diagnostic tools and logging features built into modern web frameworks and APIs. These alternatives provide similar insights without exposing security risks associated with TRACE.</p>
</li>
</ol>
<h2 id="heading-connect-method">CONNECT Method</h2>
<p>The CONNECT method is mainly used to establish a tunnel between a client and a server through an intermediary, usually a proxy server. When the client sends a CONNECT request, the server creates a tunnel that allows encrypted data to flow between the client and the destination server. This method is crucial for securing connections, especially when dealing with HTTPS.</p>
<p>CONNECT does not handle any actual data on its own. Instead, it sets up a path for secure communication, allowing encrypted information to pass through proxies without being modified or inspected.</p>
<h3 id="heading-how-connect-works">How CONNECT Works</h3>
<ol>
<li><p><strong>Sending a CONNECT Request</strong>: A client, such as a web browser, sends a CONNECT request to the proxy server. This request includes the target server's hostname and port, typically the standard HTTPS port (443). For example, when accessing <a target="_blank" href="https://example.com"><code>https://example.com</code></a>, the browser sends a CONNECT request to the proxy server asking it to connect to that domain on port 443.</p>
</li>
<li><p><strong>Establishing the Tunnel</strong>: The proxy server, upon receiving the CONNECT request, establishes a tunnel to the destination server. This tunnel allows encrypted communication to pass through without interference. The proxy simply forwards traffic between the client and the destination, acting as a relay.</p>
</li>
<li><p><strong>Encrypted Communication</strong>: Once the tunnel is set up, the client and the destination server can communicate directly using a secure encryption protocol, such as TLS (used by HTTPS). The proxy cannot decrypt or modify the data passing through because it’s encrypted between the client and the server.</p>
</li>
<li><p><strong>Secure Data Transfer</strong>: With the CONNECT method, sensitive data—such as login credentials, personal information, or financial transactions—can be transmitted securely between the client and the server, even when passing through proxies. The encrypted tunnel ensures that the data remains confidential and intact.</p>
</li>
</ol>
<h3 id="heading-example-of-a-connect-request-and-response">Example of a CONNECT Request and Response</h3>
<ul>
<li><p><strong>CONNECT Request</strong>:</p>
<pre><code class="lang-http">  CONNECT example.com:443 HTTP/1.1
  Host: example.com
</code></pre>
</li>
<li><p><strong>Proxy Response</strong> (if the tunnel is successfully established):</p>
<pre><code class="lang-http">  HTTP/1.1 200 Connection Established
</code></pre>
</li>
</ul>
<h3 id="heading-tunneling-with-connect">Tunneling with CONNECT</h3>
<p>The term <strong>tunneling</strong> in this context refers to creating a direct, secure link between the client and the destination server via a proxy. The proxy acts as a middleman but does not interfere with or access the encrypted data being transmitted through the tunnel.</p>
<h4 id="heading-steps-of-the-tunneling-process">Steps of the Tunneling Process:</h4>
<ul>
<li><p><strong>Sending the CONNECT Request</strong>: The client sends a CONNECT request to the proxy, specifying the destination server and port (for example, port 443 for HTTPS).</p>
</li>
<li><p><strong>Proxy Sets Up the Tunnel</strong>: The proxy server establishes a secure tunnel between the client and the destination server, forwarding traffic between the two endpoints.</p>
</li>
<li><p><strong>Encrypted Communication Begins</strong>: The client and the destination server communicate directly through the encrypted tunnel using HTTPS or another encryption protocol. The proxy forwards the encrypted traffic but cannot access or modify it.</p>
</li>
</ul>
<h3 id="heading-typical-use-cases-of-the-connect-method">Typical Use Cases of the CONNECT Method</h3>
<ol>
<li><p><strong>HTTPS Through Proxies</strong>: One of the most common uses of the CONNECT method is enabling <strong>HTTPS traffic through proxies</strong>. In many corporate or network environments, internet traffic must pass through a proxy server. For secure websites using HTTPS, the CONNECT method allows the proxy server to establish a tunnel, forwarding encrypted traffic between the client and the destination server without inspecting the data.</p>
<ul>
<li><strong>Example</strong>: When you visit a secure banking website from a corporate network, your browser may need to pass through a corporate proxy. The CONNECT method is used to establish an encrypted tunnel between your browser and the bank's website, allowing sensitive data (such as login credentials) to pass through the proxy securely.</li>
</ul>
</li>
<li><p><strong>VPNs and Secure Channels</strong>: <strong>VPN (Virtual Private Network)</strong> services also rely on similar tunneling techniques to encrypt and route internet traffic securely. Some VPN services use CONNECT to create secure tunnels, ensuring that all data transmitted between the user and the internet is encrypted and safe from eavesdropping.</p>
</li>
<li><p><strong>Accessing Blocked Content</strong>: In environments where certain websites are blocked (for example, schools or offices), CONNECT can sometimes be used to bypass restrictions by establishing a tunnel through a proxy. Although this practice may violate network policies, it illustrates how CONNECT can be used to establish secure, unmonitored access to otherwise blocked resources.</p>
</li>
<li><p><strong>Custom Proxies</strong>: Developers may set up <strong>custom proxies</strong> to route application traffic for performance or security reasons. In these cases, CONNECT allows HTTPS or other secure traffic to pass through the proxy while maintaining privacy and security, as the proxy server cannot access the encrypted data inside the tunnel.</p>
</li>
</ol>
<h3 id="heading-security-considerations">Security Considerations</h3>
<p>While CONNECT is essential for secure communications, it also presents some security challenges:</p>
<ul>
<li><p><strong>Bypassing Content Filters</strong>: Since CONNECT creates an encrypted tunnel that proxies cannot inspect, it can be used to bypass content filtering systems. This allows users to access restricted websites or services, which may violate organizational policies.</p>
</li>
<li><p><strong>Tunneling Malicious Traffic</strong>: CONNECT can be exploited by malicious actors to tunnel harmful or unauthorized traffic through a proxy. Because the traffic is encrypted, firewalls and security systems may not detect malicious activity.</p>
</li>
<li><p><strong>Mitigation</strong>: Many organizations address these risks by closely monitoring and restricting the use of the CONNECT method. Some proxies perform <strong>SSL interception</strong> to decrypt and inspect HTTPS traffic, though this introduces privacy concerns and may compromise user security.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>HTTP methods are essential in enabling communication between web applications and servers. Each method, from GET to CONNECT, is designed for a specific task, such as sending data, retrieving information, updating resources, or setting up secure connections. Choosing the correct method for the job improves the efficiency and security of your application.</p>
<p>GET is ideal for retrieving data, POST and PUT help with creating and updating, PATCH handles partial updates, and DELETE removes resources. HEAD checks response headers without retrieving content, OPTIONS shows supported methods, and TRACE and CONNECT assist with debugging and secure communication.</p>
<p>Using the appropriate HTTP methods ensures your application runs efficiently and securely, offering a smooth experience for users.</p>
<p>If you have any questions or suggestions, feel free to reach out on <a target="_blank" href="https://ng.linkedin.com/in/joan-ayebola">LinkedIn</a>. If you enjoyed this content, consider <a target="_blank" href="https://www.buymeacoffee.com/joanayebola">buying me a coffee</a> to support the creation of more developer-friendly contents.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ New JavaScript Array Methods to Help You Write Better, Cleaner Code ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript is always improving, and every year, new features are added to make coding easier and more efficient. These updates help developers write cleaner code and work faster. If you want to stay ahead as a developer, it's important to learn about... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/new-javascript-array-methods-to-help-you-write-better-cleaner-code/</link>
                <guid isPermaLink="false">66fc683b9c77a7afa456dbab</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ array ]]>
                    </category>
                
                    <category>
                        <![CDATA[ array methods ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Tue, 01 Oct 2024 21:23:07 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727789649013/c0c332b4-fc35-4b75-bea9-240dcd85ec88.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript is always improving, and every year, new features are added to make coding easier and more efficient. These updates help developers write cleaner code and work faster. If you want to stay ahead as a developer, it's important to learn about the latest JavaScript features.</p>
<p>In this article, we’ll talk about some of the new tools and methods available in JavaScript, like <code>findLast</code>, <code>toReversed</code>, <code>toSorted</code>, and more. These features allow you to manipulate arrays and data in smarter ways without changing your original data. We’ll look at how each one works, and I’ll show you examples, explaining how they can make your code better.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-array-methods-in-javascript">Array Methods in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-findlast-locate-the-last-matching-element"><code>findLast</code>: Locate the Last Matching Element</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-findlastindex-pinpoint-the-index-of-the-last-match"><code>findLastIndex</code>: Pinpoint the Index of the Last Match</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-toreversed-reverse-without-changing-original-arrays"><code>toReversed</code>: Reverse Without Changing Original Arrays</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-tosorted-immutable-sorting-for-cleaner-code"><code>toSorted</code>: Immutable Sorting for Cleaner Code</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-tospliced-create-new-arrays-by-splicing-without-mutation"><code>toSpliced</code>: Create New Arrays by Splicing Without Mutation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-with-modify-array-elements-by-index"><code>with</code>: Modify Array Elements by Index</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-combining-new-javascript-methods-for-advanced-data-manipulation">Combining New JavaScript Methods for Advanced Data Manipulation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-backward-compatibility-and-polyfills">Backward Compatibility and Polyfills</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-array-methods-in-javascript">Array Methods in JavaScript</h2>
<p>JavaScript has a variety of methods that make working with arrays easier. Arrays are lists of items, and you’ll often need to search, sort, or update these lists. Older methods like <code>push()</code>, <code>pop()</code>, <code>map()</code>, and <code>filter()</code> have been useful, but they can sometimes change the original data, which isn't always what you want.</p>
<p>Newer JavaScript methods offer better options to handle arrays, especially when you need to keep the original data unchanged. These new methods make coding more reliable and cleaner.</p>
<p>The latest JavaScript methods provide more ways to work with arrays without changing the original list. These methods, like <code>findLast</code>, <code>toSorted</code>, and <code>toReversed</code>, create a new array or give you the result directly, leaving your original array untouched.</p>
<h2 id="heading-findlast-locate-the-last-matching-element"><code>findLast</code>: Locate the Last Matching Element</h2>
<p>When working with arrays, you might want to search for an item that matches certain conditions. The older <code>find()</code> method helps you get the first matching item, but what if you need the last match instead?</p>
<p>This is where <code>findLast()</code> comes in. It searches the array starting from the end and gives you the last item that meets your condition, without manually reversing the array.</p>
<h3 id="heading-syntax-and-parameters-of-findlast">Syntax and Parameters of <code>findLast</code></h3>
<p>The <code>findLast()</code> method works almost like <code>find()</code>, but it looks for the last match. Here’s the basic syntax:</p>
<pre><code class="lang-javascript">array.findLast(callback(element, index, array), thisArg);
</code></pre>
<ul>
<li><p><strong>callback</strong>: A function that checks each item in the array.</p>
</li>
<li><p><strong>element</strong>: The current item being checked.</p>
</li>
<li><p><strong>index</strong>: The index of the current item.</p>
</li>
<li><p><strong>array</strong>: The array being processed.</p>
</li>
<li><p><strong>thisArg</strong>: Optional. It can be used as <code>this</code> inside the callback.</p>
</li>
</ul>
<h3 id="heading-practical-examples-of-using-findlast">Practical Examples of Using <code>findLast</code></h3>
<p>Let’s look at a simple example. Imagine you have an array of numbers, and you want to find the last number greater than 5.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">2</span>, <span class="hljs-number">7</span>, <span class="hljs-number">4</span>, <span class="hljs-number">9</span>, <span class="hljs-number">3</span>];

<span class="hljs-comment">// Find the last number greater than 5</span>
<span class="hljs-keyword">const</span> lastNumberOver5 = numbers.findLast(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num &gt; <span class="hljs-number">5</span>);
<span class="hljs-built_in">console</span>.log(lastNumberOver5); <span class="hljs-comment">// Output: 9</span>
</code></pre>
<p>In this example, <code>findLast()</code> starts searching from the end of the array and returns the last number that is greater than 5.</p>
<h3 id="heading-finding-the-last-occurrence-in-arrays">Finding the Last Occurrence in Arrays</h3>
<p>You can use <code>findLast()</code> to get the last matching item, which can be helpful when there are multiple matches in an array. Let’s say you want to find the last even number in an array:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>, <span class="hljs-number">3</span>, <span class="hljs-number">6</span>];

<span class="hljs-comment">// Find the last even number</span>
<span class="hljs-keyword">const</span> lastEvenNumber = numbers.findLast(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(lastEvenNumber); <span class="hljs-comment">// Output: 6</span>
</code></pre>
<h3 id="heading-comparison-with-find">Comparison with <code>find()</code></h3>
<p>The key difference between <code>find()</code> and <code>findLast()</code> is the direction in which they search. <code>find()</code> starts from the beginning of the array and stops at the first match, while <code>findLast()</code> starts from the end and returns the last match.</p>
<p>Here’s a comparison:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>, <span class="hljs-number">5</span>];

<span class="hljs-comment">// Using find()</span>
<span class="hljs-keyword">const</span> first5 = numbers.find(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num === <span class="hljs-number">5</span>);
<span class="hljs-built_in">console</span>.log(first5); <span class="hljs-comment">// Output: 5 (first match)</span>

<span class="hljs-comment">// Using findLast()</span>
<span class="hljs-keyword">const</span> last5 = numbers.findLast(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num === <span class="hljs-number">5</span>);
<span class="hljs-built_in">console</span>.log(last5); <span class="hljs-comment">// Output: 5 (last match)</span>
</code></pre>
<p>The <code>findLast()</code> method is particularly useful in scenarios where the order of items matters, such as:</p>
<ol>
<li><p><strong>Retrieving the last message in a chat app</strong> that meets a certain condition.</p>
</li>
<li><p><strong>Finding the last error</strong> in a list of system logs.</p>
</li>
<li><p><strong>Getting the last transaction</strong> above a certain amount in a financial app.</p>
</li>
</ol>
<h2 id="heading-findlastindex-pinpoint-the-index-of-the-last-match"><code>findLastIndex</code>: Pinpoint the Index of the Last Match</h2>
<p>Sometimes, you don’t just need the last matching item in an array, but you also want its position. This is where <code>findLastIndex()</code> helps. It works like <code>findLast()</code>, but instead of returning the value, it returns the index of the last element that meets your condition. This makes it easier to track the location of that item in the array.</p>
<h3 id="heading-syntax-and-key-parameters">Syntax and Key Parameters</h3>
<p>The syntax of <code>findLastIndex()</code> is simple and looks a lot like <code>findLast()</code>:</p>
<pre><code class="lang-javascript">array.findLastIndex(callback(element, index, array), thisArg);
</code></pre>
<ul>
<li><p><strong>callback</strong>: A function that runs for each element in the array.</p>
</li>
<li><p><strong>element</strong>: The current item being checked.</p>
</li>
<li><p><strong>index</strong>: The position of the current item in the array.</p>
</li>
<li><p><strong>array</strong>: The array being processed.</p>
</li>
<li><p><strong>thisArg</strong>: Optional. Used as <code>this</code> inside the callback.</p>
</li>
</ul>
<p>If no element meets the condition, <code>findLastIndex()</code> returns <code>-1</code>.</p>
<h3 id="heading-practical-examples-of-findlastindex-in-action">Practical Examples of <code>findLastIndex</code> in Action</h3>
<p>Let’s look at an example. Say you have an array of numbers and want to find the index of the last number greater than 5.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">2</span>, <span class="hljs-number">7</span>, <span class="hljs-number">4</span>, <span class="hljs-number">9</span>, <span class="hljs-number">3</span>];

<span class="hljs-comment">// Find the index of the last number greater than 5</span>
<span class="hljs-keyword">const</span> lastIndexOver5 = numbers.findLastIndex(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num &gt; <span class="hljs-number">5</span>);
<span class="hljs-built_in">console</span>.log(lastIndexOver5); <span class="hljs-comment">// Output: 3 (index of 9)</span>
</code></pre>
<p>In this case, <code>findLastIndex()</code> returns <code>3</code>, which is the position of <code>9</code>, the last number greater than 5 in the array.</p>
<h3 id="heading-retrieving-the-last-index-matching-a-condition">Retrieving the Last Index Matching a Condition</h3>
<p>If you need to pinpoint the position of the last element that fits a specific condition, <code>findLastIndex()</code> is the right tool. Here’s another example, finding the last even number in an array:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>, <span class="hljs-number">3</span>, <span class="hljs-number">6</span>];

<span class="hljs-comment">// Find the index of the last even number</span>
<span class="hljs-keyword">const</span> lastEvenIndex = numbers.findLastIndex(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(lastEvenIndex); <span class="hljs-comment">// Output: 5 (index of the last 6)</span>
</code></pre>
<p>In this case, the index of the last even number is <code>5</code>.</p>
<h3 id="heading-contrast-with-findindex">Contrast with <code>findIndex</code></h3>
<p>The main difference between <code>findIndex()</code> and <code>findLastIndex()</code> is the direction they search. <code>findIndex()</code> starts from the beginning of the array and stops at the first match. <code>findLastIndex()</code> works in reverse, starting from the end and returning the last match.</p>
<p>Here’s a quick comparison:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>, <span class="hljs-number">5</span>];

<span class="hljs-comment">// Using findIndex()</span>
<span class="hljs-keyword">const</span> first5Index = numbers.findIndex(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num === <span class="hljs-number">5</span>);
<span class="hljs-built_in">console</span>.log(first5Index); <span class="hljs-comment">// Output: 1 (first match)</span>

<span class="hljs-comment">// Using findLastIndex()</span>
<span class="hljs-keyword">const</span> last5Index = numbers.findLastIndex(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num === <span class="hljs-number">5</span>);
<span class="hljs-built_in">console</span>.log(last5Index); <span class="hljs-comment">// Output: 4 (last match)</span>
</code></pre>
<h3 id="heading-performance-considerations-for-large-data-sets">Performance Considerations for Large Data Sets</h3>
<p>In small arrays, the performance difference between <code>findIndex()</code> and <code>findLastIndex()</code> might not be noticeable. But with large datasets, the difference can matter. Since <code>findLastIndex()</code> starts from the end of the array, it may be more efficient if you expect the match to be near the end. This can save time compared to scanning from the start using <code>findIndex()</code>.</p>
<p>For example, when working with a large log of events, using <code>findLastIndex()</code> could quickly find the most recent event that meets a condition:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> events = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>(<span class="hljs-number">100000</span>).fill(<span class="hljs-number">0</span>).map(<span class="hljs-function">(<span class="hljs-params">_, i</span>) =&gt;</span> i + <span class="hljs-number">1</span>);

<span class="hljs-comment">// Find the index of the last number divisible by 5000</span>
<span class="hljs-keyword">const</span> lastDivisibleBy5000 = events.findLastIndex(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num % <span class="hljs-number">5000</span> === <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(lastDivisibleBy5000); <span class="hljs-comment">// Output: 99999 (index of 100000)</span>
</code></pre>
<p>In large datasets like this, using <code>findLastIndex()</code> helps avoid unnecessary searches when you’re only interested in the most recent or last occurrence.</p>
<h2 id="heading-toreversed-reverse-without-changing-original-arrays"><code>toReversed</code>: Reverse Without Changing Original Arrays</h2>
<p>In JavaScript, the <code>reverse()</code> method is used to flip the order of elements in an array. But it changes the original array. This can cause problems if you want to keep the original data intact. The <code>toReversed()</code> method fixes this issue by allowing you to reverse an array without affecting the original.</p>
<h3 id="heading-syntax-and-usage-of-toreversed">Syntax and Usage of <code>toReversed</code></h3>
<p>The <code>toReversed()</code> method is simple to use. It creates a reversed version of the array without modifying the original one. Here’s the basic syntax:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newArray = array.toReversed();
</code></pre>
<ul>
<li><p><strong>array</strong>: The array you want to reverse.</p>
</li>
<li><p><strong>newArray</strong>: A new array with the reversed elements.</p>
</li>
</ul>
<h3 id="heading-examples-of-reversing-arrays-safely">Examples of Reversing Arrays Safely</h3>
<p>Let’s look at an example where you want to reverse an array but still need to keep the original version:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-comment">// Reverse the array without changing the original</span>
<span class="hljs-keyword">const</span> reversedNumbers = numbers.toReversed();

<span class="hljs-built_in">console</span>.log(reversedNumbers); <span class="hljs-comment">// Output: [5, 4, 3, 2, 1]</span>
<span class="hljs-built_in">console</span>.log(numbers);         <span class="hljs-comment">// Output: [1, 2, 3, 4, 5]</span>
</code></pre>
<p>In this case, the original <code>numbers</code> array stays the same, and <code>toReversed()</code> returns a new array with the elements flipped.</p>
<h3 id="heading-avoiding-side-effects-with-toreversed">Avoiding Side Effects with <code>toReversed</code></h3>
<p>One of the biggest benefits of <code>toReversed()</code> is that it avoids side effects. The traditional <code>reverse()</code> method directly changes the original array, which can lead to bugs if the original data is needed elsewhere. With <code>toReversed()</code>, the original array remains unchanged, so you don’t have to worry about unexpected changes.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> letters = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>, <span class="hljs-string">'d'</span>];

<span class="hljs-comment">// Using toReversed to avoid side effects</span>
<span class="hljs-keyword">const</span> reversedLetters = letters.toReversed();

<span class="hljs-built_in">console</span>.log(reversedLetters); <span class="hljs-comment">// Output: ['d', 'c', 'b', 'a']</span>
<span class="hljs-built_in">console</span>.log(letters);         <span class="hljs-comment">// Output: ['a', 'b', 'c', 'd']</span>
</code></pre>
<p>As you can see, the original <code>letters</code> array is still in its original form after calling <code>toReversed()</code>.</p>
<h3 id="heading-comparison-with-reverse-method">Comparison with <code>reverse</code> Method</h3>
<p>The <code>reverse()</code> method directly modifies the array, while <code>toReversed()</code> leaves the original unchanged. Here’s a quick comparison:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> nums = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>];

<span class="hljs-comment">// Using reverse()</span>
<span class="hljs-keyword">const</span> reversedNums1 = nums.reverse();
<span class="hljs-built_in">console</span>.log(reversedNums1);  <span class="hljs-comment">// Output: [40, 30, 20, 10]</span>
<span class="hljs-built_in">console</span>.log(nums);           <span class="hljs-comment">// Output: [40, 30, 20, 10] (Original array changed)</span>

<span class="hljs-comment">// Using toReversed()</span>
<span class="hljs-keyword">const</span> reversedNums2 = nums.toReversed();
<span class="hljs-built_in">console</span>.log(reversedNums2);  <span class="hljs-comment">// Output: [10, 20, 30, 40]</span>
<span class="hljs-built_in">console</span>.log(nums);           <span class="hljs-comment">// Output: [40, 30, 20, 10] (Original stays as it was after reverse)</span>
</code></pre>
<p>As shown, <code>reverse()</code> changes the array itself, but <code>toReversed()</code> doesn’t touch the original array.</p>
<h3 id="heading-how-toreversed-enhances-functional-programming-practices">How <code>toReversed</code> Enhances Functional Programming Practices</h3>
<p>In functional programming, the idea is to avoid changing data directly. Instead, new values are returned from functions, leaving the original data untouched.</p>
<p><code>toReversed()</code> fits perfectly into this concept, allowing arrays to be reversed without altering the original data. This leads to cleaner and safer code because you reduce the risk of accidentally changing something.</p>
<p>For example, in a functional programming setup, you might want to reverse an array of scores for display purposes without changing the actual scores:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> scores = [<span class="hljs-number">95</span>, <span class="hljs-number">87</span>, <span class="hljs-number">75</span>, <span class="hljs-number">60</span>];

<span class="hljs-comment">// Reverse the scores for display purposes without modifying the original</span>
<span class="hljs-keyword">const</span> displayedScores = scores.toReversed();

<span class="hljs-built_in">console</span>.log(displayedScores); <span class="hljs-comment">// Output: [60, 75, 87, 95]</span>
<span class="hljs-built_in">console</span>.log(scores);          <span class="hljs-comment">// Output: [95, 87, 75, 60] (Original scores intact)</span>
</code></pre>
<h2 id="heading-tosorted-immutable-sorting-for-cleaner-code"><code>toSorted</code>: Immutable Sorting for Cleaner Code</h2>
<p>JavaScript has had the <code>sort()</code> method for a long time, which allows you to arrange elements of an array. The issue is that <code>sort()</code> changes the original array, which can lead to unintended problems when the original data is still needed elsewhere.</p>
<p>To fix this, JavaScript introduced <code>toSorted()</code>. This method lets you sort arrays without changing the original, making the code cleaner and more reliable.</p>
<h3 id="heading-syntax-and-parameters">Syntax and Parameters</h3>
<p>The syntax for <code>toSorted()</code> is straightforward, similar to <code>sort()</code>, but it doesn't modify the original array:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newArray = array.toSorted(compareFunction);
</code></pre>
<ul>
<li><p><strong>array</strong>: The array you want to sort.</p>
</li>
<li><p><strong>compareFunction</strong>: Optional. A function that defines how the elements should be sorted. If not provided, the array elements are converted to strings and sorted in ascending order.</p>
</li>
</ul>
<h3 id="heading-use-cases-of-tosorted">Use Cases of <code>toSorted</code></h3>
<p>Let’s say you have a list of students and want to sort them based on their scores, but you need the original list untouched:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> students = [
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Dave'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">85</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Alexa'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">92</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Katie'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">78</span> }
];

<span class="hljs-comment">// Sort students without changing the original array</span>
<span class="hljs-keyword">const</span> sortedStudents = students.toSorted(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> b.score - a.score);

<span class="hljs-built_in">console</span>.log(sortedStudents);
<span class="hljs-comment">// Output: [{name: 'Katie', score: 92}, {name: 'Dave', score: 85}, {name: 'Katie', score: 78}]</span>

<span class="hljs-built_in">console</span>.log(students);
<span class="hljs-comment">// Output (unchanged): [{name: 'Dave', score: 85}, {name: 'Alexa', score: 92}, {name: 'Katie', score: 78}]</span>
</code></pre>
<p>This allows you to sort the students based on their scores without affecting the original data, which might be useful elsewhere in the code.</p>
<h3 id="heading-sorting-arrays-without-mutating-original-data">Sorting Arrays Without Mutating Original Data</h3>
<p><code>toSorted()</code> provides a safe way to handle sorting without the risk of accidentally changing the original array. This is especially helpful when working on large projects where data might be used in different parts of the code.</p>
<p>Here’s an example where you sort a simple list of numbers:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">5</span>, <span class="hljs-number">2</span>, <span class="hljs-number">9</span>, <span class="hljs-number">1</span>, <span class="hljs-number">7</span>];

<span class="hljs-comment">// Sort the numbers without changing the original array</span>
<span class="hljs-keyword">const</span> sortedNumbers = numbers.toSorted();

<span class="hljs-built_in">console</span>.log(sortedNumbers); <span class="hljs-comment">// Output: [1, 2, 5, 7, 9]</span>
<span class="hljs-built_in">console</span>.log(numbers);       <span class="hljs-comment">// Output (unchanged): [5, 2, 9, 1, 7]</span>
</code></pre>
<h3 id="heading-comparison-with-the-traditional-sort-method">Comparison with the Traditional <code>sort</code> Method</h3>
<p>The traditional <code>sort()</code> method sorts an array but changes the original, which can cause problems if the original array is needed elsewhere.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">4</span>, <span class="hljs-number">2</span>];

<span class="hljs-comment">// Using sort()</span>
<span class="hljs-keyword">const</span> sortedNumbers1 = numbers.sort();
<span class="hljs-built_in">console</span>.log(sortedNumbers1); <span class="hljs-comment">// Output: [1, 2, 3, 4]</span>
<span class="hljs-built_in">console</span>.log(numbers);        <span class="hljs-comment">// Output (original array changed): [1, 2, 3, 4]</span>

<span class="hljs-comment">// Using toSorted()</span>
<span class="hljs-keyword">const</span> sortedNumbers2 = numbers.toSorted();
<span class="hljs-built_in">console</span>.log(sortedNumbers2); <span class="hljs-comment">// Output: [1, 2, 3, 4]</span>
<span class="hljs-built_in">console</span>.log(numbers);        <span class="hljs-comment">// Output (unchanged): [3, 1, 4, 2]</span>
</code></pre>
<p>As you can see, <code>sort()</code> changes the original array, but <code>toSorted()</code> keeps it untouched.</p>
<h3 id="heading-performance-and-best-practices">Performance and Best Practices</h3>
<p>For smaller arrays, performance between <code>sort()</code> and <code>toSorted()</code> will be almost the same. But for larger datasets or when sorting is frequent, <code>toSorted()</code> can help avoid side effects and make the code safer.</p>
<p>Using <code>toSorted()</code> means you can safely pass the original array to other parts of the code without worrying about unexpected changes.</p>
<p>To get the best performance, make sure to always use a proper compare function, especially for complex sorting, like sorting objects:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> people = [
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Rash'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Josh'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Sammy'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">40</span> }
];

<span class="hljs-comment">// Sort people by age without mutating the original array</span>
<span class="hljs-keyword">const</span> sortedPeople = people.toSorted(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a.age - b.age);

<span class="hljs-built_in">console</span>.log(sortedPeople);
<span class="hljs-comment">// Output: [{name: 'Josh', age: 25}, {name: 'Rash', age: 30}, {name: 'Sammy', age: 40}]</span>
</code></pre>
<p>Using <code>toSorted()</code> improves the readability of your code and helps avoid unintended side effects, especially when working with important data.</p>
<h2 id="heading-tospliced-create-new-arrays-by-splicing-without-mutation"><code>toSpliced</code>: Create New Arrays by Splicing Without Mutation</h2>
<p>The <code>splice()</code> method in JavaScript has been useful for adding, removing, or replacing elements within an array. But it changes the original array, which can lead to unexpected results if you want to keep the original data.</p>
<p>To solve this, <code>toSpliced()</code> was introduced. It works like <code>splice()</code>, but without changing the original array, allowing for a safer and cleaner approach.</p>
<h3 id="heading-syntax-and-practical-usage">Syntax and Practical Usage</h3>
<p>Here’s how the <code>toSpliced()</code> method works. It creates a new array after splicing, leaving the original one unchanged.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newArray = array.toSpliced(start, deleteCount, item1, item2, ...);
</code></pre>
<ul>
<li><p><strong>start</strong>: The index at which to start modifying the array.</p>
</li>
<li><p><strong>deleteCount</strong>: The number of items to remove from the array (optional).</p>
</li>
<li><p><strong>item1, item2, ...</strong>: The items to add at the start index (optional).</p>
</li>
</ul>
<h3 id="heading-examples-splicing-arrays-in-an-immutable-way">Examples: Splicing Arrays in an Immutable Way</h3>
<p>Let’s explore a practical example where you want to remove and replace elements from an array but keep the original intact:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruits = [<span class="hljs-string">'apple'</span>, <span class="hljs-string">'banana'</span>, <span class="hljs-string">'cherry'</span>, <span class="hljs-string">'date'</span>];

<span class="hljs-comment">// Create a new array by removing 'banana' and adding 'blueberry' without changing the original</span>
<span class="hljs-keyword">const</span> newFruits = fruits.toSpliced(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-string">'blueberry'</span>);

<span class="hljs-built_in">console</span>.log(newFruits); <span class="hljs-comment">// Output: ['apple', 'blueberry', 'cherry', 'date']</span>
<span class="hljs-built_in">console</span>.log(fruits);    <span class="hljs-comment">// Output: ['apple', 'banana', 'cherry', 'date']</span>
</code></pre>
<p>Here, <code>toSpliced()</code> removes <code>'banana'</code> and adds <code>'blueberry'</code> at the same position, but the original <code>fruits</code> array stays unchanged.</p>
<h3 id="heading-comparison-with-the-traditional-splice-method">Comparison with the Traditional <code>splice</code> Method</h3>
<p>The key difference between <code>splice()</code> and <code>toSpliced()</code> is that <code>splice()</code> changes the original array, while <code>toSpliced()</code> leaves it untouched and returns a new array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];

<span class="hljs-comment">// Using splice()</span>
<span class="hljs-keyword">const</span> splicedNumbers = numbers.splice(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">10</span>, <span class="hljs-number">20</span>);
<span class="hljs-built_in">console</span>.log(splicedNumbers); <span class="hljs-comment">// Output: [2, 3] (Removed elements)</span>
<span class="hljs-built_in">console</span>.log(numbers);        <span class="hljs-comment">// Output: [1, 10, 20, 4] (Original array changed)</span>

<span class="hljs-comment">// Using toSpliced()</span>
<span class="hljs-keyword">const</span> newNumbers = numbers.toSpliced(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>);
<span class="hljs-built_in">console</span>.log(newNumbers);     <span class="hljs-comment">// Output: [1, 5, 6, 4]</span>
<span class="hljs-built_in">console</span>.log(numbers);        <span class="hljs-comment">// Output: [1, 10, 20, 4] (Original array unchanged)</span>
</code></pre>
<p><code>splice()</code> modifies the original array, but <code>toSpliced()</code> does not, giving you more control and avoiding unwanted changes to data.</p>
<h3 id="heading-use-cases-for-functional-programming">Use Cases for Functional Programming</h3>
<p><code>toSpliced()</code> fits well with functional programming, which favors avoiding changes to existing data. For example, in applications where you often manipulate arrays (like lists of users or products), <code>toSpliced()</code> helps keep the original data intact.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> users = [<span class="hljs-string">'Dave'</span>, <span class="hljs-string">'Alexa'</span>, <span class="hljs-string">'Katie'</span>];

<span class="hljs-comment">// Remove 'Bob' and add 'Dan' without modifying the original array</span>
<span class="hljs-keyword">const</span> updatedUsers = users.toSpliced(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-string">'Dan'</span>);

<span class="hljs-built_in">console</span>.log(updatedUsers); <span class="hljs-comment">// Output: ['Dave', 'Dan', 'Katie']</span>
<span class="hljs-built_in">console</span>.log(users);        <span class="hljs-comment">// Output: ['Dave', 'Alexa', 'Katie']</span>
</code></pre>
<p>This method makes it easier to manage and work with arrays in situations where the original data needs to be preserved.</p>
<h3 id="heading-avoiding-pitfalls-with-tospliced">Avoiding Pitfalls with <code>toSpliced</code></h3>
<p>The main advantage of <code>toSpliced()</code> is that it avoids unintended changes to the original array. It reduces the chances of bugs caused by data being accidentally modified.</p>
<p>But it’s important to note that creating a new array with <code>toSpliced()</code> means that the old array is not directly updated, so you’ll need to assign the result to a new variable if you want to use the modified data.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> colors = [<span class="hljs-string">'red'</span>, <span class="hljs-string">'green'</span>, <span class="hljs-string">'blue'</span>];

<span class="hljs-comment">// Create a new array that adds 'yellow' at index 1</span>
<span class="hljs-keyword">const</span> newColors = colors.toSpliced(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'yellow'</span>);

<span class="hljs-built_in">console</span>.log(newColors); <span class="hljs-comment">// Output: ['red', 'yellow', 'green', 'blue']</span>
<span class="hljs-built_in">console</span>.log(colors);    <span class="hljs-comment">// Output: ['red', 'green', 'blue'] (Original unchanged)</span>
</code></pre>
<h2 id="heading-with-modify-array-elements-by-index"><code>with</code>: Modify Array Elements by Index</h2>
<p>The <code>with</code> method is a new and powerful tool introduced in JavaScript to help replace elements in an array without changing the original array.</p>
<p>This is helpful when you need to update specific items without affecting the rest of the data, keeping your original array intact. It promotes safer and cleaner code, especially when working with large datasets or in functional programming styles.</p>
<h3 id="heading-syntax-and-key-parameters-1">Syntax and Key Parameters</h3>
<p>The <code>with</code> method allows you to create a new array where one element at a specific index is replaced.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newArray = array.with(index, newValue);
</code></pre>
<ul>
<li><p><strong>index</strong>: The position of the element you want to replace.</p>
</li>
<li><p><strong>newValue</strong>: The value to insert at the given index.</p>
</li>
</ul>
<h3 id="heading-examples-of-using-with-for-element-replacement">Examples of Using <code>with</code> for Element Replacement</h3>
<p>Let’s explore a simple example where you want to replace an item at a specific position:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruits = [<span class="hljs-string">'apple'</span>, <span class="hljs-string">'banana'</span>, <span class="hljs-string">'cherry'</span>];

<span class="hljs-comment">// Replace 'banana' with 'blueberry' at index 1</span>
<span class="hljs-keyword">const</span> newFruits = fruits.with(<span class="hljs-number">1</span>, <span class="hljs-string">'blueberry'</span>);

<span class="hljs-built_in">console</span>.log(newFruits); <span class="hljs-comment">// Output: ['apple', 'blueberry', 'cherry']</span>
<span class="hljs-built_in">console</span>.log(fruits);    <span class="hljs-comment">// Output: ['apple', 'banana', 'cherry']</span>
</code></pre>
<p>In this example, we replaced <code>'banana'</code> with <code>'blueberry'</code>, but the original <code>fruits</code> array stays the same, which is very useful to avoid side effects in your code.</p>
<h3 id="heading-replacing-elements-in-arrays-while-maintaining-immutability">Replacing Elements in Arrays While Maintaining Immutability</h3>
<p>One of the key strengths of the <code>with</code> method is that it does not change the original array. This helps maintain immutability, which is often needed when handling data in larger applications. You can confidently replace elements without worrying about accidental changes to the original data.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>];

<span class="hljs-comment">// Replace the number at index 2 (30) with 35</span>
<span class="hljs-keyword">const</span> updatedNumbers = numbers.with(<span class="hljs-number">2</span>, <span class="hljs-number">35</span>);

<span class="hljs-built_in">console</span>.log(updatedNumbers); <span class="hljs-comment">// Output: [10, 20, 35, 40]</span>
<span class="hljs-built_in">console</span>.log(numbers);        <span class="hljs-comment">// Output: [10, 20, 30, 40] (Original unchanged)</span>
</code></pre>
<p>This makes the <code>with</code> method an ideal choice when you need to update data but still want to reference the original array elsewhere in your code.</p>
<h3 id="heading-applications-of-the-with-method">Applications of the <code>with</code> Method</h3>
<p>The <code>with</code> method can be applied in many scenarios, such as updating user profiles, modifying a list of items, or working with any data that requires selective updates. For example, when dealing with a table of users, you can replace a specific user’s data without affecting the entire dataset.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> users = [<span class="hljs-string">'Dave'</span>, <span class="hljs-string">'Alexa'</span>, <span class="hljs-string">'Katie'</span>];

<span class="hljs-comment">// Update Bob's name to 'Dan'</span>
<span class="hljs-keyword">const</span> updatedUsers = users.with(<span class="hljs-number">1</span>, <span class="hljs-string">'Dan'</span>);

<span class="hljs-built_in">console</span>.log(updatedUsers); <span class="hljs-comment">// Output: ['Dave', 'Dan', 'Katie']</span>
<span class="hljs-built_in">console</span>.log(users);        <span class="hljs-comment">// Output: ['Dave', 'Alexa', 'Katie'] (Original unchanged)</span>
</code></pre>
<p>This method helps avoid confusion that can arise from unwanted changes to data when updating specific elements in an array.</p>
<h3 id="heading-with-vs-traditional-methods-for-element-replacement"><code>with</code> vs Traditional Methods for Element Replacement</h3>
<p>Before the introduction of <code>with</code>, replacing elements in arrays required methods like <code>splice()</code> or manual approaches, both of which would modify the original array:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> colors = [<span class="hljs-string">'red'</span>, <span class="hljs-string">'green'</span>, <span class="hljs-string">'blue'</span>];

<span class="hljs-comment">// Traditional method (using mutation)</span>
colors.splice(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-string">'yellow'</span>);
<span class="hljs-built_in">console</span>.log(colors); <span class="hljs-comment">// Output: ['red', 'yellow', 'blue'] (Original array changed)</span>
</code></pre>
<p>With the new <code>with</code> method, you can avoid this problem:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> colors = [<span class="hljs-string">'red'</span>, <span class="hljs-string">'green'</span>, <span class="hljs-string">'blue'</span>];

<span class="hljs-comment">// Using `with` method</span>
<span class="hljs-keyword">const</span> newColors = colors.with(<span class="hljs-number">1</span>, <span class="hljs-string">'yellow'</span>);
<span class="hljs-built_in">console</span>.log(newColors); <span class="hljs-comment">// Output: ['red', 'yellow', 'blue']</span>
<span class="hljs-built_in">console</span>.log(colors);    <span class="hljs-comment">// Output: ['red', 'green', 'blue'] (Original unchanged)</span>
</code></pre>
<p>The <code>with</code> method ensures the original data remains intact which makes it a better option for situations where immutability is important.</p>
<h2 id="heading-combining-new-javascript-methods-for-advanced-data-manipulation">Combining New JavaScript Methods for Advanced Data Manipulation</h2>
<p>The new JavaScript methods like <code>findLast</code>, <code>toSorted</code>, and <code>with</code> provide powerful tools for managing and transforming data. When used together, they allow you to create complex data operations in a simple and readable way.</p>
<p>Let’s look at how you can combine these methods to handle data efficiently and write clean, effective code.</p>
<h3 id="heading-how-to-chain-methods-like-findlast-tosorted-and-with">How to Chain Methods like <code>findLast</code>, <code>toSorted</code>, and <code>with</code></h3>
<p>Chaining methods in JavaScript lets you apply multiple transformations to your data in a single flow.</p>
<p>For example, you might want to sort an array, find the last matching element, and then replace it with a new value. Here’s how you can do that using <code>toSorted</code>, <code>findLast</code>, and <code>with</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">20</span>, <span class="hljs-number">5</span>, <span class="hljs-number">15</span>, <span class="hljs-number">30</span>, <span class="hljs-number">10</span>];

<span class="hljs-comment">// Chain methods to sort, find the last element greater than 10, and replace it</span>
<span class="hljs-keyword">const</span> result = numbers
  .toSorted(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a - b)   <span class="hljs-comment">// Sort the array in ascending order</span>
  .with(numbers.findLastIndex(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num &gt; <span class="hljs-number">10</span>), <span class="hljs-number">100</span>);  <span class="hljs-comment">// Find and replace the last match</span>

<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: [5, 10, 15, 20, 100]</span>
</code></pre>
<p>In this example:</p>
<ul>
<li><p><code>toSorted()</code> arranges the array in ascending order without changing the original array.</p>
</li>
<li><p><code>findLastIndex()</code> finds the last number greater than 10.</p>
</li>
<li><p><code>with()</code> replaces that number (which is 30) with 100, without modifying the original array.</p>
</li>
</ul>
<p>This combination is useful when working with complex data workflows and ensures that the original data remains unchanged.</p>
<h3 id="heading-creating-complex-data-transformations-with-ease">Creating Complex Data Transformations with Ease</h3>
<p>The real power of these methods shines when you want to perform multiple actions on arrays in a readable and organized way. Here’s another example where we combine sorting, filtering, and replacing data all in one flow:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> students = [
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Dave'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">85</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Alexa'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">75</span> },
  { <span class="hljs-attr">name</span>: <span class="hljs-string">'Katoe'</span>, <span class="hljs-attr">score</span>: <span class="hljs-number">90</span> }
];

<span class="hljs-comment">// Chain methods to sort, find the last student with a score above 80, and update their score</span>
<span class="hljs-keyword">const</span> updatedStudents = students
  .toSorted(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> b.score - a.score)   <span class="hljs-comment">// Sort students by score (descending)</span>
  .with(
    students.findLastIndex(<span class="hljs-function"><span class="hljs-params">student</span> =&gt;</span> student.score &gt; <span class="hljs-number">80</span>), 
    { ...students.findLast(<span class="hljs-function"><span class="hljs-params">student</span> =&gt;</span> student.score &gt; <span class="hljs-number">80</span>), <span class="hljs-attr">score</span>: <span class="hljs-number">95</span> }
  );

<span class="hljs-built_in">console</span>.log(updatedStudents);
</code></pre>
<p>In this case:</p>
<ul>
<li><p><code>toSorted()</code> sorts students based on their scores from highest to lowest.</p>
</li>
<li><p><code>findLastIndex()</code> identifies the last student who scored above 80.</p>
</li>
<li><p><code>with()</code> creates a new array with that student’s score updated to 95.</p>
</li>
</ul>
<p>The flexibility of combining these methods means you can manage even complex data structures easily without compromising readability or changing the original data.</p>
<h3 id="heading-best-practices-for-writing-clean-efficient-code-with-these-methods">Best Practices for Writing Clean, Efficient Code with These Methods</h3>
<p>To write clean and efficient code, consider the following tips when using these new JavaScript methods:</p>
<ol>
<li><p><strong>Avoid Mutating the Original Data</strong>: Use methods like <code>toSorted</code>, <code>toReversed</code>, and <code>with</code> that do not change the original array. This ensures that your data remains consistent throughout your code.</p>
</li>
<li><p><strong>Use Chaining for Readability</strong>: Chain methods when performing multiple transformations. This keeps your code concise and easier to follow.</p>
</li>
<li><p><strong>Use Arrow Functions</strong>: Short arrow functions help reduce the complexity of your code. For instance:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> sortedNumbers = numbers.toSorted(<span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a - b);
</code></pre>
</li>
<li><p><strong>Combine Methods Thoughtfully</strong>: Make sure the methods you chain together logically follow each other. For example, it makes sense to sort data first before finding the last element that matches a condition.</p>
</li>
<li><p><strong>Handle Large Datasets Carefully</strong>: For very large arrays, consider performance implications. Methods like <code>findLast</code> and <code>toSorted</code> might take time on bigger datasets, so always test your code’s performance with realistic data sizes.</p>
</li>
</ol>
<h2 id="heading-backward-compatibility-and-polyfills">Backward Compatibility and Polyfills</h2>
<p>As new JavaScript features are added, not all browsers will support them right away. It’s important to make sure your code still works on older browsers without breaking. Let's talk about how you can handle this and introduce polyfills to fill the gap when using the latest features.</p>
<h3 id="heading-how-to-ensure-backward-compatibility-with-older-browsers">How to Ensure Backward Compatibility with Older Browsers</h3>
<p>To make sure your code works smoothly on older browsers that don’t support new JavaScript methods like <code>findLast</code>, <code>toSorted</code>, or <code>with</code>, you can add checks to see if a feature is available before using it. This way, the code doesn’t fail on unsupported browsers.</p>
<p>Here’s an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (<span class="hljs-built_in">Array</span>.prototype.findLast) {
  <span class="hljs-comment">// Use the findLast method</span>
  <span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
  <span class="hljs-keyword">const</span> lastOdd = arr.findLast(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num % <span class="hljs-number">2</span> !== <span class="hljs-number">0</span>);
  <span class="hljs-built_in">console</span>.log(lastOdd); <span class="hljs-comment">// Output: 5</span>
} <span class="hljs-keyword">else</span> {
  <span class="hljs-comment">// Fallback code for older browsers</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'findLast is not supported'</span>);
}
</code></pre>
<p>This example checks if <code>findLast</code> exists. If it doesn’t, you can run a fallback or show a message. This approach helps maintain backward compatibility.</p>
<h3 id="heading-overview-of-polyfills-for-new-javascript-features">Overview of Polyfills for New JavaScript Features</h3>
<p>A <strong>polyfill</strong> is a piece of code that adds support for new JavaScript features on browsers that don’t have them yet. It basically provides an alternative implementation of the feature.</p>
<p>For example, let’s create a polyfill for <code>findLast</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (!<span class="hljs-built_in">Array</span>.prototype.findLast) {
  <span class="hljs-built_in">Array</span>.prototype.findLast = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">callback</span>) </span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-built_in">this</span>.length - <span class="hljs-number">1</span>; i &gt;= <span class="hljs-number">0</span>; i--) {
      <span class="hljs-keyword">if</span> (callback(<span class="hljs-built_in">this</span>[i], i, <span class="hljs-built_in">this</span>)) {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>[i];
      }
    }
    <span class="hljs-keyword">return</span> <span class="hljs-literal">undefined</span>;
  };
}
</code></pre>
<p>This polyfill adds the <code>findLast</code> method to arrays that don’t support it. Now, even older browsers can run code that uses this feature.</p>
<p>Polyfills for common methods are available on sites like <strong>MDN</strong> or through libraries like <strong>core-js</strong> that cover many modern JavaScript features.</p>
<h3 id="heading-tools-and-resources-to-test-browser-support">Tools and Resources to Test Browser Support</h3>
<p>Before using new features, it’s helpful to check how widely supported they are across different browsers. Here are some tools that can assist:</p>
<ol>
<li><p><strong>Can I Use</strong>: A popular website that shows browser compatibility for new JavaScript features. You can search for methods like <code>toSorted</code> or <code>findLast</code> to see which browsers support them.</p>
<p> Example: <a target="_blank" href="https://caniuse.com/?search=findLast">Can I Use: findLast</a></p>
</li>
<li><p><strong>Babel</strong>: A JavaScript compiler that converts new JavaScript code into older versions that work on older browsers. Babel can automatically add polyfills for unsupported features.</p>
<p> Example usage with Babel:</p>
<pre><code class="lang-bash"> npm install --save-dev @babel/preset-env
</code></pre>
<p> Then configure Babel to use the preset:</p>
<pre><code class="lang-json"> {
   <span class="hljs-attr">"presets"</span>: [<span class="hljs-string">"@babel/preset-env"</span>]
 }
</code></pre>
</li>
<li><p><a target="_blank" href="http://Polyfill.io"><strong>Polyfill.io</strong></a>: A service that automatically serves the necessary polyfills based on the user's browser.</p>
<p> To use it, simply add this script to your HTML:</p>
<pre><code class="lang-html"> <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://polyfill.io/v3/polyfill.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
</li>
</ol>
<p>This script automatically adds only the polyfills needed for the browser loading the page, making it an easy way to handle backward compatibility.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>We’ve explored some of the latest JavaScript features, including methods like <code>findLast</code>, <code>findLastIndex</code>, <code>toReversed</code>, <code>toSorted</code>, <code>toSpliced</code>, and <code>with</code>.</p>
<p>These new additions bring more flexibility and efficiency to working with arrays. They help avoid unwanted changes to the original data and make code cleaner and easier to follow. For example, <code>toSorted</code> allows sorting without altering the original array, and <code>findLast</code> makes it simpler to locate the last matching element in a list.</p>
<p>Each of these methods saves time and reduces complexity when managing and transforming data.</p>
<p>As JavaScript continues to evolve, it’s important to start using these methods in future projects. They can simplify complex data manipulation tasks and make your code easier to maintain. Try adding these methods to your current codebase and explore how they can improve the way you write and manage JavaScript.</p>
<p>The next time you work with arrays, consider using <code>toSorted</code> for sorting, <code>findLast</code> for searching, or <code>with</code> for replacing elements without changing the original data. These small adjustments can have a big impact on the quality of your code.</p>
<p>If you have any questions or suggestions, feel free to reach out on <a target="_blank" href="https://ng.linkedin.com/in/joan-ayebola">LinkedIn</a>. If you enjoyed this content, consider <a target="_blank" href="https://www.buymeacoffee.com/joanayebola">buying me a coffee</a> to support the creation of more developer-friendly contents.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build an Expense Tracker with HTML, CSS, and JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Building projects is a great way to practice and improve your web development skills. And that's what we'll do in this in-depth tutorial: build a practical project using HTML, CSS, and JavaScript. If you often find yourself wondering where all your m... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-an-expense-tracker-with-html-css-and-javascript/</link>
                <guid isPermaLink="false">66e1d2a79abcf10b7699eb34</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML5 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Wed, 11 Sep 2024 17:25:59 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726055511234/dcaa759f-58f9-477d-92da-c8b98b71d310.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Building projects is a great way to practice and improve your web development skills. And that's what we'll do in this in-depth tutorial: build a practical project using HTML, CSS, and JavaScript.</p>
<p>If you often find yourself wondering where all your money went or how you managed to spend so much, then this project is for you. I created a simple expense tracker to help manage my own finances, and I decided to share a step-by-step tutorial with the developer community.</p>
<p>In this tutorial, we'll walk through the process of building a basic expense tracker from scratch. Whether you're new to web development or looking to enhance your skills, this project will provide you with practical experience in HTML, CSS, and JavaScript.</p>
<p>By the end, you'll have a fully functional tool to track your income, manage expenses, and maintain a clear overview of your finances within a sleek and user-friendly interface.</p>
<p>We'll start by setting up the structure of the tracker, move on to styling it to make it visually appealing, and finally, we'll implement the functionality that will bring it to life.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><p><a class="post-section-overview" href="#heading-setting-up-the-html-structure">Setting Up the HTML Structure</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-setting-up-the-html-structure">Styling the Expense Tracker</a> <a class="post-section-overview" href="#heading-styling-the-expense-tracker-with-css">wi</a><a class="post-section-overview" href="#heading-setting-up-the-html-structure">th CSS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-setting-up-the-html-structure">Implementing Function</a><a class="post-section-overview" href="#heading-styling-the-expense-tracker-with-css">ality wit</a><a class="post-section-overview" href="#heading-setting-up-the-html-structure">h JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-setting-up-the-html-structure">Enhancing the U</a><a class="post-section-overview" href="#heading-styling-the-expense-tracker-with-css">ser E</a><a class="post-section-overview" href="#heading-implementing-functionality-with-javascript">xp</a><a class="post-section-overview" href="#heading-styling-the-expense-tracker-with-css">erience</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-setting-up-the-html-structure">Testing and Debugging</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-setting-up-the-html-structure">Concl</a><a class="post-section-overview" href="#heading-enhancing-the-user-experience">us</a><a class="post-section-overview" href="#heading-setting-up-the-html-structure">ion</a></p>
</li>
</ol>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>To get the most out of this tutorial, having a basic understanding of HTML, CSS, and JavaScript will be beneficial. Familiarity with creating simple web pages and handling basic DOM manipulation in JavaScript will help you follow along more easily.</p>
<p>But if you're new to these technologies, don't worry – I'll guide you through each step with detailed explanations.</p>
<h2 id="heading-setting-up-the-html-structure">Setting Up the HTML Structure</h2>
<p>First of all, we need to set up the basic HTML structure. This will serve as the foundation for everythin<a class="post-section-overview" href="#heading-enhancing-the-user-experience">g</a> else we'll build. Don’t worr<a class="post-section-overview" href="#heading-testing-and-debugging">y</a> if you’re new to HTML. I'll guide you through each step.</p>
<h3 id="heading-1-create-a-basic-html-template">1. Create a Basic HTML Template</h3>
<p>Start by creating a new file and naming it <code>index.html</code>. This file will hold the structure of our expense tracker. Every HTML file starts with a basic template, which includes the <code>&lt;!DOCTYPE html&gt;</code> declaration, the <code>&lt;html&gt;</code> tag, and the head and body sections.</p>
<p>Here’s what your initial HTML template should look like:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Expense Tracker<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">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h3 id="heading-2-adding-a-container">2. Adding a Container</h3>
<p>Inside the <code>&lt;body&gt;</code> tag, let’s start by adding a <code>div</code> element with a class of <code>container</code>. This container will hold all the content of our expense tracker, such as the title, input fields, and summary. We use a container to center everything on the page and make sure our layout looks neat.</p>
<p>Here’s how you can do it:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- All content will go here --&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>
</code></pre>
<h3 id="heading-3-add-the-expense-tracker-title">3. Add the Expense Tracker Title</h3>
<p>Now, let’s add a title to our expense tracker. We’ll use the <code>&lt;h1&gt;</code> tag for this, which is typically used for the main heading on a webpage.</p>
<p>Add the following code inside the <code>container</code> div:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Expense Tracker<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
</code></pre>
<p>This heading will display prominently at the top of your page, letting users know what the application is about.</p>
<h3 id="heading-4-setting-up-sections-for-income-and-expenses">4. Setting Up Sections for Income and Expenses</h3>
<p>Next, we'll add sections for income and expenses. These sections will include input fields where users can enter their income and expense details.</p>
<p>Start by adding two <code>div</code> elements, each with a class of <code>section</code>. One section will be for income, and the other for expenses. Here’s the code:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"section"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Income<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Income input fields will go here --&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"section"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Expenses<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Expense input fields will go here --&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>The <code>&lt;h2&gt;</code> tags inside these sections serve as subheadings to label each section. We’ll add input fields in the next step.</p>
<h3 id="heading-5-adding-input-fields">5. Adding Input Fields</h3>
<p>Now, let’s add input fields for the income section. Users will need to enter a description (for example, “Salary”) and an amount. Each input field will be wrapped in a <code>div</code> with a class of <code>input-group</code> for easy styling later.</p>
<p>While this example uses Nigerian Naira (₦) for the currency, you can easily adapt it to any currency you prefer. Simply replace the currency symbol in the placeholder or any labels to match your needs.</p>
<p>Here’s how you can add the input fields:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input-group"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"income-description"</span>&gt;</span>Description<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"income-description"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"e.g. Salary"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input-group"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"income-amount"</span>&gt;</span>Amount (₦)<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"income-amount"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"e.g. 100000"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>Do the same for the expenses section, but this time, we’ll also add a dropdown for the category of the expense:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input-group"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"expense-description"</span>&gt;</span>Description<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"expense-description"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"e.g. Rent"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input-group"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"expense-category"</span>&gt;</span>Category<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"expense-category"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Housing"</span>&gt;</span>Housing<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Food"</span>&gt;</span>Food<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Transportation"</span>&gt;</span>Transportation<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Entertainment"</span>&gt;</span>Entertainment<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Others"</span>&gt;</span>Others<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input-group"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"expense-amount"</span>&gt;</span>Amount (₦)<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"expense-amount"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"e.g. 50000"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h3 id="heading-6-add-a-button-to-each-section">6. Add a Button to Each Section</h3>
<p>Finally, we need a button in each section that users will click to add their income or expense to the tracker. Place a <code>button</code> element inside each section like this:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"button-group"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"addIncome()"</span>&gt;</span>Add Income<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>And for the expenses section:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"button-group"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"addExpense()"</span>&gt;</span>Add Expense<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h3 id="heading-7-displaying-the-transaction-history">7. Displaying the Transaction History</h3>
<p>After the income and expenses sections, we need a place to display the transaction history. We’ll use a table for this, as it’s a clean and organized way to present data.</p>
<p>Add the following code after the expenses section:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"table-container"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Transaction History<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">table</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">thead</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Description<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Category<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Amount (₦)<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Type<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Action<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span> <span class="hljs-comment">&lt;!-- Column for delete button --&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">thead</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">tbody</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"transaction-history"</span>&gt;</span>
            <span class="hljs-comment">&lt;!-- Transactions will appear here --&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">tbody</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h3 id="heading-8-adding-a-summary-section">8. Adding a Summary Section</h3>
<p>At the bottom of the container, let’s add a summary section that shows the total income, total expenses, and the balance.</p>
<p>Here’s the code for the summary:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"summary"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Budget Summary<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>Total Income: ₦<span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"total-income"</span>&gt;</span>0<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Total Expenses: ₦<span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"total-expenses"</span>&gt;</span>0<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Balance: ₦<span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"balance"</span>&gt;</span>0<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h3 id="heading-9-adding-a-clear-all-button">9. Adding a Clear All Button</h3>
<p>Lastly, include a button that will allow users to clear all the data in one click. This is particularly useful if they want to reset everything.</p>
<p>Here’s how to add the clear button:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"clear-button-group"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"clearAll()"</span>&gt;</span>Clear All<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<h3 id="heading-10-putting-it-all-together">10. Putting It All Together</h3>
<p>When you put all the pieces together, your HTML structure 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> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Creative Budget Planner<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Expense Tracker<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"section"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Income<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input-group"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"income-description"</span>&gt;</span>Description<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"income-description"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"e.g. Salary"</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input-group"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"income-amount"</span>&gt;</span>Amount (₦)<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"income-amount"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"e.g. 100000"</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"button-group"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"addIncome()"</span>&gt;</span>Add Income<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"section"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Expenses<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input-group"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"expense-description"</span>&gt;</span>Description<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"expense-description"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"e.g. Rent"</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input-group"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"expense-category"</span>&gt;</span>Category<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"expense-category"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Housing"</span>&gt;</span>Housing<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Food"</span>&gt;</span>Food<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Transportation"</span>&gt;</span>Transportation<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Entertainment"</span>&gt;</span>Entertainment<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Others"</span>&gt;</span>Others<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input-group"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"expense-amount"</span>&gt;</span>Amount (₦)<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"expense-amount"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"e.g. 50000"</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"button-group"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"addExpense()"</span>&gt;</span>Add Expense<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"table-container"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Transaction History<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">table</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">thead</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Description<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Category<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Amount (₦)<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Type<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                        <span class="hljs-tag">&lt;<span class="hljs-name">th</span>&gt;</span>Action<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
                    <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">thead</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">tbody</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"transaction-history"</span>&gt;</span>
                    <span class="hljs-comment">&lt;!-- Transactions will appear here --&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">tbody</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"summary"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Budget Summary<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>Total Income: ₦<span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"total-income"</span>&gt;</span>0<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Total Expenses: ₦<span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"total-expenses"</span>&gt;</span>0<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Balance: ₦<span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"balance"</span>&gt;</span>0<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">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">"clear-button-group"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"clearAll()"</span>&gt;</span>Clear All<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/NWZEvLy" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-styling-the-expense-tracker-with-css">Styling the Expense Tracker with CSS</h2>
<p>Now that we have our HTML structure in place, it’s time to make our expense tracker visually appealing by adding some CSS. We’ll start with basic styling and then move on to more specific details to ensure everything looks neat and user-friendly.</p>
<h3 id="heading-1-setting-up-the-css-file">1. Setting Up the CSS File</h3>
<p>First, create a new file named <code>styles.css</code> in the same directory as your <code>index.html</code> file. Link this CSS file to your HTML by adding the following line inside the <code>&lt;head&gt;</code> section of <code>index.html</code>:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"styles.css"</span>&gt;</span>
</code></pre>
<p>This line tells your HTML file to use the styles defined in <code>styles.css</code>.</p>
<h3 id="heading-2-styling-the-body">2. Styling the Body</h3>
<p>Let’s start by adding some basic styles to the <code>&lt;body&gt;</code> to set a nice background color, font, and layout. Open <code>styles.css</code> and add the following code:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">font-family</span>: Arial, sans-serif;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f4f4f4</span>;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</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">height</span>: <span class="hljs-number">100vh</span>;
}
</code></pre>
<ul>
<li><p><strong>font-family:</strong> We’re using a simple and clean font.</p>
</li>
<li><p><strong>background-color:</strong> A light grey background will give our tracker a soft look.</p>
</li>
<li><p><strong>display, justify-content, align-items, height:</strong> These properties center the content vertically and horizontally.</p>
</li>
</ul>
<h3 id="heading-3-styling-the-container">3. Styling the Container</h3>
<p>Next, we’ll style the <code>.container</code> to give it a clean, organized look:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">background-color</span>: white;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">10px</span> <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.1</span>);
    <span class="hljs-attribute">max-width</span>: <span class="hljs-number">600px</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}
</code></pre>
<ul>
<li><p><strong>background-color:</strong> White makes the content stand out against the grey background.</p>
</li>
<li><p><strong>padding:</strong> Adds space inside the container so the content isn’t touching the edges.</p>
</li>
<li><p><strong>border-radius:</strong> Rounds the corners for a modern look.</p>
</li>
<li><p><strong>box-shadow:</strong> Adds a subtle shadow to lift the container off the page slightly.</p>
</li>
<li><p><strong>max-width and width:</strong> Ensures the container is responsive and doesn’t exceed a certain width.</p>
</li>
</ul>
<h3 id="heading-4-styling-the-headings">4. Styling the Headings</h3>
<p>Let’s style the headings to make them more visually distinct:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">h1</span>, <span class="hljs-selector-tag">h2</span> {
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#333</span>;
    <span class="hljs-attribute">text-align</span>: center;
}

<span class="hljs-selector-tag">h1</span> {
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-tag">h2</span> {
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">15px</span>;
}
</code></pre>
<ul>
<li><p><strong>color:</strong> A dark grey color for the text will keep it readable.</p>
</li>
<li><p><strong>text-align:</strong> Centers the headings to create a balanced layout.</p>
</li>
<li><p><strong>margin-bottom:</strong> Adds space below the headings.</p>
</li>
</ul>
<h3 id="heading-5-styling-the-input-groups">5. Styling the Input Groups</h3>
<p>Now, let’s style the input fields and labels within the <code>.input-group</code> class:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.input-group</span> {
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">15px</span>;
}

<span class="hljs-selector-class">.input-group</span> <span class="hljs-selector-tag">label</span> {
    <span class="hljs-attribute">display</span>: block;
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">5px</span>;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#555</span>;
}

<span class="hljs-selector-class">.input-group</span> <span class="hljs-selector-tag">input</span>,
<span class="hljs-selector-class">.input-group</span> <span class="hljs-selector-tag">select</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-built_in">calc</span>(<span class="hljs-number">100%</span> - <span class="hljs-number">10px</span>);
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid <span class="hljs-number">#ddd</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
    <span class="hljs-attribute">box-sizing</span>: border-box;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
}
</code></pre>
<ul>
<li><p><strong>margin-bottom:</strong> Adds space between input groups.</p>
</li>
<li><p><strong>display: block:</strong> Ensures the labels take up the full width.</p>
</li>
<li><p><strong>width:</strong> Makes the input fields and select elements responsive.</p>
</li>
<li><p><strong>padding, border, border-radius:</strong> Creates a more polished look for the inputs.</p>
</li>
<li><p><strong>box-sizing:</strong> Ensures padding is included in the element’s total width.</p>
</li>
</ul>
<h3 id="heading-6-styling-the-buttons">6. Styling the Buttons</h3>
<p>Let’s give the buttons a more interactive and appealing look:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.button-group</span> <span class="hljs-selector-tag">button</span>,
<span class="hljs-selector-class">.clear-button-group</span> <span class="hljs-selector-tag">button</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#FF69B4</span>;
    <span class="hljs-attribute">color</span>: white;
    <span class="hljs-attribute">border</span>: none;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
    <span class="hljs-attribute">cursor</span>: pointer;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
}

<span class="hljs-selector-class">.button-group</span> <span class="hljs-selector-tag">button</span><span class="hljs-selector-pseudo">:hover</span>,
<span class="hljs-selector-class">.clear-button-group</span> <span class="hljs-selector-tag">button</span><span class="hljs-selector-pseudo">:hover</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#FF1493</span>;
}
</code></pre>
<ul>
<li><p><strong>background-color:</strong> A vibrant pink for the buttons to make them stand out.</p>
</li>
<li><p><strong>color:</strong> White text for contrast against the pink background.</p>
</li>
<li><p><strong>border, padding, border-radius:</strong> No border, ample padding, and rounded corners for a modern look.</p>
</li>
<li><p><strong>cursor:</strong> Changes the cursor to a pointer on hover, indicating the button is clickable.</p>
</li>
<li><p><strong>hover:</strong> Darkens the button color when hovered for a subtle interaction effect.</p>
</li>
</ul>
<h3 id="heading-7-styling-the-transaction-history-table">7. Styling the Transaction History Table</h3>
<p>We’ll also style the transaction history table to ensure it’s easy to read and visually consistent with the rest of the tracker:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.table-container</span> {
    <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-tag">table</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
    <span class="hljs-attribute">border-collapse</span>: collapse;
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-tag">th</span>, <span class="hljs-selector-tag">td</span> {
    <span class="hljs-attribute">text-align</span>: left;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">border-bottom</span>: <span class="hljs-number">1px</span> solid <span class="hljs-number">#ddd</span>;
}

<span class="hljs-selector-tag">th</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#FF69B4</span>;
    <span class="hljs-attribute">color</span>: white;
}

<span class="hljs-selector-tag">td</span> {
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#333</span>;
}

<span class="hljs-selector-tag">td</span> <span class="hljs-selector-tag">button</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#FF1493</span>;
    <span class="hljs-attribute">color</span>: white;
    <span class="hljs-attribute">border</span>: none;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">5px</span> <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">3px</span>;
    <span class="hljs-attribute">cursor</span>: pointer;
}

<span class="hljs-selector-tag">td</span> <span class="hljs-selector-tag">button</span><span class="hljs-selector-pseudo">:hover</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#C71585</span>;
}
</code></pre>
<ul>
<li><p><strong>border-collapse:</strong> Ensures there’s no gap between table borders.</p>
</li>
<li><p><strong>padding, border-bottom:</strong> Adds padding inside table cells and a border under each row for separation.</p>
</li>
<li><p><strong>background-color for th:</strong> Matches the buttons for a cohesive design.</p>
</li>
<li><p><strong>td button:</strong> Adds a delete button inside table cells, styled similarly to the other buttons.</p>
</li>
</ul>
<h3 id="heading-8-styling-the-summary-section">8. Styling the Summary Section</h3>
<p>Finally, let’s style the summary section to make it stand out:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.summary</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#FFB3FF</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">15px</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">text-align</span>: center;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#333</span>;
}

<span class="hljs-selector-class">.summary</span> <span class="hljs-selector-tag">p</span> {
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span> <span class="hljs-number">0</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
}

<span class="hljs-selector-class">.summary</span> <span class="hljs-selector-tag">span</span> {
    <span class="hljs-attribute">font-weight</span>: bold;
}
</code></pre>
<ul>
<li><p><strong>background-color:</strong> A soft pink background helps distinguish the summary from the rest of the content.</p>
</li>
<li><p><strong>padding, border-radius:</strong> Adds spacing and rounded corners.</p>
</li>
<li><p><strong>text-align:</strong> Centers the text within the summary.</p>
</li>
<li><p><strong>font-size, font-weight:</strong> Increases the font size and weight to make the totals and balance more prominent.</p>
</li>
</ul>
<h3 id="heading-9-putting-it-all-together">9. Putting It All Together</h3>
<p>Here’s how your <code>styles.css</code> file should look with all the styles combined:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">font-family</span>: Arial, sans-serif;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f4f4f4</span>;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</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">height</span>: <span class="hljs-number">100vh</span>;
}

<span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">background-color</span>: white;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">10px</span> <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0.1</span>);
    <span class="hljs-attribute">max-width</span>: <span class="hljs-number">600px</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}

<span class="hljs-selector-tag">h1</span>, <span class="hljs-selector-tag">h2</span> {
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#333</span>;
    <span class="hljs-attribute">text-align</span>: center;
}

<span class="hljs-selector-tag">h1</span> {
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-tag">h2</span> {
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">15px</span>;
}

<span class="hljs-selector-class">.input-group</span> {
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">15px</span>;
}

<span class="hljs-selector-class">.input-group</span> <span class="hljs-selector-tag">label</span> {
    <span class="hljs-attribute">display</span>: block;
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">5px</span>;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#555</span>;
}

<span class="hljs-selector-class">.input-group</span> <span class="hljs-selector-tag">input</span>,
<span class="hljs-selector-class">.input-group</span> <span class="hljs-selector-tag">select</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-built_in">calc</span>(<span class="hljs-number">100%</span> - <span class="hljs-number">10px</span>);
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid <span class="hljs-number">#ddd</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
    <span class="hljs-attribute">box-sizing</span>: border-box;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
}

<span class="hljs-selector-class">.button-group</span> <span class="hljs-selector-tag">button</span>,
<span class="hljs-selector-class">.clear-button-group</span> <span class="hljs-selector-tag">button</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#FF69B4</span>;
    <span class="hljs-attribute">color</span>: white;
    <span class="hljs-attribute">border</span>: none;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
    <span class="hljs-attribute">cursor</span>: pointer;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
}

<span class="hljs-selector-class">.button-group</span> <span class="hljs-selector-tag">button</span><span class="hljs-selector-pseudo">:hover</span>,
<span class="hljs-selector-class">.clear-button-group</span> <span class="hljs-selector-tag">button</span><span class="hljs-selector-pseudo">:hover</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#FF1493</span>;
}

<span class="hljs-selector-class">.table-container</span> {
    <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-tag">table</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
    <span class="hljs-attribute">border-collapse</span>: collapse;
    <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-tag">th</span>, <span class="hljs-selector-tag">td</span> {
    <span class="hljs-attribute">text-align</span>: left;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">border-bottom</span>: <span class="hljs-number">1px</span> solid <span class="hljs-number">#ddd</span>;
}

<span class="hljs-selector-tag">th</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#FF69B4</span>;
    <span class="hljs-attribute">color</span>: white;
}

<span class="hljs-selector-tag">td</span> {
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#333</span>;
}

<span class="hljs-selector-tag">td</span> <span class="hljs-selector-tag">button</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#FF1493</span>;
    <span class="hljs-attribute">color</span>: white;
    <span class="hljs-attribute">border</span>: none;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">5px</span> <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">3px</span>;
    <span class="hljs-attribute">cursor</span>: pointer;
}

<span class="hljs-selector-tag">td</span> <span class="hljs-selector-tag">button</span><span class="hljs-selector-pseudo">:hover</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#C71585</span>;
}

<span class="hljs-selector-class">.summary</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#FFB3FF</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">15px</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">text-align</span>: center;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#333</span>;
}

<span class="hljs-selector-class">.summary</span> <span class="hljs-selector-tag">p</span> {
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span> <span class="hljs-number">0</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
}

<span class="hljs-selector-class">.summary</span> <span class="hljs-selector-tag">span</span> {
    <span class="hljs-attribute">font-weight</span>: bold;
}
</code></pre>
<p>With this CSS, your expense tracker should now look clean, modern, and easy to use. You can always tweak the colors, fonts, or layout to better suit your style or branding.</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/rNEQzqb" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<h2 id="heading-how-to-implement-functionality-with-javascript">How to Implement Functionality with JavaScript</h2>
<p>Now that we have our HTML structure and CSS styling in place, it’s time to bring our expense tracker to life using JavaScript. We’ll add functionality so users can add expenses, view a summary, and remove items from the list.</p>
<h3 id="heading-1-setting-up-the-javascript-file">1. Setting Up the JavaScript File</h3>
<p>First, create a new file named <code>script.js</code> in the same directory as your <code>index.html</code> file. Link this JavaScript file to your HTML by adding the following line just before the closing <code>&lt;/body&gt;</code> tag in <code>index.html</code>:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>This line tells your HTML file to execute the JavaScript code from <code>script.js</code>.</p>
<h3 id="heading-2-defining-variables">2. Defining Variables</h3>
<p>Let’s start by defining some variables to reference key elements in our HTML. Open <code>script.js</code> and add the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> expenseForm = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'expense-form'</span>);
<span class="hljs-keyword">const</span> expenseInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'expense-input'</span>);
<span class="hljs-keyword">const</span> amountInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'amount-input'</span>);
<span class="hljs-keyword">const</span> categoryInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'category-input'</span>);
<span class="hljs-keyword">const</span> transactionList = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'transaction-list'</span>);
<span class="hljs-keyword">const</span> totalExpense = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'total-expense'</span>);
<span class="hljs-keyword">const</span> totalIncome = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'total-income'</span>);
<span class="hljs-keyword">const</span> balance = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'balance'</span>);
</code></pre>
<p>Here’s what each variable does:</p>
<ul>
<li><p><strong>expenseForm:</strong> References the form where users enter new expenses.</p>
</li>
<li><p><strong>expenseInput:</strong> References the input field for the expense description.</p>
</li>
<li><p><strong>amountInput:</strong> References the input field for the expense amount.</p>
</li>
<li><p><strong>categoryInput:</strong> References the dropdown for selecting the expense category.</p>
</li>
<li><p><strong>transactionList:</strong> References the table where we’ll display the transactions.</p>
</li>
<li><p><strong>totalExpense, totalIncome, balance:</strong> Reference the elements showing the summary of expenses, income, and balance.</p>
</li>
</ul>
<h3 id="heading-3-adding-an-expense">3. Adding an Expense</h3>
<p>Next, let’s create a function that handles the addition of a new expense when the form is submitted:</p>
<pre><code class="lang-javascript">expenseForm.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    event.preventDefault();

    <span class="hljs-keyword">const</span> description = expenseInput.value.trim();
    <span class="hljs-keyword">const</span> amount = <span class="hljs-built_in">parseFloat</span>(amountInput.value.trim());
    <span class="hljs-keyword">const</span> category = categoryInput.value;

    <span class="hljs-keyword">if</span> (description === <span class="hljs-string">''</span> || <span class="hljs-built_in">isNaN</span>(amount) || amount &lt;= <span class="hljs-number">0</span>) {
        alert(<span class="hljs-string">'Please enter a valid expense description and amount.'</span>);
        <span class="hljs-keyword">return</span>;
    }

    addTransaction(description, amount, category);
    updateSummary();
    clearInputs();
});

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addTransaction</span>(<span class="hljs-params">description, amount, category</span>) </span>{
    <span class="hljs-keyword">const</span> transactionRow = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'tr'</span>);

    transactionRow.innerHTML = <span class="hljs-string">`
        &lt;td&gt;<span class="hljs-subst">${description}</span>&lt;/td&gt;
        &lt;td&gt;<span class="hljs-subst">${category}</span>&lt;/td&gt;
        &lt;td&gt;<span class="hljs-subst">${amount.toFixed(<span class="hljs-number">2</span>)}</span>&lt;/td&gt;
        &lt;td&gt;&lt;button class="delete-btn"&gt;Delete&lt;/button&gt;&lt;/td&gt;
    `</span>;

    transactionList.appendChild(transactionRow);

    transactionRow.querySelector(<span class="hljs-string">'.delete-btn'</span>).addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        transactionRow.remove();
        updateSummary();
    });
}
</code></pre>
<p>Here’s what’s happening in this code:</p>
<ul>
<li><p><code>event.preventDefault()</code><strong>:</strong> Prevents the form from refreshing the page when submitted.</p>
</li>
<li><p><code>addTransaction</code><strong>:</strong> Adds a new transaction to the table.</p>
</li>
<li><p><code>updateSummary</code><strong>:</strong> Updates the total expenses, income, and balance.</p>
</li>
<li><p><code>clearInputs</code><strong>:</strong> Clears the form inputs after the transaction is added.</p>
</li>
<li><p><strong>delete button:</strong> Allows users to remove a transaction from the list.</p>
</li>
</ul>
<h3 id="heading-4-updating-the-summary">4. Updating the Summary</h3>
<p>To keep track of the total expenses, income, and balance, we’ll create an <code>updateSummary</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateSummary</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> totalExpenses = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">let</span> totalIncomes = <span class="hljs-number">0</span>;

    <span class="hljs-keyword">const</span> transactions = transactionList.querySelectorAll(<span class="hljs-string">'tr'</span>);

    transactions.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">transaction</span>) </span>{
        <span class="hljs-keyword">const</span> amount = <span class="hljs-built_in">parseFloat</span>(transaction.children[<span class="hljs-number">2</span>].textContent);
        <span class="hljs-keyword">const</span> category = transaction.children[<span class="hljs-number">1</span>].textContent;

        <span class="hljs-keyword">if</span> (category === <span class="hljs-string">'Income'</span>) {
            totalIncomes += amount;
        } <span class="hljs-keyword">else</span> {
            totalExpenses += amount;
        }
    });

    totalExpense.textContent = totalExpenses.toFixed(<span class="hljs-number">2</span>);
    totalIncome.textContent = totalIncomes.toFixed(<span class="hljs-number">2</span>);
    balance.textContent = (totalIncomes - totalExpenses).toFixed(<span class="hljs-number">2</span>);
}
</code></pre>
<p>This function loops through each transaction in the table:</p>
<ul>
<li><p><code>totalExpenses</code> <strong>and</strong> <code>totalIncomes</code><strong>:</strong> Calculated by summing the amounts in each category.</p>
</li>
<li><p><code>totalExpense</code><strong>,</strong> <code>totalIncome</code><strong>,</strong> <code>balance</code><strong>:</strong> Updated with the calculated values.</p>
</li>
</ul>
<h3 id="heading-5-clearing-form-inputs">5. Clearing Form Inputs</h3>
<p>To reset the form after adding a transaction, we’ll create a <code>clearInputs</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">clearInputs</span>(<span class="hljs-params"></span>) </span>{
    expenseInput.value = <span class="hljs-string">''</span>;
    amountInput.value = <span class="hljs-string">''</span>;
    categoryInput.value = <span class="hljs-string">'Expense'</span>;
}
</code></pre>
<p>This function simply clears the values of the form inputs.</p>
<h3 id="heading-6-putting-it-all-together">6. Putting It All Together</h3>
<p>Here’s what your <code>script.js</code> file should look like with all the code combined:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> expenseForm = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'expense-form'</span>);
<span class="hljs-keyword">const</span> expenseInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'expense-input'</span>);
<span class="hljs-keyword">const</span> amountInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'amount-input'</span>);
<span class="hljs-keyword">const</span> categoryInput = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'category-input'</span>);
<span class="hljs-keyword">const</span> transactionList = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'transaction-list'</span>);
<span class="hljs-keyword">const</span> totalExpense = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'total-expense'</span>);
<span class="hljs-keyword">const</span> totalIncome = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'total-income'</span>);
<span class="hljs-keyword">const</span> balance = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'balance'</span>);

expenseForm.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    event.preventDefault();

    <span class="hljs-keyword">const</span> description = expenseInput.value.trim();
    <span class="hljs-keyword">const</span> amount = <span class="hljs-built_in">parseFloat</span>(amountInput.value.trim());
    <span class="hljs-keyword">const</span> category = categoryInput.value;

    <span class="hljs-keyword">if</span> (description === <span class="hljs-string">''</span> || <span class="hljs-built_in">isNaN</span>(amount) || amount &lt;= <span class="hljs-number">0</span>) {
        alert(<span class="hljs-string">'Please enter a valid expense description and amount.'</span>);
        <span class="hljs-keyword">return</span>;
    }

    addTransaction(description, amount, category);
    updateSummary();
    clearInputs();
});

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addTransaction</span>(<span class="hljs-params">description, amount, category</span>) </span>{
    <span class="hljs-keyword">const</span> transactionRow = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'tr'</span>);

    transactionRow.innerHTML = <span class="hljs-string">`
        &lt;td&gt;<span class="hljs-subst">${description}</span>&lt;/td&gt;
        &lt;td&gt;<span class="hljs-subst">${category}</span>&lt;/td&gt;
        &lt;td&gt;<span class="hljs-subst">${amount.toFixed(<span class="hljs-number">2</span>)}</span>&lt;/td&gt;
        &lt;td&gt;&lt;button class="delete-btn"&gt;Delete&lt;/button&gt;&lt;/td&gt;
    `</span>;

    transactionList.appendChild(transactionRow);

    transactionRow.querySelector(<span class="hljs-string">'.delete-btn'</span>).addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        transactionRow.remove();
        updateSummary();
    });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateSummary</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> totalExpenses = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">let</span> totalIncomes = <span class="hljs-number">0</span>;

    <span class="hljs-keyword">const</span> transactions = transactionList.querySelectorAll(<span class="hljs-string">'tr'</span>);

    transactions.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">transaction</span>) </span>{
        <span class="hljs-keyword">const</span> amount = <span class="hljs-built_in">parseFloat</span>(transaction.children[<span class="hljs-number">2</span>].textContent);
        <span class="hljs-keyword">const</span> category = transaction.children[<span class="hljs-number">1</span>].textContent;

        <span class="hljs-keyword">if</span> (category === <span class="hljs-string">'Income'</span>) {
            totalIncomes += amount;
        } <span class="hljs-keyword">else</span> {
            totalExpenses += amount;
        }
    });

    totalExpense.textContent = totalExpenses.toFixed(<span class="hljs-number">2</span>);
    totalIncome.textContent = totalIncomes.toFixed(<span class="hljs-number">2</span>);
    balance.textContent = (totalIncomes - totalExpenses).toFixed(<span class="hljs-number">2</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">clearInputs</span>(<span class="hljs-params"></span>) </span>{
    expenseInput.value = <span class="hljs-string">''</span>;
    amountInput.value = <span class="hljs-string">''</span>;
    categoryInput.value = <span class="hljs-string">'Expense'</span>;
}
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/rNEQzQb" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<h3 id="heading-7-testing-the-expense-tracker">7. Testing the Expense Tracker</h3>
<p>With all the code in place, open your <code>index.html</code> file in a web browser. Try adding some expenses and incomes to see how they appear in the transaction table. You should see the total expenses, total income, and balance update automatically as you add and delete transactions.</p>
<p>Congratulations! You’ve now implemented a fully functional expense tracker using JavaScript. This tracker is a simple but powerful tool for managing personal finances, and you can further expand it by adding features like data persistence, additional categories, or more detailed reporting.</p>
<h2 id="heading-how-to-enhance-the-user-experience">How to Enhance the User Experience</h2>
<p>Now that the core functionality of our expense tracker is up and running, it’s time to improve the user experience. Adding small details and thoughtful enhancements can make your application more intuitive, interactive, and enjoyable to use.</p>
<p>Here are some ideas for enhancing the user experience of our expense tracker:</p>
<h3 id="heading-1-adding-real-time-feedback">1. Adding Real-Time Feedback</h3>
<p>It’s helpful for users to receive feedback as they interact with your application. Let’s add a notification feature to confirm that a transaction was successfully added. We’ll do this by showing a brief message after a transaction is submitted.</p>
<p>In your HTML, add a <code>div</code> below the form for the notification message:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"notification"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"hidden"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>In your CSS, style the notification to make it more visible:</p>
<pre><code class="lang-css"><span class="hljs-selector-id">#notification</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#28a745</span>;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">text-align</span>: center;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
}

<span class="hljs-selector-class">.hidden</span> {
  <span class="hljs-attribute">display</span>: none;
}
</code></pre>
<p>Now, in your JavaScript file, we’ll show this notification for a few seconds after a transaction is added:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showNotification</span>(<span class="hljs-params">message</span>) </span>{
    <span class="hljs-keyword">const</span> notification = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'notification'</span>);
    notification.textContent = message;
    notification.classList.remove(<span class="hljs-string">'hidden'</span>);

    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        notification.classList.add(<span class="hljs-string">'hidden'</span>);
    }, <span class="hljs-number">2000</span>); <span class="hljs-comment">// Notification will disappear after 2 seconds</span>
}
</code></pre>
<p>Update the <code>addTransaction</code> function to show this notification when a new transaction is added:</p>
<pre><code class="lang-javascript">addTransaction(description, amount, category);
showNotification(<span class="hljs-string">'Transaction added successfully!'</span>);
updateSummary();
clearInputs();
</code></pre>
<p>This way, each time a user submits a transaction, they get immediate feedback.</p>
<h3 id="heading-2-displaying-a-balance-indicator">2. Displaying a Balance Indicator</h3>
<p>To give users a clearer visual understanding of their financial status, you can implement a balance indicator. This could be a simple color change for the balance display depending on whether the balance is positive or negative.</p>
<p>In your CSS, add styles for different balance states:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.positive</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#28a745</span>; <span class="hljs-comment">/* Green for positive balance */</span>
}

<span class="hljs-selector-class">.negative</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#dc3545</span>; <span class="hljs-comment">/* Red for negative balance */</span>
}
</code></pre>
<p>Then, in your <code>updateSummary</code> function, apply the appropriate class based on the balance:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateSummary</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> totalExpenses = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">let</span> totalIncomes = <span class="hljs-number">0</span>;

    <span class="hljs-keyword">const</span> transactions = transactionList.querySelectorAll(<span class="hljs-string">'tr'</span>);

    transactions.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">transaction</span>) </span>{
        <span class="hljs-keyword">const</span> amount = <span class="hljs-built_in">parseFloat</span>(transaction.children[<span class="hljs-number">2</span>].textContent);
        <span class="hljs-keyword">const</span> category = transaction.children[<span class="hljs-number">1</span>].textContent;

        <span class="hljs-keyword">if</span> (category === <span class="hljs-string">'Income'</span>) {
            totalIncomes += amount;
        } <span class="hljs-keyword">else</span> {
            totalExpenses += amount;
        }
    });

    totalExpense.textContent = totalExpenses.toFixed(<span class="hljs-number">2</span>);
    totalIncome.textContent = totalIncomes.toFixed(<span class="hljs-number">2</span>);

    <span class="hljs-keyword">const</span> currentBalance = totalIncomes - totalExpenses;
    balance.textContent = currentBalance.toFixed(<span class="hljs-number">2</span>);

    <span class="hljs-comment">// Apply positive/negative class</span>
    <span class="hljs-keyword">if</span> (currentBalance &gt;= <span class="hljs-number">0</span>) {
        balance.classList.remove(<span class="hljs-string">'negative'</span>);
        balance.classList.add(<span class="hljs-string">'positive'</span>);
    } <span class="hljs-keyword">else</span> {
        balance.classList.remove(<span class="hljs-string">'positive'</span>);
        balance.classList.add(<span class="hljs-string">'negative'</span>);
    }
}
</code></pre>
<p>Now, when users are in the positive, the balance will show up in green. If they are in the negative, it will appear in red.</p>
<h3 id="heading-3-preserving-data-with-local-storage">3. Preserving Data with Local Storage</h3>
<p>One major enhancement is saving the transactions even after the page is refreshed. For this, we can use the browser’s local storage. By saving the transactions in local storage, the tracker will retain the data between sessions.</p>
<p>First, modify the <code>addTransaction</code> function to store the transactions in local storage:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addTransaction</span>(<span class="hljs-params">description, amount, category</span>) </span>{
    <span class="hljs-keyword">const</span> transaction = {
        <span class="hljs-attr">description</span>: description,
        <span class="hljs-attr">amount</span>: amount,
        <span class="hljs-attr">category</span>: category
    };

    <span class="hljs-keyword">let</span> transactions = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'transactions'</span>)) || [];
    transactions.push(transaction);
    <span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'transactions'</span>, <span class="hljs-built_in">JSON</span>.stringify(transactions));

    <span class="hljs-keyword">const</span> transactionRow = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'tr'</span>);
    transactionRow.innerHTML = <span class="hljs-string">`
        &lt;td&gt;<span class="hljs-subst">${description}</span>&lt;/td&gt;
        &lt;td&gt;<span class="hljs-subst">${category}</span>&lt;/td&gt;
        &lt;td&gt;<span class="hljs-subst">${amount.toFixed(<span class="hljs-number">2</span>)}</span>&lt;/td&gt;
        &lt;td&gt;&lt;button class="delete-btn"&gt;Delete&lt;/button&gt;&lt;/td&gt;
    `</span>;
    transactionList.appendChild(transactionRow);

    transactionRow.querySelector(<span class="hljs-string">'.delete-btn'</span>).addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        transactionRow.remove();
        removeTransaction(transaction);
        updateSummary();
    });
}
</code></pre>
<p>Next, create a <code>removeTransaction</code> function to handle deletion from local storage:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">removeTransaction</span>(<span class="hljs-params">transactionToRemove</span>) </span>{
    <span class="hljs-keyword">let</span> transactions = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'transactions'</span>)) || [];

    transactions = transactions.filter(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">transaction</span>) </span>{
        <span class="hljs-keyword">return</span> !(transaction.description === transactionToRemove.description &amp;&amp;
                 transaction.amount === transactionToRemove.amount &amp;&amp;
                 transaction.category === transactionToRemove.category);
    });

    <span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'transactions'</span>, <span class="hljs-built_in">JSON</span>.stringify(transactions));
}
</code></pre>
<p>To load saved transactions when the page is loaded, create a <code>loadTransactions</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">loadTransactions</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> transactions = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'transactions'</span>)) || [];

    transactions.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">transaction</span>) </span>{
        addTransaction(transaction.description, transaction.amount, transaction.category);
    });

    updateSummary();
}

<span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, loadTransactions);
</code></pre>
<p>Now, each time the page loads, the saved transactions are retrieved from local storage and displayed in the table.</p>
<h3 id="heading-4-how-to-improve-form-ux">4. How to Improve Form UX</h3>
<p>Let’s make the form more user-friendly by automatically focusing on the description input field when the page loads and clearing the form fields when a user submits a transaction. We can also restrict the amount field to only accept numbers.</p>
<p>To automatically focus on the description field:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    expenseInput.focus();
});
</code></pre>
<p>To restrict the amount input to numbers only, you can add the following attribute to the <code>amount-input</code> in your HTML:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"amount-input"</span> <span class="hljs-attr">min</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">step</span>=<span class="hljs-string">"0.01"</span> <span class="hljs-attr">required</span>&gt;</span>
</code></pre>
<h3 id="heading-5-using-icons-for-better-ui">5. Using Icons for Better UI</h3>
<p>Consider replacing the 'Delete' button text with an icon to improve the visual appeal. You can use an icon library like Font Awesome to add a trash icon.</p>
<p>First, include Font Awesome in your HTML file by adding this line inside the <code>&lt;head&gt;</code> section:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"</span>&gt;</span>
</code></pre>
<p>Then, in your <code>addTransaction</code> function, replace the delete button with an icon:</p>
<pre><code class="lang-javascript">transactionRow.innerHTML = <span class="hljs-string">`
    &lt;td&gt;<span class="hljs-subst">${description}</span>&lt;/td&gt;
    &lt;td&gt;<span class="hljs-subst">${category}</span>&lt;/td&gt;
    &lt;td&gt;<span class="hljs-subst">${amount.toFixed(<span class="hljs-number">2</span>)}</span>&lt;/td&gt;
    &lt;td&gt;&lt;button class="delete-btn"&gt;&lt;i class="fas fa-trash"&gt;&lt;/i&gt;&lt;/button&gt;&lt;/td&gt;
`</span>;
</code></pre>
<p>This little tweak makes your tracker look more modern and visually appealing.</p>
<h2 id="heading-testing-and-debugging">Testing and Debugging</h2>
<p>After implementing the functionality and enhancing the user experience, it’s crucial to test the expense tracker thoroughly to ensure everything works as expected. Testing helps you catch any bugs or issues before they become a problem for users.</p>
<p>In this section, we’ll go over some basic testing and debugging strategies to make sure our expense tracker is solid.</p>
<h3 id="heading-1-testing-basic-functionality">1. Testing Basic Functionality</h3>
<p>Start by testing the core features of your expense tracker:</p>
<ul>
<li><p><strong>Adding Transactions</strong>: Enter a few transactions and ensure they appear correctly in the table, with the description, category, and amount displayed properly.</p>
</li>
<li><p><strong>Deleting Transactions</strong>: Test the delete functionality by removing transactions and verifying that they are deleted both from the table and from local storage.</p>
</li>
<li><p><strong>Updating the Summary</strong>: Check that the total income, total expenses, and balance update correctly as you add and remove transactions.</p>
</li>
</ul>
<p>If any of these functionalities don’t work as expected, double-check the relevant code sections. Ensure that the JavaScript functions are correctly manipulating the DOM and updating local storage.</p>
<h3 id="heading-2-cross-browser-testing">2. Cross-Browser Testing</h3>
<p>Your expense tracker should work consistently across different web browsers. Test the application on multiple browsers like Chrome, Firefox, Safari, and Edge. Make sure the layout, functionality, and styling are consistent across all platforms.</p>
<p>If you encounter any browser-specific issues, you might need to adjust your CSS or JavaScript. For instance, some CSS properties might behave differently on different browsers, so ensure compatibility or provide fallbacks.</p>
<h3 id="heading-3-mobile-responsiveness">3. Mobile Responsiveness</h3>
<p>Test your expense tracker on various devices to ensure it’s fully responsive. Open the application on your phone or use the browser’s developer tools to simulate different screen sizes. Check how the layout adapts, and make sure the tracker is usable on smaller screens.</p>
<p>Look out for issues like:</p>
<ul>
<li><p>Text or buttons being too small or hard to tap.</p>
</li>
<li><p>The layout breaking or elements overlapping.</p>
</li>
<li><p>The form fields not fitting the screen.</p>
</li>
</ul>
<p>If you spot any problems, consider adjusting your CSS to improve the mobile experience. You might need to use media queries to tweak the layout for smaller screens.</p>
<h3 id="heading-4-testing-edge-cases">4. Testing Edge Cases</h3>
<p>Think about how users might interact with the expense tracker in unexpected ways. Consider testing the following edge cases:</p>
<ul>
<li><p><strong>Empty Inputs</strong>: Try submitting a transaction with empty fields. Does your form validation prevent this? Ensure that your <code>required</code> attributes and JavaScript validations are working.</p>
</li>
<li><p><strong>Negative Amounts</strong>: Enter negative numbers in the amount field. Does the tracker handle this correctly? You may want to restrict the input to prevent negative values.</p>
</li>
<li><p><strong>Large Numbers</strong>: Test with very large numbers in the amount field. Does the application handle large values without breaking?</p>
</li>
<li><p><strong>Duplicate Transactions</strong>: Add the same transaction multiple times. Does your tracker manage duplicates gracefully?</p>
</li>
</ul>
<p>By testing these edge cases, you can identify and address potential bugs before they affect users.</p>
<h3 id="heading-5-debugging-common-issues">5. Debugging Common Issues</h3>
<p>If you run into issues while testing, debugging is your next step. Here are some common problems you might encounter and how to troubleshoot them:</p>
<ul>
<li><p><strong>JavaScript Errors</strong>: If something isn’t working, check the browser’s console for any JavaScript errors. The console will usually provide information about what went wrong and which line of code caused the issue.</p>
</li>
<li><p><strong>Layout Problems</strong>: If the layout doesn’t look right, inspect the elements using the browser’s developer tools. Check the CSS properties being applied and see if there are any issues with margins, padding, or Flexbox/Grid settings.</p>
</li>
<li><p><strong>Data Not Persisting</strong>: If transactions aren’t being saved or loaded correctly, revisit the local storage code. Make sure you’re correctly saving and retrieving data, and that the JSON is being parsed and stringified properly.</p>
</li>
<li><p><strong>Event Listeners Not Firing</strong>: If buttons or other interactive elements aren’t working, ensure that your event listeners are properly attached. Double-check the selectors and make sure the elements exist when you’re trying to attach the listeners.</p>
</li>
</ul>
<h3 id="heading-6-user-testing">6. User Testing</h3>
<p>Finally, consider asking others to test your expense tracker. They might use the application in ways you didn’t anticipate, helping you identify usability issues or bugs that you missed. Watch how they interact with the tracker and gather feedback on any confusing elements or unexpected behaviors.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Building an expense tracker from scratch is not only a great way to sharpen your web development skills but also provides you with a practical tool to manage your finances.</p>
<p>Throughout this tutorial, we’ve walked through the entire process, from setting up the HTML structure to styling it with CSS, adding functionality with JavaScript, enhancing the user experience, and testing and debugging the final product.</p>
<p>By following these steps, you’ve created a fully functional expense tracker that allows you to easily add, view, and delete transactions, while keeping track of your income and expenses. You’ve also learned how to handle data persistence with local storage, ensuring that your data remains available even after a page refresh.</p>
<p>Remember, the principles and techniques you’ve applied here can be extended to more complex projects. Whether you’re looking to add more features to this tracker or take on a new challenge, the skills you’ve gained will be invaluable.</p>
<p>Thank you for following along with this tutorial. I hope you found it helpful and that you feel more confident in your ability to build web applications.</p>
<p>If you have any questions or suggestions, feel free to reach out on <a target="_blank" href="https://ng.linkedin.com/in/joan-ayebola">LinkedIn</a>. If you enjoyed this content, consider <a target="_blank" href="https://www.buymeacoffee.com/joanayebola">buying me a coffee</a> to support the creation of more developer-friendly contents.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create Interactive HTML Prototypes – How Far Can You Go Without JavaScript? ]]>
                </title>
                <description>
                    <![CDATA[ Interactivity is what makes a website come alive. Whether it's a button that reveals more content or a form that responds to your input, these little touches keep users engaged. Traditionally, we've relied heavily on JavaScript to make websites inter... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-create-interactive-html-prototypes/</link>
                <guid isPermaLink="false">66cdb0be7c4342e19f393004</guid>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Tue, 27 Aug 2024 10:55:58 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724485095228/2bc8f1c3-d0b8-41a2-a741-f9eaa2b6dde0.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Interactivity is what makes a website come alive. Whether it's a button that reveals more content or a form that responds to your input, these little touches keep users engaged. Traditionally, we've relied heavily on JavaScript to make websites interactive. But what if I told you that HTML alone can do more than you think?</p>
<p>In this article, we'll explore how far you can go in creating interactive prototypes using just HTML. We'll challenge the common belief that JavaScript is always necessary for interactivity by showing you how to build engaging features with nothing but HTML. By the end, you'll see that sometimes, simplicity is all you need to bring your ideas to life.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-basics-of-html-forms">Basics of HTML For</a><a class="post-section-overview" href="#heading-basics-of-html-forms">ms</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-interactive-html-elements">Interactive HTML Elements</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-advanced-interactive-prototypes-with-html">Creating Advanced Interactive Prototypes with HTML</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-html-only-interactive-techniques">HTML-Only Interactive Techniques</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-design-tips-for-html-only-prototypes">Design Tips for HTML-Only Prototypes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-basics-of-html-forms"><strong>Basics of HTML Forms</strong></h2>
<p>HTML forms are essential for collecting user input, whether it's for signing up for a service, submitting feedback<a class="post-section-overview" href="#heading-html-only-interactive-techniques">,</a> or conductin<a class="post-section-overview" href="#heading-design-tips-for-html-only-prototypes">g</a> a search. The power of forms lies <a class="post-section-overview" href="#heading-design-tips-for-html-only-prototypes"></a>in their ability to handle user data and send it to a server for processing. Understanding how to construct a basic form is the first step in leveraging HTML's interactive capabilities.</p>
<p>A basic form in HTML might look like this</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"/submit"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"name"</span>&gt;</span>Name:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">na</span>&lt;<span class="hljs-attr">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724569293880/1cb1bba7-7532-4741-9451-b4ce6aabf74f.jpeg" alt="A simple form with two input fields labeled &quot;Name:&quot; and &quot;Email:&quot;, followed by a &quot;Submit&quot; button. " class="image--center mx-auto" width="379" height="192" loading="lazy"></p>
<ul>
<li><p>The <code>&lt;form&gt;</code> element is a container for all the input elements. The <code>action</code> attribute specifies where the form data should be sent when the form is submitted. The <code>method</code> attribute determines how the data is sent (typically using <code>GET</code> or <code>POST</code>).</p>
</li>
<li><p>The <code>&lt;label&gt;</code> element provides a user-friendly label for each input field, improving accessibility.</p>
</li>
<li><p>The <code>&lt;input&gt;</code> elements are where users enter their information. Each input has a <code>type</code> attribute that defines what kind of data it accepts (for example: <code>text</code>, <code>email</code>, <code>password</code>).</p>
</li>
<li><p>The <code>&lt;button&gt;</code> element submits the form when clicked.</p>
</li>
</ul>
<p>Forms are fundamental because they involve direct user interaction, making them a critical component of any interactive prototype.</p>
<h2 id="heading-interactive-html-elements"><strong>Interactive HTML Elements</strong></h2>
<p>Beyond forms, HTML includes a variety of elements that naturally respond to user actions. These elements can be used to create interactive interfaces without writing any JavaScript, which is perfect for quick prototyping.</p>
<h3 id="heading-buttons-checkboxes-and-radio-buttons"><strong>Buttons, Checkboxes, and Radio Buttons</strong></h3>
<p><strong>Buttons:</strong> Buttons are one of the most straightforward interactive elements. They can perform a wide range of actions, from submitting a form to triggering a CSS animation. Buttons are usually defined with the <code>&lt;button&gt;</code> or <code>&lt;input type="button"&gt;</code> elements.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"button"</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1724573151277/d726e8ce-3e0e-49c3-a3b0-c20944c6e807.jpeg" alt="A button with the text &quot;Click Me&quot; displayed in the center." class="image--center mx-auto" width="135" height="67" loading="lazy"></p>
<p>In the above example, the button doesn't do anything by itself unless tied to a form or an action. However, in prototypes, buttons can visually represent functionality, making the prototype feel more complete.</p>
<p><strong>Checkboxes:</strong> Checkboxes allow users to select multiple options from a list. They are ideal for scenarios where more than one choice is allowed.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"option1"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"option1"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Option 1"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"option1"</span>&gt;</span>Option 1<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/qBzYwLY" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p>Each checkbox can be checked or unchecked, providing immediate visual feedback.</p>
<p><strong>Radio Buttons:</strong> Radio buttons are used when only one option can be selected from a group. This is useful in cases like surveys or quizzes where the user needs to choose one answer.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"choice1"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"choice"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Choice 1"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"choice1"</span>&gt;</span>Choice 1<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"choice2"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"choice"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Choice 2"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"choice2"</span>&gt;</span>Choice 2<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/BagxEMB" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p>When one radio button in a group is selected, the others are automatically deselected, ensuring that only one option is chosen.</p>
<p>These elements are simple yet powerful, providing the basic building blocks for interactive user interfaces.</p>
<h3 id="heading-the-and-elements"><strong>The</strong> <code>&lt;details&gt;</code> and <code>&lt;summary&gt;</code> Elements</h3>
<p>The <code>&lt;details&gt;</code> and <code>&lt;summary&gt;</code> elements provide a way to create sections of content that users can expand or collapse. This is particularly useful for FAQs, where you might want to show the question and hide the answer until the user chooses to reveal it.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">details</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">summary</span>&gt;</span>What is HTML?<span class="hljs-tag">&lt;/<span class="hljs-name">summary</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>HTML stands for HyperText Markup Language. It is the standard language used to create web pages.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">details</span>&gt;</span>
</code></pre>
<details>
  <summary>What is HTML?</summary>
  <p>HTML stands for HyperText Markup Language. It is the standard language used to create web pages.</p>
</details>

<p><strong>How it works:</strong></p>
<ul>
<li><p>The <code>&lt;summary&gt;</code> element is the clickable heading that the user interacts with.</p>
</li>
<li><p>The content inside the <code>&lt;details&gt;</code> tag (but outside the <code>&lt;summary&gt;</code> tag) remains hidden until the user clicks on the summary, revealing it.</p>
</li>
</ul>
<p>This simple interaction adds a layer of user control, allowing content to be hidden or shown based on user action, all without JavaScript.</p>
<h3 id="heading-different-types-of"><strong>Different Types of</strong> <code>&lt;input&gt;</code></h3>
<p>The <code>&lt;input&gt;</code> element is one of the most versatile in HTML. Depending on its <code>type</code> attribute, it can serve different purposes, from accepting text input to allowing date selection. Understanding the various input types is key to creating functional prototypes.</p>
<p>Here are a few common types:</p>
<p><strong>Text Input:</strong> This is the most common input type, used for single-line text input.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter your username"</span>&gt;</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/eYwroxW" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p>The <code>placeholder</code> attribute provides a hint to the user about what to enter.</p>
<p><strong>Password Input:</strong> This input type hides the characters as the user types, making it suitable for sensitive information like passwords.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter your password"</span>&gt;</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/dyBeLaq" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p><strong>Email Input:</strong> The <code>email</code> type ensures that the user’s input is in a valid email format.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter your email"</span>&gt;</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/OJeZGdK" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p><strong>Date Input:</strong> This type provides a date picker, allowing users to select a date from a calendar interface.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"date"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"birthdate"</span>&gt;</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/yLdjrwV" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p>These different input types enhance user experience by providing specialized interfaces for different types of data. They help make the form more intuitive and reduce the likelihood of user errors.</p>
<h2 id="heading-how-to-create-advanced-interactive-prototypes-with-html"><strong>How to Create Advanced Interactive Prototypes with HTML</strong></h2>
<p>Once you're comfortable with the basics of HTML forms and interactive elements, you can start creating more advanced prototypes that offer a richer user experience. In this section, we'll explore how to combine form elements to build complex interactions and simulate dynamic content updates, using only HTML.</p>
<h3 id="heading-how-to-combine-form-elements-for-complex-interactions"><strong>How to Combine Form Elements for Complex Interactions</strong></h3>
<p>Combining different form elements can help you create more sophisticated interactions and user experiences. While HTML alone has its limitations, you can still achieve quite a bit by using these elements creatively.</p>
<h4 id="heading-multi-step-forms-and-conditional-inputs"><strong>Multi-step Forms and Conditional Inputs</strong></h4>
<p>Multi-step forms are useful when you want to break a long form into smaller, more manageable sections. This approach can improve user experience by making complex forms feel less overwhelming. While HTML alone doesn’t support multi-step functionality directly, you can use the <code>&lt;fieldset&gt;</code> and <code>&lt;legend&gt;</code> elements to organize form sections visually.</p>
<p><strong>Example of a Multi-step Form:</strong></p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">fieldset</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">legend</span>&gt;</span>Step 1: Personal Information<span class="hljs-tag">&lt;/<span class="hljs-name">legend</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"name"</span>&gt;</span>Name:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"email"</span>&gt;</span>Email:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</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">"document.getElementById('step2').style.display='block';"</span>&gt;</span>Next<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">fieldset</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">fieldset</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"step2"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"display:none;"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">legend</span>&gt;</span>Step 2: Address Details<span class="hljs-tag">&lt;/<span class="hljs-name">legend</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"address"</span>&gt;</span>Address:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"address"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"address"</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"city"</span>&gt;</span>City:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"city"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"city"</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">"document.getElementById('step2').style.display='none';"</span>&gt;</span>Previous<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">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">fieldset</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/JjQvVzv" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p><strong>How it works:</strong></p>
<ul>
<li><p><strong>Fieldsets</strong>: The <code>&lt;fieldset&gt;</code> element groups related fields together and helps visually separate different sections of the form.</p>
</li>
<li><p><strong>Legends</strong>: The <code>&lt;legend&gt;</code> element provides a title for each section.</p>
</li>
<li><p><strong>Buttons</strong>: Use <code>&lt;button&gt;</code> elements with <code>onclick</code> attributes to show or hide sections. In a real-world scenario, you’d use JavaScript for better control, but this example demonstrates the concept.</p>
</li>
</ul>
<p><strong>Conditional Inputs</strong> allow users to fill out additional fields based on previous choices. While HTML alone doesn’t support this functionality natively, you can use checkboxes and radio buttons creatively to show or hide sections of the form.</p>
<p><strong>Example of Conditional Inputs:</strong></p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"subscribe"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"subscribe"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"subscribe"</span>&gt;</span>
    Subscribe to newsletter
  <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"newsletterDetails"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"display:none;"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"frequency"</span>&gt;</span>Preferred Frequency:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"frequency"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"frequency"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"weekly"</span>&gt;</span>Weekly<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"monthly"</span>&gt;</span>Monthly<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">select</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>&gt;</span><span class="javascript">
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'subscribe'</span>).addEventListener(<span class="hljs-string">'change'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'newsletterDetails'</span>).style.display = <span class="hljs-built_in">this</span>.checked ? <span class="hljs-string">'block'</span> : <span class="hljs-string">'none'</span>;
    });
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/VwJxNRV" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p><strong>How it works:</strong></p>
<ul>
<li><p><strong>Checkboxes</strong>: The checkbox lets users opt into additional options.</p>
</li>
<li><p><strong>Conditional Display</strong>: The <code>&lt;div&gt;</code> with <code>id="newsletterDetails"</code> shows or hides based on the checkbox state. While the JavaScript is necessary to handle the condition, HTML alone provides the structure and initial display.</p>
</li>
</ul>
<h4 id="heading-simulating-dynamic-content-updates"><strong>Simulating Dynamic Content Updates</strong></h4>
<p>Simulating dynamic content updates involves creating sections of a webpage that can change based on user input. While full dynamic updates require JavaScript, you can use HTML and CSS to simulate these changes.</p>
<p><strong>Example of Simulated Dynamic Content Updates:</strong></p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"view"</span>&gt;</span>Choose a view:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"view"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"view"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"overview"</span>&gt;</span>Overview<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"details"</span>&gt;</span>Details<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"overviewContent"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Overview<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>This is the overview content.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"detailsContent"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"display:none;"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Details<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>This is the detailed content.<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">script</span>&gt;</span><span class="javascript">
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'view'</span>).addEventListener(<span class="hljs-string">'change'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">var</span> selectedView = <span class="hljs-built_in">this</span>.value;
      <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'overviewContent'</span>).style.display = selectedView === <span class="hljs-string">'overview'</span> ? <span class="hljs-string">'block'</span> : <span class="hljs-string">'none'</span>;
      <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'detailsContent'</span>).style.display = selectedView === <span class="hljs-string">'details'</span> ? <span class="hljs-string">'block'</span> : <span class="hljs-string">'none'</span>;
    });
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/rNEvbbz" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p><strong>How it works:</strong></p>
<ul>
<li><p><strong>Dropdown Menu</strong>: A <code>&lt;select&gt;</code> element allows users to choose between different views.</p>
</li>
<li><p><strong>Content Sections</strong>: The content sections are shown or hidden based on the user’s selection. This simulation relies on JavaScript to handle the visibility, but the structure is set up with HTML.</p>
</li>
</ul>
<p>While true dynamic updates are best handled with JavaScript, these examples show how you can create the illusion of interactivity using HTML and CSS alone.</p>
<h2 id="heading-html-only-interactive-techniques"><strong>HTML-Only Interactive Techniques</strong></h2>
<p>While JavaScript is commonly used for creating interactive features, HTML itself offers several techniques to achieve interactivity. In this section, we'll explore four HTML-only techniques: using the <code>target</code> attribute for page-level interactions, emulating modal dialogs, creating tooltips, and building interactive image maps. Each technique highlights how HTML can be used creatively to add interactive elements to your webpages.</p>
<h3 id="heading-how-to-use-the-target-attribute-for-page-level-interactions"><strong>How to Use the</strong> <code>target</code> Attribute for Page-level Interactions</h3>
<p>The <code>target</code> attribute allows you to control where a linked document will open. This can be used to create interactive experiences that involve navigating between different sections of a page or opening new pages within the same window or tab.</p>
<p><strong>Example of Using the</strong> <code>target</code> Attribute:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#section1"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_self"</span>&gt;</span>Go to Section 1<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#section2"</span> <span class="hljs-attr">target</span>=<span class="hljs-string">"_self"</span>&gt;</span>Go to Section 2<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"section1"</span>&gt;</span>Section 1<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>Content for Section 1...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"section2"</span>&gt;</span>Section 2<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>Content for Section 2...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/NWZMmVG" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p><strong>How it works:</strong></p>
<ul>
<li><p><strong>Anchors (</strong><code>&lt;a&gt;</code> elements): These links navigate to different parts of the same page or other pages. The <code>href</code> attribute points to the target location.</p>
</li>
<li><p><code>target="_self"</code>: This attribute ensures the link opens in the same window or tab, which is the default behavior. You can use other values like <code>_blank</code> to open links in a new tab or window.</p>
</li>
</ul>
<p>Using the target attribute allows you to control how users interact with links and navigate your site, enhancing the user experience without relying on JavaScript.</p>
<h3 id="heading-how-to-emulate-modal-dialogs"><strong>How to Emulate Modal Dialogs</strong></h3>
<p>Modal dialogs are often used to display important information or prompts that require user interaction before proceeding. While creating true modals typically involves JavaScript, you can use HTML and CSS to simulate modal dialogs.</p>
<p><strong>Example of Emulating a Modal Dialog:</strong></p>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- Hidden checkbox to toggle the modal --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"modal-toggle"</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- Button to open the modal --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"modal-toggle"</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"cursor: pointer;"</span>&gt;</span>Open Modal<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>

    <span class="hljs-comment">&lt;!-- The Modal --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"modal"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"modal-content"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"close"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"document.getElementById('modal-toggle').click();"</span>&gt;</span><span class="hljs-symbol">&amp;times;</span><span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Modal Title<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>This is a simple modal dialog without JavaScript!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
<span class="hljs-comment">/* Hide the checkbox */</span>
<span class="hljs-selector-id">#modal-toggle</span> {
    <span class="hljs-attribute">display</span>: none;
}

<span class="hljs-comment">/* The modal background */</span>
<span class="hljs-selector-class">.modal</span> {
    <span class="hljs-attribute">display</span>: none;
    <span class="hljs-attribute">position</span>: fixed;
    <span class="hljs-attribute">top</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">left</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">100%</span>;
    <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">0</span>, <span class="hljs-number">0.5</span>);
    <span class="hljs-attribute">justify-content</span>: center;
    <span class="hljs-attribute">align-items</span>: center;
}

<span class="hljs-comment">/* Show the modal when the checkbox is checked */</span>
<span class="hljs-selector-id">#modal-toggle</span><span class="hljs-selector-pseudo">:checked</span> ~ <span class="hljs-selector-class">.modal</span> {
    <span class="hljs-attribute">display</span>: flex;
}

<span class="hljs-comment">/* The modal content */</span>
<span class="hljs-selector-class">.modal-content</span> {
    <span class="hljs-attribute">background-color</span>: white;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
    <span class="hljs-attribute">max-width</span>: <span class="hljs-number">500px</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
    <span class="hljs-attribute">text-align</span>: center;
    <span class="hljs-attribute">position</span>: relative;
}

<span class="hljs-comment">/* The close button */</span>
<span class="hljs-selector-class">.close</span> {
    <span class="hljs-attribute">position</span>: absolute;
    <span class="hljs-attribute">top</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">right</span>: <span class="hljs-number">10px</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">24px</span>;
    <span class="hljs-attribute">text-decoration</span>: none;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#333</span>;
    <span class="hljs-attribute">cursor</span>: pointer;
}

<span class="hljs-selector-class">.close</span><span class="hljs-selector-pseudo">:hover</span> {
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#ff4c4c</span>;
}

</span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/poXVBmN" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p><strong>How it works:</strong></p>
<ul>
<li><p><strong>Checkbox (</strong><code>&lt;input type="checkbox"&gt;</code>): Used to control the visibility of the modal.</p>
</li>
<li><p><strong>Labels</strong>: The labels act as buttons to open and close the modal. Clicking the "Open Modal" label checks the checkbox, which makes the modal visible. Clicking the "Close" label unchecks the checkbox and hides the modal.</p>
</li>
<li><p><strong>CSS</strong>: Controls the appearance and positioning of the modal and its overlay.</p>
</li>
</ul>
<p>This approach allows you to create a modal-like effect with HTML and CSS alone, providing a user-friendly way to present information or options.</p>
<h3 id="heading-how-to-create-html-only-tooltips"><strong>How to Create HTML-only Tooltips</strong></h3>
<p>Tooltips provide additional information when a user hovers over an element. While JavaScript can enhance tooltips, you can create basic tooltips using just HTML and CSS.</p>
<p><strong>Example of Creating Tooltips:</strong></p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"tooltip"</span>&gt;</span>
  Hover over me
  <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"tooltip-text"</span>&gt;</span>Tooltip text<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
  <span class="hljs-selector-class">.tooltip</span> {
    <span class="hljs-attribute">position</span>: relative;
    <span class="hljs-attribute">display</span>: inline-block;
    <span class="hljs-attribute">cursor</span>: pointer;
  }
  <span class="hljs-selector-class">.tooltip</span> <span class="hljs-selector-class">.tooltip-text</span> {
    <span class="hljs-attribute">visibility</span>: hidden;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">120px</span>;
    <span class="hljs-attribute">background-color</span>: black;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">text-align</span>: center;
    <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">5px</span> <span class="hljs-number">0</span>;
    <span class="hljs-attribute">position</span>: absolute;
    <span class="hljs-attribute">z-index</span>: <span class="hljs-number">1</span>;
    <span class="hljs-attribute">bottom</span>: <span class="hljs-number">125%</span>; <span class="hljs-comment">/* Position above the tooltip trigger */</span>
    <span class="hljs-attribute">left</span>: <span class="hljs-number">50%</span>;
    <span class="hljs-attribute">margin-left</span>: -<span class="hljs-number">60px</span>;
    <span class="hljs-attribute">opacity</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">transition</span>: opacity <span class="hljs-number">0.3s</span>;
  }
  <span class="hljs-selector-class">.tooltip</span><span class="hljs-selector-pseudo">:hover</span> <span class="hljs-selector-class">.tooltip-text</span> {
    <span class="hljs-attribute">visibility</span>: visible;
    <span class="hljs-attribute">opacity</span>: <span class="hljs-number">1</span>;
  }
</span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/MWMXyoO" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p><strong>How it works:</strong></p>
<ul>
<li><p><strong>Tooltip Container</strong>: The <code>&lt;div class="tooltip"&gt;</code> contains the text that triggers the tooltip and the tooltip text itself.</p>
</li>
<li><p><strong>Tooltip Text</strong>: The <code>&lt;span class="tooltip-text"&gt;</code> is hidden by default and only becomes visible when the user hovers over the tooltip container.</p>
</li>
<li><p><strong>CSS</strong>: Uses <code>visibility</code> and <code>opacity</code> to show and hide the tooltip, with a transition effect for smooth appearance.</p>
</li>
</ul>
<p>This method allows you to add helpful hints or extra information to your webpage without needing JavaScript.</p>
<h3 id="heading-how-to-build-interactive-image-maps"><strong>How to Build Interactive Image Maps</strong></h3>
<p>Image maps enable you to create clickable areas on an image, allowing users to interact with different parts of an image. HTML’s <code>&lt;map&gt;</code> and <code>&lt;area&gt;</code> elements are used to define these clickable regions.</p>
<p><strong>Example of Building an Image Map:</strong></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">"map-image.jpg"</span> <span class="hljs-attr">usemap</span>=<span class="hljs-string">"#image-map"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Map Image"</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">map</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"image-map"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">area</span> <span class="hljs-attr">shape</span>=<span class="hljs-string">"rect"</span> <span class="hljs-attr">coords</span>=<span class="hljs-string">"34,44,270,350"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"page1.html"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Region 1"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">area</span> <span class="hljs-attr">shape</span>=<span class="hljs-string">"circle"</span> <span class="hljs-attr">coords</span>=<span class="hljs-string">"130,136,60"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"page2.html"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Region 2"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">area</span> <span class="hljs-attr">shape</span>=<span class="hljs-string">"poly"</span> <span class="hljs-attr">coords</span>=<span class="hljs-string">"300,50,400,150,350,200"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"page3.html"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Region 3"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">map</span>&gt;</span>
</code></pre>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/joanayebola/embed/KKjezQv" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<p> </p>
<p><strong>How it works:</strong></p>
<ul>
<li><p><strong>Image</strong>: The <code>&lt;img&gt;</code> tag includes the <code>usemap</code> attribute, which links to the <code>&lt;map&gt;</code> element.</p>
</li>
<li><p><strong>Map and Areas</strong>: The <code>&lt;map&gt;</code> element contains one or more <code>&lt;area&gt;</code> elements. Each <code>&lt;area&gt;</code> defines a clickable region on the image.</p>
<ul>
<li><p><code>shape="rect"</code>: Defines a rectangular area with specified coordinates.</p>
</li>
<li><p><code>shape="circle"</code>: Defines a circular area with a center and radius.</p>
</li>
</ul>
</li>
</ul>
<p>Image maps allow you to create interactive images with different regions that lead to various pages or actions, adding an extra layer of engagement to your prototypes.</p>
<h2 id="heading-design-tips-for-html-only-prototypes"><strong>Design Tips for HTML-Only Prototypes</strong></h2>
<p>Designing HTML-only prototypes involves focusing on both usability and performance. While HTML alone provides a solid foundation for interactive elements, it’s essential to ensure that your prototypes are accessible, fast, and efficient. This section offers tips on making your HTML-only prototypes more effective, covering accessibility, performance, and limitations.</p>
<h3 id="heading-make-sure-your-prototype-is-accessible"><strong>Make Sure Your Prototype is Accessible</strong></h3>
<p>Accessibility ensures that your prototypes can be used by everyone, including those with disabilities. By adhering to accessibility principles, you improve the user experience for all users and make your prototypes more inclusive.</p>
<h4 id="heading-keyboard-friendly-navigation"><strong>Keyboard-friendly Navigation</strong></h4>
<p>Many users rely on keyboards for navigation, so it’s crucial to ensure that all interactive elements can be accessed and used via keyboard alone.</p>
<p><strong>Tips for Keyboard-Friendly Navigation:</strong></p>
<ul>
<li><p><strong>Use Semantic HTML</strong>: Proper use of HTML elements like <code>&lt;button&gt;</code>, <code>&lt;a&gt;</code>, and <code>&lt;input&gt;</code> helps with keyboard navigation. These elements are naturally focusable and keyboard-navigable.</p>
</li>
<li><p><strong>Tab Index</strong>: The <code>tabindex</code> attribute can be used to manage the order of focusable elements. For example, <code>tabindex="0"</code> allows an element to be focusable, while negative values like <code>tabindex="-1"</code> remove an element from the tab order.</p>
</li>
<li><p><strong>Visible Focus Indicators</strong>: Ensure that focus indicators (like outlines) are visible when navigating with the keyboard. This helps users see which element is currently in focus.</p>
</li>
</ul>
<p><strong>Example:</strong></p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">tabindex</span>=<span class="hljs-string">"0"</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#section1"</span> <span class="hljs-attr">tabindex</span>=<span class="hljs-string">"0"</span>&gt;</span>Go to Section 1<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">tabindex</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter text here"</span>&gt;</span>
</code></pre>
<h4 id="heading-screen-reader-support"><strong>Screen Reader Support</strong></h4>
<p>Screen readers help visually impaired users navigate your site. To ensure that your prototypes are accessible to these users, include relevant ARIA (Accessible Rich Internet Applications) attributes and use semantic HTML.</p>
<p><strong>Tips for Screen Reader Support:</strong></p>
<ul>
<li><p><strong>Alt Text</strong>: Use the <code>alt</code> attribute for images to provide descriptive text for screen readers.</p>
</li>
<li><p><strong>ARIA Roles and Labels</strong>: Use ARIA roles and labels to enhance the accessibility of interactive elements. For example, <code>role="button"</code> can be used for clickable elements that are not inherently buttons.</p>
</li>
<li><p><strong>Descriptive Labels</strong>: Ensure that form inputs and interactive elements have clear and descriptive labels.</p>
</li>
</ul>
<p><strong>Example:</strong></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">"logo.jpg"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Company Logo"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">aria-label</span>=<span class="hljs-string">"Close"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"closeModal()"</span>&gt;</span>X<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>Incorporating these practices makes your prototypes more navigable and usable for individuals with disabilities.</p>
<h3 id="heading-the-speed-and-simplicity-of-html-only-prototypes"><strong>The Speed and Simplicity of HTML-only Prototypes</strong></h3>
<p>HTML-only prototypes are often faster to load and simpler to maintain due to their reliance on minimal resources. These benefits contribute to a more efficient user experience.</p>
<h4 id="heading-faster-loading"><strong>Faster Loading</strong></h4>
<p>HTML-only prototypes typically load faster because they don’t rely on external scripts or complex interactions that can slow down performance. The simplicity of HTML means fewer resources need to be processed by the browser.</p>
<p><strong>Benefits:</strong></p>
<ul>
<li><p><strong>Reduced Load Times</strong>: Without JavaScript or complex CSS, the browser can render the content more quickly.</p>
</li>
<li><p><strong>Improved Performance</strong>: Fewer resources mean less strain on the client’s device, resulting in smoother performance.</p>
</li>
</ul>
<h4 id="heading-lower-resource-use"><strong>Lower Resource Use</strong></h4>
<p>Using HTML alone minimizes resource consumption. Without JavaScript or heavy CSS, your prototype consumes less memory and processing power.</p>
<p><strong>Benefits:</strong></p>
<ul>
<li><p><strong>Lower Memory Usage</strong>: Less reliance on external scripts means reduced memory footprint.</p>
</li>
<li><p><strong>Less CPU Usage</strong>: Simplified interactions reduce the need for extensive computation, leading to lower CPU usage.</p>
</li>
</ul>
<p>These aspects contribute to a more efficient and responsive user experience, especially important for users on slower connections or less powerful devices.</p>
<h3 id="heading-where-html-falls-short"><strong>Where HTML Falls Short</strong></h3>
<p>HTML is great for building interactive prototypes, but it has some limits. Knowing these limits helps you decide when to add other technologies.</p>
<h4 id="heading-no-complex-logic"><strong>No Complex Logic</strong></h4>
<p>HTML alone is limited in handling complex logic and dynamic interactions. For example, conditions, loops, or advanced calculations require JavaScript.</p>
<p><strong>Limitations:</strong></p>
<ul>
<li><p><strong>Conditional Logic</strong>: HTML cannot perform actions based on complex conditions or states.</p>
</li>
<li><p><strong>Dynamic Updates</strong>: Changes to the page content or structure based on user input often require JavaScript.</p>
</li>
</ul>
<p><strong>Example Limitation:</strong></p>
<ul>
<li><strong>Interactive Forms</strong>: Complex forms with dynamic fields or conditional sections generally need JavaScript to manage the logic and interactions effectively.</li>
</ul>
<h4 id="heading-difficulties-with-more-advanced-interactions"><strong>Difficulties with More Advanced Interactions</strong></h4>
<p>Some interactions, such as real-time updates or complex animations, are challenging to achieve with HTML alone. While CSS can handle some animations, more advanced interactions often require scripting.</p>
<p><strong>Limitations:</strong></p>
<ul>
<li><p><strong>Real-time Data</strong>: Updating content in real time based on user actions or external data sources is typically not possible with HTML alone.</p>
</li>
<li><p><strong>Complex Animations</strong>: Advanced animations and transitions usually require JavaScript or CSS animations.</p>
</li>
</ul>
<p><strong>Example Limitation:</strong></p>
<ul>
<li><strong>Live Content Updates</strong>: HTML cannot fetch or update content dynamically without JavaScript or server-side solutions.</li>
</ul>
<p>Recognizing these limitations helps you balance the use of HTML with other technologies when needed to achieve your desired functionality.</p>
<h2 id="heading-when-to-use-html-only-prototypes"><strong>When to Use HTML-Only Prototypes</strong></h2>
<p>HTML-only prototypes can be a powerful tool in your design toolkit, especially when simplicity and performance are key.</p>
<p>Understanding when to use HTML-only solutions, considering your audience, and knowing how to blend HTML with JavaScript can help you create effective prototypes that meet your project needs.</p>
<h3 id="heading-when-html-only-is-the-right-choice"><strong>When HTML-only is the Right Choice</strong></h3>
<p>HTML-only prototypes are particularly useful in specific scenarios where their simplicity and efficiency shine. Here are some situations where using HTML-only prototypes makes sense:</p>
<p><strong>1. Simple Forms and Surveys:</strong> When you need to create basic forms or surveys to collect user input, HTML forms with standard input elements can be used effectively. These prototypes are easy to set up and provide a straightforward way for users to submit information.</p>
<p><strong>Example:</strong></p>
<ul>
<li><p>A contact form on a website.</p>
</li>
<li><p>A quick survey to gather feedback from users.</p>
</li>
</ul>
<p><strong>2. Static Information Display:</strong> For displaying static content or information, HTML is sufficient. Prototypes that focus on showcasing content without requiring dynamic interactions are ideal candidates for HTML-only design.</p>
<p><strong>Example:</strong></p>
<ul>
<li><p>An informational landing page.</p>
</li>
<li><p>A product details page that provides static information.</p>
</li>
</ul>
<p><strong>3. Prototyping Early Concepts:</strong> When prototyping early concepts or initial designs, HTML-only prototypes can help quickly visualize and test ideas without the need for complex scripting. This approach allows you to iterate rapidly and focus on layout and structure.</p>
<p><strong>Example:</strong></p>
<ul>
<li><p>Wireframes or mockups of a new feature.</p>
</li>
<li><p>Early-stage designs for a website or application.</p>
</li>
</ul>
<p><strong>4. Performance Considerations:</strong> For situations where performance is critical and you need to ensure fast loading times and low resource usage, HTML-only prototypes can be advantageous. They eliminate the overhead of additional scripts and reduce processing demands.</p>
<p><strong>Example:</strong></p>
<ul>
<li><p>A mobile landing page with minimal resources.</p>
</li>
<li><p>A lightweight information page with fast load times.</p>
</li>
</ul>
<p><strong>5. Accessibility and Simplicity:</strong> When designing for accessibility and simplicity, HTML provides a strong foundation. Using semantic HTML and built-in attributes ensures that your prototypes are accessible to users with disabilities.</p>
<p><strong>Example:</strong></p>
<ul>
<li><p>An accessible form with clear labels and input fields.</p>
</li>
<li><p>A simple navigation menu with clear, focusable links.</p>
</li>
</ul>
<h3 id="heading-understanding-your-audience"><strong>Understanding Your Audience</strong></h3>
<p>Knowing your audience is crucial when deciding whether to use HTML-only prototypes. Consider the following factors:</p>
<p><strong>1. User Needs and Expectations:</strong> Understand what your users need and expect from the prototype. If your audience is looking for simple, straightforward interactions, HTML-only may be sufficient. For more complex interactions or dynamic content, consider integrating JavaScript.</p>
<p><strong>Example:</strong></p>
<ul>
<li><p>Users who need a basic contact form may be satisfied with an HTML-only solution.</p>
</li>
<li><p>Users who expect interactive features or real-time updates might require a combination of HTML and JavaScript.</p>
</li>
</ul>
<p><strong>2. Technical Constraints:</strong> Consider the technical constraints of your audience’s devices and browsers. HTML-only prototypes generally perform well across various devices and browsers, making them suitable for diverse audiences.</p>
<p><strong>Example:</strong></p>
<ul>
<li>A prototype for users with older devices or limited internet connectivity may benefit from the simplicity of HTML-only design.</li>
</ul>
<p><strong>3. User Expertise:</strong> Assess the technical expertise of your audience. If they are not familiar with complex interactions or scripting, HTML-only prototypes can provide a more accessible and user-friendly experience.</p>
<p><strong>Example:</strong></p>
<ul>
<li>A prototype for a non-technical audience may prioritize simplicity and ease of use with HTML-only design.</li>
</ul>
<p><strong>4. Feedback and Iteration:</strong> Gather feedback from users to understand how they interact with your prototype. If users find HTML-only prototypes sufficient for their needs, you can continue with this approach. If more advanced features are requested, consider integrating additional technologies.</p>
<p><strong>Example:</strong></p>
<ul>
<li>Collect user feedback on a basic form and decide if additional features or interactions are needed.</li>
</ul>
<h3 id="heading-mixing-html-and-javascript"><strong>Mixing HTML and JavaScript</strong></h3>
<p>While HTML-only prototypes have their strengths, combining HTML with JavaScript can enhance functionality and provide a richer user experience.</p>
<p>Here’s when and how to mix HTML and JavaScript effectively:</p>
<p><strong>1. Adding Dynamic Interactions:</strong> When your prototype requires dynamic interactions, such as real-time updates or complex logic, JavaScript can complement HTML to provide these features.</p>
<p><strong>Example:</strong></p>
<ul>
<li><p>A form that updates in real time based on user input.</p>
</li>
<li><p>An interactive map with zoom and filter capabilities.</p>
</li>
</ul>
<p><strong>2. Enhancing User Experience:</strong> JavaScript can be used to improve the user experience by adding interactive elements like modals, carousels, or animations that HTML alone cannot achieve.</p>
<p><strong>Example:</strong></p>
<ul>
<li><p>A modal dialog that opens and closes based on user actions.</p>
</li>
<li><p>A carousel that allows users to navigate through images or content.</p>
</li>
</ul>
<p><strong>3. Handling Complex Logic:</strong> For prototypes involving complex calculations, conditional logic, or data manipulation, JavaScript can handle these requirements more effectively than HTML alone.</p>
<p><strong>Example:</strong></p>
<ul>
<li><p>A calculator that performs complex calculations based on user input.</p>
</li>
<li><p>A dynamic form that adjusts fields based on previous selections.</p>
</li>
</ul>
<p><strong>4. Iterating and Testing:</strong> Start with an HTML-only prototype to establish the basic structure and layout. Once you have a clear understanding of the design, integrate JavaScript to add interactivity and test the enhanced functionality.</p>
<p><strong>Example:</strong></p>
<ul>
<li>Begin with a static prototype of a feature and then add JavaScript to refine and test interactive elements.</li>
</ul>
<p><strong>5. Balancing Complexity:</strong> Use JavaScript to enhance the prototype where necessary, but avoid overcomplicating the design. Maintain a balance between simplicity and functionality to ensure the prototype remains easy to use and understand.</p>
<p><strong>Example:</strong></p>
<ul>
<li>Implement JavaScript for essential interactions but keep the overall design and layout straightforward.</li>
</ul>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>HTML-only prototypes are a great choice for many design tasks because they are simple and quick to build. They work well for basic interactions like forms and displaying information.</p>
<p>HTML alone is powerful for straightforward designs. However, if you need more advanced features or dynamic interactions, adding JavaScript can help. Mixing HTML with JavaScript lets you enhance your prototypes when needed.</p>
<p>In summary, HTML-only prototypes offer speed, accessibility, and ease of use. Understanding when to use HTML by itself and when to add other tools ensures that your prototypes are both effective and user-friendly.</p>
<p>That's all for this article! If you'd like to continue the conversation or have questions, suggestions, or feedback, feel free to reach out to connect with me on <a target="_blank" href="https://ng.linkedin.com/in/joan-ayebola">LinkedIn</a>. If you enjoyed this content, consider <a target="_blank" href="https://www.buymeacoffee.com/joanayebola">buying me a coffee</a> to support the creation of more developer-friendly contents.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Server-Side Rendering in Next.js Apps for Better SEO ]]>
                </title>
                <description>
                    <![CDATA[ Server-side rendering (SSR) is a web development technique that can help improve your site's SEO. It does this by generating HTML content on the server in response to a user's request.  This approach contrasts with client-side rendering (CSR), where ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/server-side-rendering-in-next-js-for-improved-seo/</link>
                <guid isPermaLink="false">66c4c415bd556981b1bdc441</guid>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SEO ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Server side rendering ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Wed, 17 Jul 2024 18:02:11 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/How-to-Use-Server-Side-Rendering-in-Next.js-Apps-for-Better-SEO-Cover-Image.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Server-side rendering (SSR) is a web development technique that can help improve your site's SEO. It does this by generating HTML content on the server in response to a user's request. </p>
<p>This approach contrasts with client-side rendering (CSR), where content is delivered as a basic HTML shell, and JavaScript fetches and displays data in the browser.</p>
<p>SSR offers significant SEO advantages, making it a perfect fit for Next.js, a popular React framework. Let's discuss how using SSR with Next.js can elevate your website's search engine visibility.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-server-side-rendering">What is Server-Side Rendering</a>?</li>
<li><a class="post-section-overview" href="#heading-how-to-get-started-with-nextjs-and-ssr">How to Get Started with Next.js and SSR</a></li>
<li><a class="post-section-overview" href="#heading-how-nextjs-enables-server-side-rendering">How Next.js Enables Server-side Rendering</a></li>
<li><a class="post-section-overview" href="#heading-data-fetching-with-getstaticprops-and-getserversideprops">Data Fetching with getStaticProps and getServerSideProps</a></li>
<li><a class="post-section-overview" href="#heading-benefits-of-ssr-for-seo-with-nextjs-and-how-to-optimize">Benefits of SSR for SEO with Next.js and How to Optimize</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-is-server-side-rendering">What is Server-Side Rendering?</h2>
<p>Server-side rendering (SSR) is a technique in web development where the web server generates the complete HTML content of a web page before sending it to the user's browser. </p>
<p>This is unlike client-side rendering (CSR), where the browser downloads a basic HTML structure and then uses JavaScript to fetch and display the content.</p>
<h2 id="heading-how-to-get-started-with-nextjs-and-ssr">How to Get Started with Next.js and SSR</h2>
<p>Getting started with Next.js and server-side rendering (SSR) involves a few steps. Here's a step-by-step guide to help you set up a Next.js project and implement SSR.</p>
<h3 id="heading-step-1-install-nextjs">Step 1: Install Next.js</h3>
<p>First, you need to install Next.js. You can do this using <code>create-next-app</code>, which sets up a new Next.js project with a default configuration. Run the following command in your terminal:</p>
<pre><code class="lang-bash">npx create-next-app my-next-app
<span class="hljs-built_in">cd</span> my-next-app
npm run dev
</code></pre>
<p>This command creates a new Next.js application in a folder called <code>my-next-app</code> and starts the development server.</p>
<h3 id="heading-step-2-understand-the-project-structure">Step 2: Understand the Project Structure</h3>
<p>Next.js organizes the project with some default folders and files:</p>
<ul>
<li><strong><code>pages/</code></strong>: This folder contains all the pages of your application. Each file represents a route in your app.</li>
<li><strong><code>public/</code></strong>: Static assets like images can be placed here.</li>
<li><strong><code>styles/</code></strong>: Contains CSS files for styling your application.</li>
</ul>
<h3 id="heading-step-3-create-a-simple-page-with-ssr">Step 3: Create a Simple Page with SSR</h3>
<p>Now, let's create a simple page that uses SSR.</p>
<p>Create a new file <code>pages/index.js</code>:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// pages/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">const</span> Home = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome to Next.js with SSR<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>Data fetched from the server: {data.message}<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">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getServerSideProps</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Fetch data from an API or other sources</span>
  <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json();

  <span class="hljs-comment">// Return the data as props to the Home component</span>
  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">props</span>: {
      data,
    },
  };
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Home;
</code></pre>
<p>Let's discuss this code in some detail. For the <code>home</code> component:</p>
<ul>
<li>The <code>Home</code> component is a functional component that accepts <code>props</code>.</li>
<li>The <code>data</code> prop contains the data fetched from the server.</li>
<li>Inside the component, we render a welcome message and the fetched data.</li>
</ul>
<p>The <code>getServerSideProps</code> function:</p>
<ul>
<li>This function is exported from the <code>pages/index.js</code> file.</li>
<li>It executes on the server for each request to this page.</li>
<li>Inside this function, you can perform asynchronous operations such as fetching data from an external API.</li>
<li>The fetched data is returned as an object with a <code>props</code> key. This object will be passed to the <code>Home</code> component as props.</li>
</ul>
<p>You can add error handling to the <code>getServerSideProps</code> function to manage any issues that might arise during data fetching. Here's an example:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getServerSideProps</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
    <span class="hljs-keyword">if</span> (!res.ok) {
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Failed to fetch data'</span>);
    }
    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json();
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">props</span>: {
        data,
      },
    };
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(error);
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">props</span>: {
        <span class="hljs-attr">data</span>: { <span class="hljs-attr">message</span>: <span class="hljs-string">'Error fetching data'</span> },
      },
    };
  }
}
</code></pre>
<h4 id="heading-step-4-run-the-application">Step 4: Run the Application</h4>
<p>Start your development server if it's not already running:</p>
<pre><code class="lang-bash">npm run dev
</code></pre>
<p>Open your browser and go to <code>http://localhost:3000</code>. You should see the message fetched from the API displayed on the page.</p>
<h2 id="heading-how-nextjs-enables-server-side-rendering">How Next.js Enables Server-Side Rendering</h2>
<p>Next.js provides a seamless way to enable SSR and Static Site Generation (SSG). It pre-renders every page by default. Depending on the use case, you can choose between SSR and SSG:</p>
<ul>
<li><strong>Server-Side Rendering (SSR)</strong>: Pages are rendered on each request.</li>
<li><strong>Static Site Generation (SSG)</strong>: Pages are generated at build time.</li>
</ul>
<p>Next.js determines which rendering method to use based on the functions you implement in your page components (<code>getStaticProps</code> and <code>getServerSideProps</code>).</p>
<h3 id="heading-nextjs-page-components">Next.js Page Components</h3>
<p>Next.js uses the <code>pages/</code> directory to define routes. Each file in this directory corresponds to a route in your application.</p>
<ul>
<li><code>pages/index.js</code> → <code>/</code></li>
<li><code>pages/about.js</code> → <code>/about</code></li>
<li><code>pages/posts/[id].js</code> → <code>/posts/:id</code></li>
</ul>
<p>Here's a basic example of a page component:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// pages/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">const</span> Home = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome to Next.js<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is the home page.<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> Home;
</code></pre>
<h3 id="heading-data-fetching-with-getstaticprops-and-getserversideprops">Data Fetching with <code>getStaticProps</code> and <code>getServerSideProps</code></h3>
<p><code>getStaticProps</code> is used for static generation. It runs at build time and allows you to fetch data and pass it to your page as props. Use this for data that doesn't change often.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// pages/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">const</span> Home = <span class="hljs-function">(<span class="hljs-params">{ posts }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Blog Posts<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
        {posts.map(post =&gt; (
          <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{post.id}</span>&gt;</span>{post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        ))}
      <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span class="hljs-comment">// This function runs at build time</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getStaticProps</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Fetch data from an API</span>
  <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/posts'</span>);
  <span class="hljs-keyword">const</span> posts = <span class="hljs-keyword">await</span> res.json();

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">props</span>: {
      posts,
    },
  };
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Home;
</code></pre>
<p><code>getServerSideProps</code> is used for server-side rendering. It runs on every request and allows you to fetch data at request time.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// pages/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">const</span> Home = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Server-Side Rendering with Next.js<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>Data fetched from the server: {data.message}<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-comment">// This function runs on every request</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getServerSideProps</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Fetch data from an external API</span>
  <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json();

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">props</span>: {
      data,
    },
  };
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Home;
</code></pre>
<h2 id="heading-benefits-of-ssr-for-seo-with-nextjs-and-how-to-optimize">Benefits of SSR for SEO with Next.js and How to Optimize</h2>
<p>In this section, we will look at the main benefits of using SSR for SEO and give easy-to-follow tips on how to make the most of these benefits with your Next.js application.</p>
<h3 id="heading-1-improved-indexing-by-search-engines">1. Improved Indexing by Search Engines</h3>
<p>Client-side rendering (CSR) can cause issues with search engines struggling to index content properly since it is rendered in the user's browser using JavaScript. </p>
<p>SSR, however, renders content on the server before sending it to the user's browser, ensuring the HTML is complete and can be easily crawled and indexed by search engines.</p>
<p><strong>Use SSR for important pages:</strong> Ensure that key pages, such as landing pages, blog posts, and product pages, are rendered on the server to facilitate better indexing.</p>
<p>Example – Using SSR for a blog post page:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// pages/blog/[id].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> { useRouter } <span class="hljs-keyword">from</span> <span class="hljs-string">'next/router'</span>;
<span class="hljs-keyword">import</span> Head <span class="hljs-keyword">from</span> <span class="hljs-string">'next/head'</span>;

<span class="hljs-keyword">const</span> BlogPost = <span class="hljs-function">(<span class="hljs-params">{ post }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> router = useRouter();
  <span class="hljs-keyword">if</span> (router.isFallback) {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</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">Head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>{post.title}<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">"description"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">{post.excerpt}</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">h1</span>&gt;</span>{post.title}<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>{post.content}<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">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getServerSideProps</span>(<span class="hljs-params">{ params }</span>) </span>{
  <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://api.example.com/posts/<span class="hljs-subst">${params.id}</span>`</span>);
  <span class="hljs-keyword">const</span> post = <span class="hljs-keyword">await</span> res.json();

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">props</span>: {
      post,
    },
  };
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> BlogPost
</code></pre>
<ul>
<li><strong>BlogPost Component:</strong> This component displays a blog post. It uses <code>next/head</code> to manage meta tags, which are important for SEO.</li>
<li><strong>getServerSideProps Function:</strong> This function fetches data for the blog post from an API. It runs on the server for every request to this page, ensuring the content is ready for search engines to index when they crawl the page.</li>
</ul>
<h3 id="heading-2-faster-load-times">2. Faster Load Times</h3>
<p>Search engines like Google use page load speed as a ranking factor. SSR can improve initial load time because the server sends a fully rendered page to the browser, enhancing perceived performance and user experience.</p>
<p><strong>Optimize server response time:</strong> Ensure your server is optimized for quick responses. Use caching strategies to reduce server load.</p>
<p>Example – cache-control header for SSR:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getServerSideProps</span>(<span class="hljs-params">{ res }</span>) </span>{
  res.setHeader(<span class="hljs-string">'Cache-Control'</span>, <span class="hljs-string">'public, s-maxage=10, stale-while-revalidate=59'</span>);

  <span class="hljs-keyword">const</span> resData = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/data'</span>);
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> resData.json();

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">props</span>: {
      data,
    },
  };
}
</code></pre>
<ul>
<li><strong><code>getServerSideProps</code> Function:</strong> This function sets cache-control headers to cache the response for 10 seconds and serve stale content while revalidating for 59 seconds. This improves server response time and page load speed, contributing to better SEO.</li>
</ul>
<h3 id="heading-3-improved-social-media-sharing">3. Improved Social Media Sharing</h3>
<p>When sharing links on social media, platforms like Facebook and Twitter scrape the URL content to generate previews. SSR ensures that necessary metadata is available in the initial HTML, resulting in better previews and increased click-through rates.</p>
<p><strong>Manage meta tags with <code>next/head</code>:</strong> Use the <code>next/head</code> component to add meta tags for social media and SEO.</p>
<p>Example – Adding meta tags to a page:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> Head <span class="hljs-keyword">from</span> <span class="hljs-string">'next/head'</span>;

<span class="hljs-keyword">const</span> Page = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =&gt;</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">Head</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>{data.title}<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">"description"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">{data.description}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">property</span>=<span class="hljs-string">"og:title"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">{data.title}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">property</span>=<span class="hljs-string">"og:description"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">{data.description}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">property</span>=<span class="hljs-string">"og:image"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">{data.image}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"twitter:card"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"summary_large_image"</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">h1</span>&gt;</span>{data.title}<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>{data.content}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
);
</code></pre>
<ul>
<li><strong><code>Page</code> Component:</strong> This component uses <code>next/head</code> to add SEO meta tags, including Open Graph tags for social media previews. This ensures that when the page is shared, social media platforms can generate rich previews with the provided metadata.</li>
</ul>
<h3 id="heading-4-enhanced-user-experience">4. Enhanced User Experience</h3>
<p>A faster, more responsive website enhances the overall user experience, leading to longer visit durations and lower bounce rates. Both factors positively influence your SEO rankings.</p>
<p><strong>Pre-render pages with static generation (SSG) for less dynamic content:</strong> Use SSG for pages that don’t change often to reduce server load and improve performance.</p>
<p>Example – Using SSG for a static page:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getStaticProps</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/static-data'</span>);
  <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> res.json();

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">props</span>: {
      data,
    },
    <span class="hljs-attr">revalidate</span>: <span class="hljs-number">10</span>, <span class="hljs-comment">// Revalidate at most once every 10 seconds</span>
  };
}

<span class="hljs-keyword">const</span> StaticPage = <span class="hljs-function">(<span class="hljs-params">{ data }</span>) =&gt;</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>{data.title}<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>{data.content}<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> StaticPage;
</code></pre>
<ul>
<li><strong><code>StaticPage</code> Component:</strong> This component displays static content fetched from an API.</li>
<li><strong><code>getStaticProps</code> Function:</strong> This function fetches data at build time and revalidates it every 10 seconds, ensuring the content is always fresh while reducing server load.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Using server-side rendering and Next.js together is like giving your website an extra boost for search engines. With pre-built content for search engines and a smooth experience for visitors, your site is set up to be seen by more people naturally.  </p>
<p>This works great for any kind of website, from online stores to blogs. Next.js with SSR makes it easy to build a website that search engines love and users enjoy.</p>
<p>That's all for this article! If you'd like to continue the conversation or have questions, suggestions, or feedback, feel free to reach out to connect with me on <a target="_blank" href="https://ng.linkedin.com/in/joan-ayebola">LinkedIn</a>. And if you enjoyed this content, consider <a target="_blank" href="https://www.buymeacoffee.com/joanayebola">buying me a coffee</a> to support the creation of more developer-friendly contents.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Data Flow in Redux Explained – A State Management Handbook ]]>
                </title>
                <description>
                    <![CDATA[ In complex React applications, managing application state effectively can become a challenge. This is where Redux, a predictable state management library, steps in. By introducing a unidirectional data flow, Redux brings order and clarity to how data... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-data-flows-in-redux/</link>
                <guid isPermaLink="false">66c4c3d48e05d0e4345147c6</guid>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Redux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ State Management  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Wed, 03 Jul 2024 13:45:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/07/Data-Flow-in-Redux-Explained-Cover-No-Photo.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In complex React applications, managing application state effectively can become a challenge. This is where Redux, a predictable state management library, steps in.</p>
<p>By introducing a unidirectional data flow, Redux brings order and clarity to how data updates and interacts within your React components.</p>
<p>This article discusses the inner workings of Redux, specifically focusing on how data flows throughout your application. We'll explore core concepts like the Redux store, actions, reducers, and selectors, along with practical examples of how they work together to seamlessly manage your application state.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-redux">What is Redux?</a></li>
<li><a class="post-section-overview" href="#heading-why-use-redux-for-data-management">Why Use Redux for Data Management?</a></li>
<li><a class="post-section-overview" href="#heading-core-concepts-of-redux-data-flow">Core Concepts of Redux Data Flow</a>  </li>
<li><a class="post-section-overview" href="#heading-unidirectional-data-flow">Unidirectional Data Flow</a>  </li>
<li><a class="post-section-overview" href="#heading-benefits-of-unidirectional-data-flow">Benefits of Unidirectional Data Flow</a></li>
<li><a class="post-section-overview" href="#heading-state-management-with-redux-store">State Management with Redux Store</a>  </li>
<li><a class="post-section-overview" href="#heading-what-is-the-redux-store">What is the Redux Store?</a>  </li>
<li><a class="post-section-overview" href="#heading-store-structure-state-reducers-actions">Store Structure (State, Reducers, Actions)</a></li>
<li><a class="post-section-overview" href="#heading-actions-initiating-state-changes">Actions: Initiating State Changes</a>  </li>
<li><a class="post-section-overview" href="#heading-action-creators-functions-to-create-actions">Action Creators (Functions to Create Actions)</a>  </li>
<li><a class="post-section-overview" href="#heading-action-types-identifying-different-actions">Action Types (Identifying Different Actions)</a></li>
<li><a class="post-section-overview" href="#heading-how-to-process-state-changes">How to Process State Changes</a>  </li>
<li><a class="post-section-overview" href="#heading-pure-functions-reducers-at-the-core">Pure Functions: Reducers at the Core</a>  </li>
<li><a class="post-section-overview" href="#heading-characteristics-of-pure-functions">Characteristics of Pure Functions</a> </li>
<li><a class="post-section-overview" href="#heading-anatomy-of-a-reducer-function">Anatomy of a Reducer Function</a>  </li>
<li><a class="post-section-overview" href="#heading-parameters-previous-state-and-action-object">Parameters: Previous State and Action Object</a>  </li>
<li><a class="post-section-overview" href="#heading-return-value-updated-state">Return Value: Updated State</a></li>
<li><a class="post-section-overview" href="#heading-how-to-handle-different-actions-in-reducers">How to Handle Different Actions in Reducers</a>  </li>
<li><a class="post-section-overview" href="#heading-using-switch-statements">Using Switch Statements or Conditional Logic</a></li>
<li><a class="post-section-overview" href="#heading-dispatching-actions-how-to-update-the-redux-store">Dispatching Actions: How to Update the Redux Store</a>  </li>
<li><a class="post-section-overview" href="#heading-the-dispatch-function">The <code>dispatch</code> Function</a>  </li>
<li><a class="post-section-overview" href="#heading-dispatching-actions-from-components-or-events">Dispatching Actions from Components or Events</a></li>
<li><a class="post-section-overview" href="#heading-how-to-access-specific-data-from-the-store">How to Access Specific Data from the Store</a>  </li>
<li><a class="post-section-overview" href="#heading-creating-selector-functions">Creating Selector Functions</a>  </li>
<li><a class="post-section-overview" href="#heading-memoization-for-efficient-selector-usage">Memoization for Efficient Selector Usage</a></li>
<li><a class="post-section-overview" href="#heading-how-to-connect-react-components-to-redux">How to Connect React Components to Redux</a>  </li>
<li><a class="post-section-overview" href="#heading-the-connect-function-from-react-redux-library">The <code>connect</code> Function from <code>react-redux</code> Library</a>  </li>
<li><a class="post-section-overview" href="#heading-mapping-state-and-dispatch-to-props">Mapping State and Dispatch to Props</a>  </li>
<li><a class="post-section-overview" href="#heading-using-connected-components-in-your-application">Using Connected Components in Your Application</a></li>
<li><a class="post-section-overview" href="#heading-advanced-redux-data-flow-techniques">Advanced Redux Data Flow Techniques</a>  </li>
<li><a class="post-section-overview" href="#heading-asynchronous-actions-redux-thunk-redux-saga">Asynchronous Actions (Redux Thunk, Redux Saga)</a>  </li>
<li><a class="post-section-overview" href="#heading-middleware-for-extending-redux-functionality">Middleware for Extending Redux Functionality</a></li>
<li><a class="post-section-overview" href="#heading-best-practices-for-managing-data-flow-in-redux">Best Practices for Managing Data Flow in Redux</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-is-redux">What is Redux?</h2>
<p>Redux is a predictable state container for JavaScript applications, primarily used with libraries like React. It helps manage the application state in a centralized store, making it easier to manage and update state across your entire application.</p>
<p>In simple terms, Redux provides a way to store and manage the data that your application needs to work. It follows a strict pattern to ensure that state changes are predictable and manageable.</p>
<h2 id="heading-why-use-redux-for-data-management">Why Use Redux for Data Management?</h2>
<p>Using Redux for data management in your application offers several advantages:</p>
<p><strong>Centralized State Management</strong>: Redux stores the application's state in a single store, making it easier to manage and debug compared to having scattered state across multiple components.</p>
<p><strong>Predictable State Changes</strong>: State mutations are done through reducers, which are pure functions. This ensures that state changes are predictable and traceable, making it easier to understand how data flows through your application.</p>
<p><strong>Easier Debugging</strong>: With a single source of truth, debugging becomes simpler. You can log state changes, track actions, and even implement time-travel debugging (via Redux DevTools) to replay actions and inspect state at any point in time.</p>
<p><strong>Facilitates Testing</strong>: Since reducers are pure functions that depend only on their input and produce predictable output, testing becomes straightforward. You can easily test how reducers update the state in response to different actions.</p>
<p><strong>Enforces Unidirectional Data Flow</strong>: Redux follows a strict unidirectional data flow pattern. Data flows in one direction: actions are dispatched, reducers update the state immutably, and components subscribe to the changes they're interested in. This pattern simplifies data management and reduces bugs related to inconsistent state.</p>
<p><strong>Eases State Persistence</strong>: Redux makes it easier to persist your application state across sessions or store it locally, enhancing the user experience by preserving data between visits.</p>
<p><strong>Scalability</strong>: Redux scales well with large applications because of its centralized state management. As your application grows, managing state becomes more manageable and less error-prone compared to using local component state or prop drilling.</p>
<h2 id="heading-core-concepts-of-redux-data-flow">Core Concepts of Redux Data Flow</h2>
<p>Understanding the core concepts of Redux data flow is essential for mastering state management in modern JavaScript applications.</p>
<h3 id="heading-unidirectional-data-flow">Unidirectional Data Flow</h3>
<p>Redux follows a strict unidirectional data flow pattern, which means that data in your application moves in a single direction through a series of steps:</p>
<ol>
<li><strong>Actions</strong>: Actions are plain JavaScript objects that represent an intention to change the state. They are the only source of information for the store.</li>
<li><strong>Reducers</strong>: Reducers are pure functions responsible for handling state transitions based on actions. They specify how the application's state changes in response to actions sent to the store.</li>
<li><strong>Store</strong>: The store holds the application state. It allows access to the state via <code>getState()</code>, updates the state via <code>dispatch(action)</code>, and registers listeners via <code>subscribe(listener)</code>.</li>
<li><strong>View</strong>: React components (or any other UI layer) subscribe to the store to receive updates when the state changes. They then re-render based on the updated state.</li>
</ol>
<p>Here’s a simplified overview of how the unidirectional data flow works in Redux:</p>
<ol>
<li><strong>Action Dispatch</strong>: Components dispatch actions to the Redux store using <code>store.dispatch(action)</code>. Actions are plain JavaScript objects with a <code>type</code> field that describes the type of action being performed.</li>
<li><strong>Action Handling</strong>: The store passes the dispatched action to the root reducer. The reducer is a pure function that takes the current state and the action, computes the new state based on the action, and returns the updated state.</li>
<li><strong>State Update</strong>: The Redux store updates its state based on the return value of the root reducer. It notifies all subscribed components of the state change.</li>
<li><strong>Component Re-render</strong>: Components that are subscribed to the store receive the updated state as props. They re-render with the new data.</li>
</ol>
<h3 id="heading-benefits-of-unidirectional-data-flow">Benefits of Unidirectional Data Flow</h3>
<p><strong>Predictability</strong>: By enforcing a single direction for data flow, Redux makes state changes more predictable and easier to understand. Actions are explicit about what changes are happening, and reducers clearly define how the state transitions occur.</p>
<p><strong>Debugging</strong>: Unidirectional data flow simplifies debugging because you can trace how state changes propagate through your application. Redux DevTools enhance this further by allowing you to track actions, inspect state changes over time, and even replay actions to reproduce bugs.</p>
<p><strong>Maintainability</strong>: With a clear separation between data (state) and logic (reducers), Redux promotes cleaner, more maintainable code. It reduces the likelihood of bugs caused by inconsistent state mutations or side effects.</p>
<p><strong>Scalability</strong>: As your application grows in size and complexity, unidirectional data flow helps manage state updates more effectively. It avoids the pitfalls of two-way data binding and ensures that changes to the state are controlled and manageable.</p>
<p><strong>Testing</strong>: Since reducers are pure functions that take inputs and produce outputs without side effects, unit testing becomes straightforward. You can test reducers with different actions and state scenarios to ensure they behave as expected.</p>
<h2 id="heading-state-management-with-redux-store">State Management with Redux Store</h2>
<p>State management plays a pivotal role in modern web development, ensuring applications maintain consistent and predictable states across various components.</p>
<h3 id="heading-what-is-the-redux-store">What is the Redux Store?</h3>
<p>The Redux Store is the heart of Redux state management. It holds the entire state tree of your application. The store allows you to:</p>
<ul>
<li>Access the current state of your application via <code>store.getState()</code>.</li>
<li>Dispatch actions to change the state using <code>store.dispatch(action)</code>.</li>
<li>Subscribe to changes in the state so your components can update accordingly using <code>store.subscribe(listener)</code>.</li>
</ul>
<p>In essence, the Redux Store acts as a centralized repository for the state of your application, facilitating predictable data flow and making state management more manageable.</p>
<h3 id="heading-store-structure-state-reducers-actions">Store Structure (State, Reducers, Actions)</h3>
<p>The <strong>state</strong> in Redux represents the entire state of your application. It is typically structured as a plain JavaScript object. The shape of the state is defined by the reducers. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">todos</span>: [],
  <span class="hljs-attr">visibilityFilter</span>: <span class="hljs-string">'SHOW_ALL'</span>,
};
</code></pre>
<p>In this example, <code>todos</code> and <code>visibilityFilter</code> are pieces of state managed by Redux.</p>
<p><strong>Reducers</strong> are functions that specify how the application's state changes in response to actions dispatched to the store. They take the current state and an action as arguments, and return the new state based on the action type. </p>
<p>Reducers must be pure functions, meaning they produce the same output for the same input and do not modify the state directly.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> todosReducer = <span class="hljs-function">(<span class="hljs-params">state = [], action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'ADD_TODO'</span>:
      <span class="hljs-keyword">return</span> [
        ...state,
        {
          <span class="hljs-attr">id</span>: action.id,
          <span class="hljs-attr">text</span>: action.text,
          <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
        }
      ];
    <span class="hljs-keyword">case</span> <span class="hljs-string">'TOGGLE_TODO'</span>:
      <span class="hljs-keyword">return</span> state.map(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span>
        (todo.id === action.id)
          ? { ...todo, <span class="hljs-attr">completed</span>: !todo.completed }
          : todo
      );
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
};
</code></pre>
<p>In this example, <code>todosReducer</code> manages the <code>todos</code> piece of state, handling actions like <code>'ADD_TODO'</code> and <code>'TOGGLE_TODO'</code> to add new todos or toggle their completion status.</p>
<p><strong>Actions</strong> are plain JavaScript objects that describe what happened in your application. They are the only source of information for the store. Actions typically have a <code>type</code> field that indicates the type of action being performed, and they may also carry additional data necessary for the action.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> addTodo = <span class="hljs-function">(<span class="hljs-params">text</span>) =&gt;</span> ({
  <span class="hljs-attr">type</span>: <span class="hljs-string">'ADD_TODO'</span>,
  <span class="hljs-attr">id</span>: nextTodoId++,
  text
});

<span class="hljs-keyword">const</span> toggleTodo = <span class="hljs-function">(<span class="hljs-params">id</span>) =&gt;</span> ({
  <span class="hljs-attr">type</span>: <span class="hljs-string">'TOGGLE_TODO'</span>,
  id
});
</code></pre>
<p>In this example, <code>addTodo</code> and <code>toggleTodo</code> are action creator functions that return actions to add a new todo and toggle the completion status of a todo, respectively.</p>
<p>The relationship between these elements in Redux is crucial for managing application state effectively:</p>
<ul>
<li><strong>Actions</strong> describe events that occur in your application.</li>
<li><strong>Reducers</strong> specify how the application's state changes in response to actions.</li>
<li><strong>Store</strong> holds the application state and allows you to dispatch actions to update the state.</li>
</ul>
<p>Together, these components form the core structure of Redux state management, providing a clear and predictable way to manage and update application state across your entire application.</p>
<h2 id="heading-actions-initiating-state-changes">Actions: Initiating State Changes</h2>
<p>Managing state effectively lies at the core of creating dynamic and responsive applications. Actions, within the Redux architecture and similar state management libraries, serve as important elements for initiating state changes.</p>
<h3 id="heading-action-creators-functions-to-create-actions">Action Creators (Functions to Create Actions)</h3>
<p>Action creators in Redux are functions that create and return action objects. These action objects describe what happened in your application and are dispatched to the Redux store to initiate state changes. </p>
<p>Action creators encapsulate the logic of creating actions, making your code more modular and easier to test.</p>
<p>Here's an example of an action creator:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Action creator function</span>
<span class="hljs-keyword">const</span> addTodo = <span class="hljs-function">(<span class="hljs-params">text</span>) =&gt;</span> ({
  <span class="hljs-attr">type</span>: <span class="hljs-string">'ADD_TODO'</span>,
  <span class="hljs-attr">id</span>: nextTodoId++,
  text
});

<span class="hljs-comment">// Usage of the action creator</span>
<span class="hljs-keyword">const</span> newTodoAction = addTodo(<span class="hljs-string">'Buy groceries'</span>);
</code></pre>
<p>In this example:</p>
<ul>
<li><code>addTodo</code> is an action creator function that takes <code>text</code> as a parameter and returns an action object.</li>
<li>The action object has a <code>type</code> field (<code>'ADD_TODO'</code>) that identifies the type of action and additional fields (<code>id</code> and <code>text</code>) that provide necessary data for the action.</li>
</ul>
<p>Action creators simplify the process of creating actions, especially when actions require complex data or calculations before dispatching.</p>
<h3 id="heading-action-types-identifying-different-actions">Action Types (Identifying Different Actions)</h3>
<p>Action types in Redux are string constants that define the type of action being performed. They are used to identify and differentiate different actions that can be dispatched to the Redux store. By using string constants for action types, Redux ensures that action types are unique and easy to reference throughout your application.</p>
<p>Here's how action types are typically defined:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Action types as constants</span>
<span class="hljs-keyword">const</span> ADD_TODO = <span class="hljs-string">'ADD_TODO'</span>;
<span class="hljs-keyword">const</span> TOGGLE_TODO = <span class="hljs-string">'TOGGLE_TODO'</span>;
<span class="hljs-keyword">const</span> SET_VISIBILITY_FILTER = <span class="hljs-string">'SET_VISIBILITY_FILTER'</span>;
</code></pre>
<p>These constants (<code>ADD_TODO</code>, <code>TOGGLE_TODO</code>, <code>SET_VISIBILITY_FILTER</code>) represent different actions that can occur in your application, such as adding a todo, toggling the completion status of a todo, or setting a visibility filter for todos.</p>
<p>Action types are typically used in action objects created by action creators and are matched in reducers to determine how the state should change in response to each action.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example of using action types in a reducer</span>
<span class="hljs-keyword">const</span> todosReducer = <span class="hljs-function">(<span class="hljs-params">state = [], action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> ADD_TODO:
      <span class="hljs-keyword">return</span> [
        ...state,
        {
          <span class="hljs-attr">id</span>: action.id,
          <span class="hljs-attr">text</span>: action.text,
          <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
        }
      ];
    <span class="hljs-keyword">case</span> TOGGLE_TODO:
      <span class="hljs-keyword">return</span> state.map(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span>
        (todo.id === action.id)
          ? { ...todo, <span class="hljs-attr">completed</span>: !todo.completed }
          : todo
      );
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
};
</code></pre>
<p>In this example:</p>
<ul>
<li><code>ADD_TODO</code> and <code>TOGGLE_TODO</code> are action types used in the <code>todosReducer</code> to handle different types of actions (<code>'ADD_TODO'</code> and <code>'TOGGLE_TODO'</code>).</li>
<li>The <code>action.type</code> field in the switch statement ensures that the reducer responds appropriately to each dispatched action based on its type.</li>
</ul>
<h2 id="heading-how-to-process-state-changes">How to Process State Changes</h2>
<p>At the heart of state management are reducers, pure functions designed to handle state transitions in a controlled and immutable manner.</p>
<h3 id="heading-pure-functions-reducers-at-the-core">Pure Functions: Reducers at the Core</h3>
<p>Reducers in Redux are pure functions responsible for specifying how the application's state changes in response to actions dispatched to the store. They take the current state and an action as arguments, and return the new state based on the action type.</p>
<p>Here’s a breakdown of how reducers work and their role in managing state changes:</p>
<p><strong>Pure Functions</strong>: Reducers are pure functions, which means they:</p>
<ul>
<li>Produce the same output for the same input every time they are called.</li>
<li>Do not cause any side effects (such as modifying arguments or global variables).</li>
<li>Do not mutate the state directly, but instead return a new state object.</li>
</ul>
<p><strong>Handling State Transitions</strong>: Reducers specify how the application's state changes in response to different types of actions. They use the current state and the action dispatched to compute and return the new state.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example of a todos reducer</span>
<span class="hljs-keyword">const</span> todosReducer = <span class="hljs-function">(<span class="hljs-params">state = [], action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'ADD_TODO'</span>:
      <span class="hljs-keyword">return</span> [
        ...state,
        {
          <span class="hljs-attr">id</span>: action.id,
          <span class="hljs-attr">text</span>: action.text,
          <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
        }
      ];
    <span class="hljs-keyword">case</span> <span class="hljs-string">'TOGGLE_TODO'</span>:
      <span class="hljs-keyword">return</span> state.map(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span>
        (todo.id === action.id)
          ? { ...todo, <span class="hljs-attr">completed</span>: !todo.completed }
          : todo
      );
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
};
</code></pre>
<p>In this example:</p>
<ul>
<li><code>todosReducer</code> is a pure function that takes <code>state</code> (current todos array) and <code>action</code> as arguments.</li>
<li>Depending on the <code>action.type</code>, it computes and returns a new state (updated todos array).</li>
</ul>
<p><strong>Immutable State Updates</strong>: Reducers should never mutate the state directly. Instead, they create copies of the state and modify the copies to produce a new state object. This ensures that Redux can detect state changes and update components efficiently.</p>
<p><strong>Single Responsibility Principle</strong>: Each reducer typically handles updates to a specific slice of the application state. This helps maintain a clear separation of concerns and makes reducers easier to understand, test, and maintain.</p>
<h3 id="heading-characteristics-of-pure-functions">Characteristics of Pure Functions</h3>
<p>Pure functions, including Redux reducers, have specific characteristics that make them well-suited for managing state changes:</p>
<p><strong>Deterministic</strong>: A pure function always produces the same output for the same input. This predictability ensures that reducers behave consistently and are easier to reason about.</p>
<p><strong>No Side Effects</strong>: Pure functions do not modify the input arguments or any external state. They only depend on their input parameters and produce an output without causing observable side effects.</p>
<p><strong>Immutable Data</strong>: Pure functions do not mutate data. Instead, they create and return new data structures. In Redux, reducers produce a new state object without modifying the existing state, enabling efficient change detection and state management.</p>
<p><strong>Referential Transparency</strong>: Pure functions can be replaced with their return values without affecting the correctness of the program. This property supports composability and makes it easier to test and reason about code.</p>
<h2 id="heading-anatomy-of-a-reducer-function">Anatomy of a Reducer Function</h2>
<p>A reducer function, at its core, defines how application state changes in response to dispatched actions. This function takes two parameters: the current state and an action object, determining the new state based on the type of action received.</p>
<h3 id="heading-parameters-previous-state-and-action-object">Parameters: Previous State and Action Object</h3>
<p>A reducer function in Redux is a pure function that takes two parameters: the previous state (state before the action is applied) and an action object. These parameters define how the reducer computes the next state of the application.</p>
<p><strong>Previous State</strong>: This parameter represents the current state of the application before the action is dispatched. It is immutable and should not be modified directly within the reducer.</p>
<p><strong>Action Object</strong>: An action object is a plain JavaScript object that describes what happened in your application. It typically has a <code>type</code> field that indicates the type of action being performed. Other fields in the action object may provide additional data necessary to update the state.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> action = {
  <span class="hljs-attr">type</span>: <span class="hljs-string">'ADD_TODO'</span>,
  <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">text</span>: <span class="hljs-string">'Buy groceries'</span>
};
</code></pre>
<p>In this example, <code>action.type</code> is <code>'ADD_TODO'</code>, indicating that we want to add a new todo item to the state.</p>
<h3 id="heading-return-value-updated-state">Return Value: Updated State</h3>
<p>The reducer function must return the updated state based on the previous state and the action object passed to it. The updated state is typically a new object that represents the application's state after applying the action.</p>
<p>Here’s the basic structure of a reducer function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">todos</span>: [],
  <span class="hljs-attr">visibilityFilter</span>: <span class="hljs-string">'SHOW_ALL'</span>
};

<span class="hljs-keyword">const</span> todoAppReducer = <span class="hljs-function">(<span class="hljs-params">state = initialState, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'ADD_TODO'</span>:
      <span class="hljs-keyword">return</span> {
        ...state,
        <span class="hljs-attr">todos</span>: [
          ...state.todos,
          {
            <span class="hljs-attr">id</span>: action.id,
            <span class="hljs-attr">text</span>: action.text,
            <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
          }
        ]
      };
    <span class="hljs-keyword">case</span> <span class="hljs-string">'TOGGLE_TODO'</span>:
      <span class="hljs-keyword">return</span> {
        ...state,
        <span class="hljs-attr">todos</span>: state.todos.map(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span>
          (todo.id === action.id)
            ? { ...todo, <span class="hljs-attr">completed</span>: !todo.completed }
            : todo
        )
      };
    <span class="hljs-keyword">case</span> <span class="hljs-string">'SET_VISIBILITY_FILTER'</span>:
      <span class="hljs-keyword">return</span> {
        ...state,
        <span class="hljs-attr">visibilityFilter</span>: action.filter
      };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
};
</code></pre>
<p>In this example:</p>
<ul>
<li><code>todoAppReducer</code> is a reducer function that manages the state of todos and visibility filters.</li>
<li>It takes <code>state</code> (previous state) and <code>action</code> as parameters.</li>
<li>Depending on the <code>action.type</code>, it computes and returns a new state object that reflects the changes caused by the action.</li>
</ul>
<h3 id="heading-key-points">Key Points:</h3>
<p><strong>Immutable Update</strong>: Reducers should never modify the previous state directly. Instead, they create a new state object by copying the previous state (<code>...state</code>) and applying changes to it.</p>
<p><strong>Default Case</strong>: The <code>default</code> case in the <code>switch</code> statement returns the current state unchanged if the reducer doesn’t recognize the action type. This ensures that the reducer always returns a valid state object, even if no changes are made.</p>
<p><strong>Single Responsibility</strong>: Each case in the <code>switch</code> statement corresponds to a specific action type and is responsible for updating a specific slice of the application state. This promotes a clear separation of concerns and makes reducers easier to understand and maintain.</p>
<h2 id="heading-how-to-handle-different-actions-in-reducers">How to Handle Different Actions in Reducers</h2>
<p>In Redux, you can handle different actions in reducers using either switch statements or conditional logic. Both approaches aim to determine how the application state should change based on the type of action dispatched.</p>
<h3 id="heading-using-switch-statements">Using Switch Statements</h3>
<p>Switch statements are commonly used in Redux reducers to handle different action types. Each <code>case</code> in the switch statement corresponds to a specific action type, and the reducer executes the corresponding logic based on the action type.</p>
<p>Here's an example of using switch statements in a reducer:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">todos</span>: [],
  <span class="hljs-attr">visibilityFilter</span>: <span class="hljs-string">'SHOW_ALL'</span>
};

<span class="hljs-keyword">const</span> todoAppReducer = <span class="hljs-function">(<span class="hljs-params">state = initialState, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'ADD_TODO'</span>:
      <span class="hljs-keyword">return</span> {
        ...state,
        <span class="hljs-attr">todos</span>: [
          ...state.todos,
          {
            <span class="hljs-attr">id</span>: action.id,
            <span class="hljs-attr">text</span>: action.text,
            <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
          }
        ]
      };
    <span class="hljs-keyword">case</span> <span class="hljs-string">'TOGGLE_TODO'</span>:
      <span class="hljs-keyword">return</span> {
        ...state,
        <span class="hljs-attr">todos</span>: state.todos.map(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span>
          (todo.id === action.id)
            ? { ...todo, <span class="hljs-attr">completed</span>: !todo.completed }
            : todo
        )
      };
    <span class="hljs-keyword">case</span> <span class="hljs-string">'SET_VISIBILITY_FILTER'</span>:
      <span class="hljs-keyword">return</span> {
        ...state,
        <span class="hljs-attr">visibilityFilter</span>: action.filter
      };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
};
</code></pre>
<p>In this example:</p>
<ul>
<li>The <code>todoAppReducer</code> function uses a switch statement to handle different action types (<code>'ADD_TODO'</code>, <code>'TOGGLE_TODO'</code>, <code>'SET_VISIBILITY_FILTER'</code>).</li>
<li>Each <code>case</code> block specifies how the state should be updated in response to the corresponding action type.</li>
<li>The <code>default</code> case returns the current state unchanged if the reducer doesn’t recognize the action type, ensuring that the reducer always returns a valid state object.</li>
</ul>
<h3 id="heading-using-conditional-logic">Using Conditional Logic</h3>
<p>Alternatively, reducers can also use conditional logic (if-else statements) to determine how to update the state based on the action type. While less common than switch statements in Redux, conditional logic can be used similarly to handle actions.</p>
<p>Here's an example of using conditional logic in a reducer:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> todoAppReducer = <span class="hljs-function">(<span class="hljs-params">state = initialState, action</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (action.type === <span class="hljs-string">'ADD_TODO'</span>) {
    <span class="hljs-keyword">return</span> {
      ...state,
      <span class="hljs-attr">todos</span>: [
        ...state.todos,
        {
          <span class="hljs-attr">id</span>: action.id,
          <span class="hljs-attr">text</span>: action.text,
          <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
        }
      ]
    };
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (action.type === <span class="hljs-string">'TOGGLE_TODO'</span>) {
    <span class="hljs-keyword">return</span> {
      ...state,
      <span class="hljs-attr">todos</span>: state.todos.map(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span>
        (todo.id === action.id)
          ? { ...todo, <span class="hljs-attr">completed</span>: !todo.completed }
          : todo
      )
    };
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (action.type === <span class="hljs-string">'SET_VISIBILITY_FILTER'</span>) {
    <span class="hljs-keyword">return</span> {
      ...state,
      <span class="hljs-attr">visibilityFilter</span>: action.filter
    };
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> state;
  }
};
</code></pre>
<p>In this example:</p>
<ul>
<li>The <code>todoAppReducer</code> function uses if-else statements to check the action type (<code>action.type</code>) and execute different logic based on the type of action.</li>
<li>Each condition specifies how the state should be updated for the corresponding action type.</li>
<li>The final <code>else</code> block returns the current state unchanged if the action type is not recognized.</li>
</ul>
<h3 id="heading-choosing-between-switch-statements-and-conditional-logic">Choosing Between Switch Statements and Conditional Logic</h3>
<h4 id="heading-1-switch-statements">1. Switch Statements:</h4>
<ul>
<li>Advantages: Switch statements are typically more readable and maintainable when handling multiple action types in Redux reducers. They clearly separate different cases based on action types.</li>
<li>Considerations: Ensure each action type has a corresponding <code>case</code> in the switch statement to handle updates correctly.</li>
</ul>
<h4 id="heading-2-conditional-logic">2. Conditional Logic:</h4>
<ul>
<li>Advantages: Conditional logic (if-else statements) provides flexibility and can be easier to understand in certain scenarios where there are fewer action types.</li>
<li>Considerations: Maintain consistency in handling action types and ensure each condition handles state updates correctly.</li>
</ul>
<p>In practice, switch statements are the recommended approach in Redux reducers due to their clarity and convention within the Redux community. They help maintain a structured approach to managing state changes based on different action types, promoting consistency and predictability in Redux applications.</p>
<h2 id="heading-dispatching-actions-how-to-update-the-redux-store">Dispatching Actions: How to Update the Redux Store</h2>
<p>Dispatching actions in Redux is fundamental to managing state updates within your application. Redux, a predictable state container for JavaScript applications, relies on actions as payloads of information that send data from your application to the Redux store.</p>
<h3 id="heading-the-dispatch-function">The <code>dispatch</code> function</h3>
<p>In Redux, the <code>dispatch</code> function is a method provided by the Redux store. It is used to dispatch actions to trigger state changes in the application. When an action is dispatched, the Redux store calls the reducer function associated with it, computes the new state, and notifies all subscribers that the state has been updated.</p>
<p>Here's how you use the <code>dispatch</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createStore } <span class="hljs-keyword">from</span> <span class="hljs-string">'redux'</span>;

<span class="hljs-comment">// Reducer function</span>
<span class="hljs-keyword">const</span> counterReducer = <span class="hljs-function">(<span class="hljs-params">state = { count: <span class="hljs-number">0</span> }, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'INCREMENT'</span>:
      <span class="hljs-keyword">return</span> { ...state, <span class="hljs-attr">count</span>: state.count + <span class="hljs-number">1</span> };
    <span class="hljs-keyword">case</span> <span class="hljs-string">'DECREMENT'</span>:
      <span class="hljs-keyword">return</span> { ...state, <span class="hljs-attr">count</span>: state.count - <span class="hljs-number">1</span> };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
};

<span class="hljs-comment">// Create Redux store</span>
<span class="hljs-keyword">const</span> store = createStore(counterReducer);

<span class="hljs-comment">// Dispatch actions to update state</span>
store.dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">'INCREMENT'</span> });
store.dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">'DECREMENT'</span> });
</code></pre>
<p>In this example:</p>
<ul>
<li>We create a Redux store using <code>createStore</code> and pass in the <code>counterReducer</code> function.</li>
<li>The <code>store.dispatch</code> function is used to dispatch actions (<code>{ type: 'INCREMENT' }</code> and <code>{ type: 'DECREMENT' }</code>) to update the state.</li>
<li>Each dispatched action triggers the corresponding case in the reducer, updating the state as defined.</li>
</ul>
<h3 id="heading-dispatching-actions-from-components-or-events">Dispatching Actions from Components or Events</h3>
<p>In a typical Redux application, actions are often dispatched from React components in response to user interactions or other events. </p>
<p>To dispatch actions from components, you typically connect the component to the Redux store using React Redux's <code>connect</code> function or hooks like <code>useDispatch</code>.</p>
<p>Here's how you can dispatch actions from a React component using <code>connect</code> and <code>mapDispatchToProps</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-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>;

<span class="hljs-comment">// Action creator functions</span>
<span class="hljs-keyword">const</span> increment = <span class="hljs-function">() =&gt;</span> ({ <span class="hljs-attr">type</span>: <span class="hljs-string">'INCREMENT'</span> });
<span class="hljs-keyword">const</span> decrement = <span class="hljs-function">() =&gt;</span> ({ <span class="hljs-attr">type</span>: <span class="hljs-string">'DECREMENT'</span> });

<span class="hljs-comment">// Component definition</span>
<span class="hljs-keyword">const</span> Counter = <span class="hljs-function">(<span class="hljs-params">{ count, increment, decrement }</span>) =&gt;</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">p</span>&gt;</span>Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{increment}</span>&gt;</span>Increment<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">{decrement}</span>&gt;</span>Decrement<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-comment">// Map state to props</span>
<span class="hljs-keyword">const</span> mapStateToProps = <span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> ({
  <span class="hljs-attr">count</span>: state.count
});

<span class="hljs-comment">// Map dispatch to props</span>
<span class="hljs-keyword">const</span> mapDispatchToProps = {
  increment,
  decrement
};

<span class="hljs-comment">// Connect component to Redux store</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> connect(mapStateToProps, mapDispatchToProps)(Counter);
</code></pre>
<p>In this example:</p>
<ul>
<li><code>increment</code> and <code>decrement</code> are action creator functions that return actions (<code>{ type: 'INCREMENT' }</code> and <code>{ type: 'DECREMENT' }</code>).</li>
<li>The <code>Counter</code> component is connected to the Redux store using <code>connect</code>. It receives <code>count</code> from the Redux state as a prop, along with <code>increment</code> and <code>decrement</code> action creators.</li>
<li>Clicking the "Increment" and "Decrement" buttons dispatches actions, which are handled by the reducer to update the Redux state.</li>
</ul>
<p>Alternatively, you can use React Redux hooks (<code>useDispatch</code>) for dispatching actions in functional components:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { useDispatch, useSelector } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>;

<span class="hljs-keyword">const</span> Counter = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> count = useSelector(<span class="hljs-function"><span class="hljs-params">state</span> =&gt;</span> state.count);
  <span class="hljs-keyword">const</span> dispatch = useDispatch();

  <span class="hljs-keyword">const</span> handleIncrement = <span class="hljs-function">() =&gt;</span> {
    dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">'INCREMENT'</span> });
  };

  <span class="hljs-keyword">const</span> handleDecrement = <span class="hljs-function">() =&gt;</span> {
    dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">'DECREMENT'</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">p</span>&gt;</span>Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleIncrement}</span>&gt;</span>Increment<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">{handleDecrement}</span>&gt;</span>Decrement<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> Counter;
</code></pre>
<p>In this functional component example:</p>
<ul>
<li><code>useSelector</code> is used to select <code>count</code> from the Redux store state.</li>
<li><code>useDispatch</code> is used to get the <code>dispatch</code> function from the Redux store.</li>
<li><code>handleIncrement</code> and <code>handleDecrement</code> functions dispatch actions (<code>{ type: 'INCREMENT' }</code> and <code>{ type: 'DECREMENT' }</code>) to update the Redux state when the buttons are clicked.</li>
</ul>
<h2 id="heading-how-to-access-specific-data-from-the-store">How to Access Specific Data from the Store</h2>
<p>Accessing specific data from the store in Redux involves navigating through the application's state structure to retrieve precise information needed for rendering components or performing logic.</p>
<h3 id="heading-creating-selector-functions">Creating Selector Functions</h3>
<p>Selectors in Redux are functions that encapsulate the logic for retrieving specific pieces of data from the Redux store state. They help to decouple the components from the structure of the state and facilitate efficient data access and transformation.</p>
<p>Here’s how you can create selector functions:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example Redux state</span>
<span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">todos</span>: [
    { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">text</span>: <span class="hljs-string">'Learn Redux'</span>, <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span> },
    { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">text</span>: <span class="hljs-string">'Write Redux selectors'</span>, <span class="hljs-attr">completed</span>: <span class="hljs-literal">true</span> },
    <span class="hljs-comment">// more todos...</span>
  ],
  <span class="hljs-attr">visibilityFilter</span>: <span class="hljs-string">'SHOW_COMPLETED'</span>
};

<span class="hljs-comment">// Selector function to get todos from state</span>
<span class="hljs-keyword">const</span> getTodos = <span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> state.todos;

<span class="hljs-comment">// Selector function to filter todos based on visibility filter</span>
<span class="hljs-keyword">const</span> getVisibleTodos = <span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> todos = getTodos(state);
  <span class="hljs-keyword">const</span> visibilityFilter = state.visibilityFilter;

  <span class="hljs-keyword">switch</span> (visibilityFilter) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'SHOW_COMPLETED'</span>:
      <span class="hljs-keyword">return</span> todos.filter(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span> todo.completed);
    <span class="hljs-keyword">case</span> <span class="hljs-string">'SHOW_ACTIVE'</span>:
      <span class="hljs-keyword">return</span> todos.filter(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span> !todo.completed);
    <span class="hljs-keyword">case</span> <span class="hljs-string">'SHOW_ALL'</span>:
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> todos;
  }
};
</code></pre>
<p>In this example:</p>
<ul>
<li><code>getTodos</code> is a selector function that retrieves the <code>todos</code> array from the Redux state.</li>
<li><code>getVisibleTodos</code> is a selector function that filters <code>todos</code> based on the <code>visibilityFilter</code> stored in the state.</li>
</ul>
<p>Selectors can also be composed to create more complex selectors:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Composed selector function to get visible todos</span>
<span class="hljs-keyword">const</span> getVisibleTodos = <span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> todos = getTodos(state);
  <span class="hljs-keyword">const</span> visibilityFilter = state.visibilityFilter;

  <span class="hljs-keyword">switch</span> (visibilityFilter) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'SHOW_COMPLETED'</span>:
      <span class="hljs-keyword">return</span> getCompletedTodos(todos);
    <span class="hljs-keyword">case</span> <span class="hljs-string">'SHOW_ACTIVE'</span>:
      <span class="hljs-keyword">return</span> getActiveTodos(todos);
    <span class="hljs-keyword">case</span> <span class="hljs-string">'SHOW_ALL'</span>:
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> todos;
  }
};

<span class="hljs-comment">// Helper functions for filtering todos</span>
<span class="hljs-keyword">const</span> getCompletedTodos = <span class="hljs-function">(<span class="hljs-params">todos</span>) =&gt;</span> todos.filter(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span> todo.completed);
<span class="hljs-keyword">const</span> getActiveTodos = <span class="hljs-function">(<span class="hljs-params">todos</span>) =&gt;</span> todos.filter(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span> !todo.completed);
</code></pre>
<h3 id="heading-memoization-for-efficient-selector-usage">Memoization for Efficient Selector Usage</h3>
<p>Memoization is a technique used to optimize expensive computations by caching the results of function calls based on their input. In the context of Redux selectors, memoization can improve performance by ensuring that selectors only recalculate their results when their input (state) changes.</p>
<p>You can use libraries like <code>reselect</code> for memoization in Redux selectors:</p>
<pre><code class="lang-bash">npm install reselect
</code></pre>
<p>Example usage of <code>reselect</code> for memoization:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createSelector } <span class="hljs-keyword">from</span> <span class="hljs-string">'reselect'</span>;

<span class="hljs-comment">// Selectors</span>
<span class="hljs-keyword">const</span> getTodos = <span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> state.todos;
<span class="hljs-keyword">const</span> getVisibilityFilter = <span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> state.visibilityFilter;

<span class="hljs-comment">// Memoized selector to get visible todos</span>
<span class="hljs-keyword">const</span> getVisibleTodos = createSelector(
  [getTodos, getVisibilityFilter],
  <span class="hljs-function">(<span class="hljs-params">todos, visibilityFilter</span>) =&gt;</span> {
    <span class="hljs-keyword">switch</span> (visibilityFilter) {
      <span class="hljs-keyword">case</span> <span class="hljs-string">'SHOW_COMPLETED'</span>:
        <span class="hljs-keyword">return</span> todos.filter(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span> todo.completed);
      <span class="hljs-keyword">case</span> <span class="hljs-string">'SHOW_ACTIVE'</span>:
        <span class="hljs-keyword">return</span> todos.filter(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span> !todo.completed);
      <span class="hljs-keyword">case</span> <span class="hljs-string">'SHOW_ALL'</span>:
      <span class="hljs-keyword">default</span>:
        <span class="hljs-keyword">return</span> todos;
    }
  }
);
</code></pre>
<p>In this example:</p>
<ul>
<li><code>createSelector</code> from <code>reselect</code> creates a memoized selector that takes <code>getTodos</code> and <code>getVisibilityFilter</code> as input selectors.</li>
<li>The selector function computes the filtered todos based on the <code>visibilityFilter</code> and caches the result until the input selectors change.</li>
</ul>
<h2 id="heading-how-to-connect-react-components-to-redux">How to Connect React Components to Redux</h2>
<p>Connecting React components to Redux is a fundamental technique for managing application state efficiently within React-based projects. Redux serves as a centralized store that holds the entire state of your application, making it accessible to any component that needs it.</p>
<h3 id="heading-the-connect-function-from-react-redux-library">The <code>connect</code> Function from react-redux Library</h3>
<p>In React applications using Redux for state management, the <code>connect</code> function from the <code>react-redux</code> library is used to connect React components to the Redux store. It provides a way to inject Redux state and action dispatching functions (dispatchers) into your components.</p>
<p>Here’s how you use <code>connect</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-keyword">import</span> { connect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>;

<span class="hljs-comment">// Define a React component</span>
<span class="hljs-keyword">const</span> Counter = <span class="hljs-function">(<span class="hljs-params">{ count, increment, decrement }</span>) =&gt;</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">p</span>&gt;</span>Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{increment}</span>&gt;</span>Increment<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">{decrement}</span>&gt;</span>Decrement<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-comment">// Map Redux state to component props</span>
<span class="hljs-keyword">const</span> mapStateToProps = <span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> ({
  <span class="hljs-attr">count</span>: state.count
});

<span class="hljs-comment">// Map dispatching actions to component props</span>
<span class="hljs-keyword">const</span> mapDispatchToProps = {
  <span class="hljs-attr">increment</span>: <span class="hljs-function">() =&gt;</span> ({ <span class="hljs-attr">type</span>: <span class="hljs-string">'INCREMENT'</span> }),
  <span class="hljs-attr">decrement</span>: <span class="hljs-function">() =&gt;</span> ({ <span class="hljs-attr">type</span>: <span class="hljs-string">'DECREMENT'</span> })
};

<span class="hljs-comment">// Connect component to Redux store</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> connect(mapStateToProps, mapDispatchToProps)(Counter);
</code></pre>
<h3 id="heading-mapping-state-and-dispatch-to-props">Mapping State and Dispatch to Props</h3>
<p><strong><code>mapStateToProps</code></strong>: This function maps the Redux store's state to the props of your React component. It takes the Redux state as an argument and returns an object. Each field in the returned object will become a prop for the connected component.</p>
<p><strong><code>mapDispatchToProps</code></strong>: This function maps dispatching actions to props of your React component. It can be an object where each field is an action creator function, or a function that receives <code>dispatch</code> as an argument and returns an object. Each action creator will be wrapped automatically with <code>dispatch</code> so they can be called directly.</p>
<p>In the example:</p>
<ul>
<li><code>mapStateToProps</code> maps the <code>count</code> field from the Redux state (<code>state.count</code>) to the <code>count</code> prop of the <code>Counter</code> component.</li>
<li><code>mapDispatchToProps</code> maps the <code>increment</code> and <code>decrement</code> actions to props, so clicking the buttons in the <code>Counter</code> component will dispatch the corresponding actions (<code>{ type: 'INCREMENT' }</code> and <code>{ type: 'DECREMENT' }</code>).</li>
</ul>
<h3 id="heading-using-connected-components-in-your-application">Using Connected Components in Your Application</h3>
<p>Once a component is connected to the Redux store using <code>connect</code>, it can access Redux state and dispatch actions via props. Here’s how you can use connected components in your application:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>;
<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>;
<span class="hljs-keyword">import</span> { createStore } <span class="hljs-keyword">from</span> <span class="hljs-string">'redux'</span>;
<span class="hljs-keyword">import</span> rootReducer <span class="hljs-keyword">from</span> <span class="hljs-string">'./reducers'</span>; <span class="hljs-comment">// Import your root reducer</span>
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App'</span>; <span class="hljs-comment">// Import your connected component</span>

<span class="hljs-comment">// Create Redux store with root reducer</span>
<span class="hljs-keyword">const</span> store = createStore(rootReducer);

<span class="hljs-comment">// Render the App component inside the Provider</span>
ReactDOM.render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>,
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>)
);
</code></pre>
<p>In this setup:</p>
<ul>
<li><code>Provider</code> is a component from <code>react-redux</code> that makes the Redux store available to any nested components that have been connected using <code>connect</code>.</li>
<li><code>store</code> is created using <code>createStore</code> and combined with a root reducer (<code>rootReducer</code>) that combines all your reducers into one.</li>
</ul>
<p>By wrapping your top-level component (<code>App</code> in this case) with <code>Provider</code> and passing the Redux store as a prop, all connected components within your application can access the Redux store and interact with it through props (<code>mapStateToProps</code> and <code>mapDispatchToProps</code> mappings).</p>
<h2 id="heading-advanced-redux-data-flow-techniques">Advanced Redux Data Flow Techniques</h2>
<p>Advanced Redux data flow techniques expand upon the fundamental principles of managing state in complex applications. These techniques go beyond basic actions and reducers, introducing concepts such as middleware, selectors, and asynchronous actions.</p>
<h3 id="heading-asynchronous-actions-redux-thunk-redux-saga">Asynchronous Actions (Redux Thunk, Redux Saga)</h3>
<p>In Redux, handling asynchronous actions involves managing actions that have side effects, such as fetching data from a server or updating state asynchronously. Redux provides several middleware solutions to handle asynchronous actions effectively.</p>
<h4 id="heading-redux-thunk">Redux Thunk</h4>
<p>Redux Thunk is a middleware that allows you to write action creators that return a function instead of an action object. This function can then perform asynchronous operations and dispatch regular synchronous actions when the asynchronous operations complete.</p>
<p>Example of using Redux Thunk for asynchronous actions:</p>
<p><strong>Setting up Redux Thunk Middleware</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createStore, applyMiddleware } <span class="hljs-keyword">from</span> <span class="hljs-string">'redux'</span>;
<span class="hljs-keyword">import</span> thunk <span class="hljs-keyword">from</span> <span class="hljs-string">'redux-thunk'</span>;
<span class="hljs-keyword">import</span> rootReducer <span class="hljs-keyword">from</span> <span class="hljs-string">'./reducers'</span>; <span class="hljs-comment">// Import your root reducer</span>

<span class="hljs-comment">// Create Redux store with thunk middleware</span>
<span class="hljs-keyword">const</span> store = createStore(rootReducer, applyMiddleware(thunk));
</code></pre>
<p><strong>Async Action Creator using Redux Thunk</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Action creator function using Redux Thunk</span>
<span class="hljs-keyword">const</span> fetchPosts = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">async</span> (dispatch) =&gt; {
    dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">'FETCH_POSTS_REQUEST'</span> });

    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/posts'</span>);
      <span class="hljs-keyword">const</span> posts = <span class="hljs-keyword">await</span> response.json();
      dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">'FETCH_POSTS_SUCCESS'</span>, <span class="hljs-attr">payload</span>: posts });
    } <span class="hljs-keyword">catch</span> (error) {
      dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">'FETCH_POSTS_FAILURE'</span>, <span class="hljs-attr">error</span>: error.message });
    }
  };
};
</code></pre>
<p>In this example:</p>
<ul>
<li><code>fetchPosts</code> is an action creator that returns a function instead of an action object.</li>
<li>Inside the function, you can perform asynchronous operations (like fetching data) and dispatch actions based on the result.</li>
<li>Redux Thunk middleware intercepts functions returned by action creators, enabling asynchronous actions in Redux.</li>
</ul>
<h4 id="heading-redux-saga">Redux Saga</h4>
<p>Redux Saga is another middleware for handling side effects in Redux applications. It uses ES6 generators to make asynchronous code easier to read, write, and test.</p>
<p>Example of using Redux Saga for handling asynchronous actions:</p>
<p><strong>Setting up Redux Saga Middleware</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createStore, applyMiddleware } <span class="hljs-keyword">from</span> <span class="hljs-string">'redux'</span>;
<span class="hljs-keyword">import</span> createSagaMiddleware <span class="hljs-keyword">from</span> <span class="hljs-string">'redux-saga'</span>;
<span class="hljs-keyword">import</span> rootReducer <span class="hljs-keyword">from</span> <span class="hljs-string">'./reducers'</span>; <span class="hljs-comment">// Import your root reducer</span>
<span class="hljs-keyword">import</span> rootSaga <span class="hljs-keyword">from</span> <span class="hljs-string">'./sagas'</span>; <span class="hljs-comment">// Import your root saga</span>

<span class="hljs-comment">// Create Redux Saga middleware</span>
<span class="hljs-keyword">const</span> sagaMiddleware = createSagaMiddleware();

<span class="hljs-comment">// Create Redux store with Saga middleware</span>
<span class="hljs-keyword">const</span> store = createStore(rootReducer, applyMiddleware(sagaMiddleware));

<span class="hljs-comment">// Run the root saga</span>
sagaMiddleware.run(rootSaga);
</code></pre>
<p><strong>Example Saga (rootSaga.js)</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { all, call, put, takeEvery } <span class="hljs-keyword">from</span> <span class="hljs-string">'redux-saga/effects'</span>;
<span class="hljs-keyword">import</span> { fetchPostsSuccess, fetchPostsFailure } <span class="hljs-keyword">from</span> <span class="hljs-string">'./actions'</span>; <span class="hljs-comment">// Import your action creators</span>

<span class="hljs-comment">// Worker saga for fetching posts</span>
<span class="hljs-function"><span class="hljs-keyword">function</span>* <span class="hljs-title">fetchPostsSaga</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">yield</span> call(fetch, <span class="hljs-string">'https://jsonplaceholder.typicode.com/posts'</span>);
    <span class="hljs-keyword">const</span> posts = <span class="hljs-keyword">yield</span> call([response, <span class="hljs-string">'json'</span>]);
    <span class="hljs-keyword">yield</span> put(fetchPostsSuccess(posts));
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-keyword">yield</span> put(fetchPostsFailure(error.message));
  }
}

<span class="hljs-comment">// Watcher saga to listen for FETCH_POSTS_REQUEST action</span>
<span class="hljs-function"><span class="hljs-keyword">function</span>* <span class="hljs-title">watchFetchPosts</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">yield</span> takeEvery(<span class="hljs-string">'FETCH_POSTS_REQUEST'</span>, fetchPostsSaga);
}

<span class="hljs-comment">// Root saga</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span>* <span class="hljs-title">rootSaga</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">yield</span> all([
    watchFetchPosts()
    <span class="hljs-comment">// Add more watchers if needed</span>
  ]);
}
</code></pre>
<p>In this example:</p>
<ul>
<li><code>fetchPostsSaga</code> is a worker saga that performs the asynchronous operation (fetching posts).</li>
<li><code>watchFetchPosts</code> is a watcher saga that listens for specific actions (<code>FETCH_POSTS_REQUEST</code>) and triggers the corresponding worker saga.</li>
<li><code>rootSaga</code> combines multiple sagas using <code>all</code> and runs them using <code>sagaMiddleware.run</code>.</li>
</ul>
<h3 id="heading-middleware-for-extending-redux-functionality">Middleware for Extending Redux Functionality</h3>
<p>Middleware in Redux provides a way to extend the Redux store's capabilities, such as logging actions, handling asynchronous operations, routing, and more. Middleware sits between dispatching an action and the moment it reaches the reducer, allowing interception and manipulation of actions.</p>
<h4 id="heading-example-of-custom-middleware">Example of Custom Middleware:</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> loggerMiddleware = <span class="hljs-function"><span class="hljs-params">store</span> =&gt;</span> <span class="hljs-function"><span class="hljs-params">next</span> =&gt;</span> <span class="hljs-function"><span class="hljs-params">action</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Dispatching action:'</span>, action);
  <span class="hljs-keyword">const</span> result = next(action);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'New state:'</span>, store.getState());
  <span class="hljs-keyword">return</span> result;
};

<span class="hljs-comment">// Applying custom middleware to Redux store</span>
<span class="hljs-keyword">import</span> { createStore, applyMiddleware } <span class="hljs-keyword">from</span> <span class="hljs-string">'redux'</span>;
<span class="hljs-keyword">import</span> rootReducer <span class="hljs-keyword">from</span> <span class="hljs-string">'./reducers'</span>; <span class="hljs-comment">// Import your root reducer</span>

<span class="hljs-comment">// Create Redux store with custom middleware</span>
<span class="hljs-keyword">const</span> store = createStore(rootReducer, applyMiddleware(loggerMiddleware));
</code></pre>
<p>In this example:</p>
<ul>
<li><code>loggerMiddleware</code> is a custom middleware function that logs each dispatched action and the resulting state.</li>
<li><code>next</code> is a function provided by Redux that allows the action to continue to the next middleware or the reducer.</li>
<li>Custom middleware enhances Redux functionality by intercepting actions, performing custom logic, and optionally dispatching new actions or modifying existing ones.</li>
</ul>
<h2 id="heading-best-practices-for-managing-data-flow-in-redux">Best Practices for Managing Data Flow in Redux</h2>
<p>Redux provides a structured way to manage state in JavaScript applications, but effective usage requires adhering to best practices. Here are my key recommendations for managing data flow in Redux:</p>
<h3 id="heading-organizing-reducers-and-actions">Organizing Reducers and Actions</h3>
<p><strong>File Structure and Organization</strong>:</p>
<ul>
<li><strong>Separate concerns</strong>: Keep actions, reducers, and selectors in separate files to maintain clarity and modularity.</li>
<li><strong>Feature-based structure</strong>: Group related actions and reducers together based on features rather than types.</li>
</ul>
<pre><code class="lang-plaintext">src/
├── actions/
│   ├── todosActions.js
│   └── userActions.js
├── reducers/
│   ├── todosReducer.js
│   └── userReducer.js
├── selectors/
│   ├── todosSelectors.js
│   └── userSelectors.js
└── store.js
</code></pre>
<p><strong>Action Types</strong>:</p>
<ul>
<li><strong>Constants</strong>: Use constants or enums for action types to prevent typos and ensure consistency.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// Action types</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> ADD_TODO = <span class="hljs-string">'ADD_TODO'</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> DELETE_TODO = <span class="hljs-string">'DELETE_TODO'</span>;
</code></pre>
<p><strong>Reducer Composition</strong>:</p>
<ul>
<li><strong>Combine reducers</strong>: Use <code>combineReducers</code> from Redux to combine multiple reducers into a single root reducer.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { combineReducers } <span class="hljs-keyword">from</span> <span class="hljs-string">'redux'</span>;
<span class="hljs-keyword">import</span> todosReducer <span class="hljs-keyword">from</span> <span class="hljs-string">'./todosReducer'</span>;
<span class="hljs-keyword">import</span> userReducer <span class="hljs-keyword">from</span> <span class="hljs-string">'./userReducer'</span>;

<span class="hljs-keyword">const</span> rootReducer = combineReducers({
  <span class="hljs-attr">todos</span>: todosReducer,
  <span class="hljs-attr">user</span>: userReducer
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> rootReducer;
</code></pre>
<h3 id="heading-immutable-state-updates">Immutable State Updates</h3>
<p><strong>Immutability with Spread Operator</strong>:</p>
<ul>
<li><strong>Use spread operator (<code>...</code>)</strong>: Create new objects or arrays when updating state to maintain immutability.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// Updating an array in Redux state</span>
<span class="hljs-keyword">const</span> todosReducer = <span class="hljs-function">(<span class="hljs-params">state = initialState, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> ADD_TODO:
      <span class="hljs-keyword">return</span> {
        ...state,
        <span class="hljs-attr">todos</span>: [
          ...state.todos,
          {
            <span class="hljs-attr">id</span>: action.id,
            <span class="hljs-attr">text</span>: action.text,
            <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
          }
        ]
      };
    <span class="hljs-keyword">case</span> TOGGLE_TODO:
      <span class="hljs-keyword">return</span> {
        ...state,
        <span class="hljs-attr">todos</span>: state.todos.map(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span>
          (todo.id === action.id) ? { ...todo, <span class="hljs-attr">completed</span>: !todo.completed } : todo
        )
      };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
};
</code></pre>
<p><strong>Immutable Libraries</strong>:</p>
<ul>
<li><strong>Immutable.js</strong>: Consider using libraries like Immutable.js for more complex data structures to enforce immutability and optimize performance.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { <span class="hljs-built_in">Map</span>, List } <span class="hljs-keyword">from</span> <span class="hljs-string">'immutable'</span>;

<span class="hljs-keyword">const</span> initialState = <span class="hljs-built_in">Map</span>({
  <span class="hljs-attr">todos</span>: List(),
  <span class="hljs-attr">user</span>: <span class="hljs-built_in">Map</span>()
});

<span class="hljs-keyword">const</span> todosReducer = <span class="hljs-function">(<span class="hljs-params">state = initialState, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> ADD_TODO:
      <span class="hljs-keyword">return</span> state.update(<span class="hljs-string">'todos'</span>, <span class="hljs-function"><span class="hljs-params">todos</span> =&gt;</span> todos.push(<span class="hljs-built_in">Map</span>({
        <span class="hljs-attr">id</span>: action.id,
        <span class="hljs-attr">text</span>: action.text,
        <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span>
      })));

    <span class="hljs-keyword">case</span> TOGGLE_TODO:
      <span class="hljs-keyword">return</span> state.update(<span class="hljs-string">'todos'</span>, <span class="hljs-function"><span class="hljs-params">todos</span> =&gt;</span>
        todos.map(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span>
          (todo.get(<span class="hljs-string">'id'</span>) === action.id) ? todo.set(<span class="hljs-string">'completed'</span>, !todo.get(<span class="hljs-string">'completed'</span>)) : todo
        )
      );

    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
};
</code></pre>
<h3 id="heading-testing-redux-applications">Testing Redux Applications</h3>
<p><strong>Unit Testing</strong>:</p>
<ul>
<li><strong>Reducers</strong>: Test reducers to ensure they handle actions correctly and return the expected state.</li>
</ul>
<pre><code class="lang-javascript">describe(<span class="hljs-string">'todosReducer'</span>, <span class="hljs-function">() =&gt;</span> {
  it(<span class="hljs-string">'should handle ADD_TODO'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> action = { <span class="hljs-attr">type</span>: <span class="hljs-string">'ADD_TODO'</span>, <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">text</span>: <span class="hljs-string">'Test todo'</span> };
    <span class="hljs-keyword">const</span> initialState = { <span class="hljs-attr">todos</span>: [] };
    <span class="hljs-keyword">const</span> expectedState = { <span class="hljs-attr">todos</span>: [{ <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">text</span>: <span class="hljs-string">'Test todo'</span>, <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span> }] };

    expect(todosReducer(initialState, action)).toEqual(expectedState);
  });
});
</code></pre>
<p><strong>Integration Testing</strong>:</p>
<ul>
<li><strong>Action Creators and Thunks</strong>: Test action creators and thunks to verify they dispatch the correct actions or handle asynchronous operations.</li>
</ul>
<pre><code class="lang-javascript">describe(<span class="hljs-string">'fetchPosts action creator'</span>, <span class="hljs-function">() =&gt;</span> {
  it(<span class="hljs-string">'creates FETCH_POSTS_SUCCESS when fetching posts has been done'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> expectedActions = [
      { <span class="hljs-attr">type</span>: <span class="hljs-string">'FETCH_POSTS_REQUEST'</span> },
      { <span class="hljs-attr">type</span>: <span class="hljs-string">'FETCH_POSTS_SUCCESS'</span>, <span class="hljs-attr">payload</span>: { <span class="hljs-comment">/* mocked data */</span> } }
    ];

    <span class="hljs-keyword">const</span> store = mockStore({ <span class="hljs-attr">posts</span>: [] });

    <span class="hljs-keyword">return</span> store.dispatch(fetchPosts()).then(<span class="hljs-function">() =&gt;</span> {
      expect(store.getActions()).toEqual(expectedActions);
    });
  });
});
</code></pre>
<p><strong>Integration with Components</strong>:</p>
<ul>
<li><strong>Connected Components</strong>: Test connected components using <code>redux-mock-store</code> to simulate Redux store behavior.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> configureStore <span class="hljs-keyword">from</span> <span class="hljs-string">'redux-mock-store'</span>;
<span class="hljs-keyword">import</span> { Provider } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-redux'</span>;
<span class="hljs-keyword">import</span> { render } <span class="hljs-keyword">from</span> <span class="hljs-string">'@testing-library/react'</span>;
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App'</span>;

<span class="hljs-keyword">const</span> mockStore = configureStore([]);

describe(<span class="hljs-string">'&lt;App /&gt;'</span>, <span class="hljs-function">() =&gt;</span> {
  it(<span class="hljs-string">'renders App component'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> store = mockStore({ <span class="hljs-comment">/* mocked state */</span> });

    <span class="hljs-keyword">const</span> { getByText } = render(
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">{store}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>
    );

    expect(getByText(<span class="hljs-string">'Welcome to Redux App'</span>)).toBeInTheDocument();
  });
});
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Redux offers a powerful state management solution for JavaScript applications, providing a predictable and centralized way to manage application state. </p>
<p>Whether handling asynchronous operations with middleware like Redux Thunk or Redux Saga, or optimizing state management through immutable data practices, Redux empowers you to build scalable and maintainable applications. </p>
<p>By mastering these techniques, you can leverage Redux to streamline data flow, enhance application performance, and simplify the complexities of managing state in modern web development.</p>
<p>That's all for this article! If you'd like to continue the conversation or have questions, suggestions, or feedback, feel free to reach out to connect with me on <a target="_blank" href="https://ng.linkedin.com/in/joan-ayebola">LinkedIn</a>. And if you enjoyed this content, consider <a target="_blank" href="https://www.buymeacoffee.com/joanayebola">buying me a coffee</a> to support the creation of more developer-friendly contents.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Breakpoints for Responsive Web Design ]]>
                </title>
                <description>
                    <![CDATA[ Breakpoints are fundamental to the concept of responsive web design. They enable websites to adapt seamlessly across different devices and screen sizes.  Breakpoints mark the points at which a website's layout and content should change to ensure opti... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/breakpoints-for-responsive-web-design/</link>
                <guid isPermaLink="false">66c4c3b8e486f65d4125b7f9</guid>
                
                    <category>
                        <![CDATA[ responsive design ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Design ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Mon, 24 Jun 2024 18:03:30 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/Ivory-and-Blue-Lavender-Aesthetic-Photo-Collage-Presentation--13-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Breakpoints are fundamental to the concept of responsive web design. They enable websites to adapt seamlessly across different devices and screen sizes. </p>
<p>Breakpoints mark the points at which a website's layout and content should change to ensure optimal user experience on devices ranging from smartphones and tablets to desktop computers. </p>
<p>It's really important for today's web designers to know how breakpoints work and use them smartly. This helps them create websites that work well on all kinds of devices and are easy for people to use.</p>
<p>In this article, we'll explore breakpoints in detail: why they matter, how to use them effectively, and their role in making websites adjust smoothly to different screen sizes.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-responsive-web-design-rwd">What is Responsive Web Design?</a></li>
<li><a class="post-section-overview" href="#heading-why-are-breakpoints-important-in-rwd">Why are Breakpoints Important in RWD?</a></li>
<li><a class="post-section-overview" href="#heading-common-breakpoint-ranges-for-responsive-design-2024">Common Breakpoint Ranges for Responsive Design (2024)</a></li>
<li><a class="post-section-overview" href="#heading-factors-to-consider-when-choosing-the-right-breakpoints-for-your-project">Factors to Consider When Choosing the Right Breakpoints for Your Project</a></li>
<li><a class="post-section-overview" href="#heading-basic-structure-of-a-media-query">Basic Structure of a Media Query</a></li>
<li><a class="post-section-overview" href="#heading-advanced-breakpoint-techniques">Advanced Breakpoint Techniques</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-is-responsive-web-design-rwd">What is Responsive Web Design (RWD)?</h2>
<p>Responsive Web Design (RWD) is an approach to web design that ensures web pages render well on a variety of devices and window or screen sizes. </p>
<p>It involves using fluid grids, flexible images, and CSS media queries to automatically adapt the layout and content of a website to the device's screen size and orientation. </p>
<p>The goal of responsive web design is to provide an optimal viewing and interaction experience, ensuring easy reading and navigation with minimal resizing, panning, and scrolling across a wide range of devices, from desktop computers to mobile phones.</p>
<h2 id="heading-why-are-breakpoints-important-in-rwd">Why are Breakpoints Important in RWD?</h2>
<p>Breakpoints are important in Responsive Web Design (RWD) because they define specific points where a website's layout and content should adapt to different screen sizes and devices. </p>
<p>Here’s why they are crucial:</p>
<h3 id="heading-device-compatibility">Device Compatibility</h3>
<p>Breakpoints enable websites to adjust their design and layout to ensure compatibility with various devices like smartphones, tablets, laptops, and desktops. This adaptability ensures that users have a consistent and optimized experience regardless of the device they use.</p>
<h3 id="heading-optimal-user-experience">Optimal User Experience</h3>
<p>Designers can use breakpoints to tailor the presentation of content, navigation, and functionality based on screen size. This customization enhances user experience by ensuring content is readable, accessible, and easy to interact with across devices.</p>
<h3 id="heading-fluidity-in-design">Fluidity in Design</h3>
<p>Instead of creating fixed-width designs that may not scale well, breakpoints allow for fluid grids and flexible elements. This approach ensures that the design remains visually appealing and functional, regardless of the screen dimensions.</p>
<h3 id="heading-content-prioritization">Content Prioritization</h3>
<p>With breakpoints, designers can prioritize and reorganize content based on device capabilities and user needs. This ensures that essential information remains accessible and prominent, enhancing usability and engagement.</p>
<h3 id="heading-performance-optimization">Performance Optimization</h3>
<p>Breakpoints make websites load faster and work better on different devices by adjusting how they look and work based on each device's size and type. This is crucial for retaining user interest and reducing bounce rates, particularly on mobile devices with slower internet connections.</p>
<h3 id="heading-seo-friendliness">SEO Friendliness</h3>
<p>Responsive websites with well-implemented breakpoints provide a seamless user experience across devices. Search engines value responsive design because it improves accessibility and usability, potentially leading to better search engine rankings.</p>
<h2 id="heading-common-breakpoint-ranges-for-responsive-design-2024">Common Breakpoint Ranges for Responsive Design (2024)</h2>
<p>In 2024, responsive web design commonly employs a mobile-first approach, ensuring websites are designed to function and look good on smaller screens before scaling up. </p>
<p>Here are the typical breakpoint ranges used for different screen sizes:</p>
<p><strong>Extra Small Screens (Mobile):</strong></p>
<ul>
<li>Range: Up to 576px viewport width</li>
<li>Description: Targets smartphones and small mobile devices in portrait mode.</li>
</ul>
<p><strong>Small Screens (Tablets):</strong></p>
<ul>
<li>Range: 577px to 768px viewport width</li>
<li>Description: Includes larger smartphones and smaller tablets in portrait mode.</li>
</ul>
<p><strong>Medium Screens (Large Tablets):</strong></p>
<ul>
<li>Range: 769px to 1024px viewport width</li>
<li>Description: Targets larger tablets and smaller desktop screens in landscape mode.</li>
</ul>
<p><strong>Large Screens (Desktops):</strong></p>
<ul>
<li>Range: 1025px to 1440px viewport width</li>
<li>Description: Targets standard desktop screens and larger laptops.</li>
</ul>
<p><strong>Extra Large Screens (Large Desktops):</strong></p>
<ul>
<li>Range: 1441px and above viewport width</li>
<li>Description: Includes large desktop monitors and wide-screen displays.</li>
</ul>
<h3 id="heading-example-css-media-queries">Example CSS Media Queries:</h3>
<pre><code class="lang-css"><span class="hljs-comment">/* Example of CSS media queries for common breakpoint ranges */</span>

<span class="hljs-comment">/* Extra Small Screens (Mobile) */</span>
<span class="hljs-keyword">@media</span> <span class="hljs-keyword">only</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">576px</span>) {
  <span class="hljs-comment">/* CSS rules specific for extra small screens */</span>
  <span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>; <span class="hljs-comment">/* Adjust layout for full-width on small screens */</span>
  }
}

<span class="hljs-comment">/* Small Screens (Tablets) */</span>
<span class="hljs-keyword">@media</span> <span class="hljs-keyword">only</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">577px</span>) <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">768px</span>) {
  <span class="hljs-comment">/* CSS rules specific for small screens */</span>
  <span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>; <span class="hljs-comment">/* Adjust layout for smaller container width on tablets */</span>
  }
}

<span class="hljs-comment">/* Medium Screens (Large Tablets) */</span>
<span class="hljs-keyword">@media</span> <span class="hljs-keyword">only</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">769px</span>) <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">1024px</span>) {
  <span class="hljs-comment">/* CSS rules specific for medium screens */</span>
  <span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">70%</span>; <span class="hljs-comment">/* Adjust layout for moderate container width on large tablets */</span>
  }
}

<span class="hljs-comment">/* Large Screens (Desktops) */</span>
<span class="hljs-keyword">@media</span> <span class="hljs-keyword">only</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">1025px</span>) <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">1440px</span>) {
  <span class="hljs-comment">/* CSS rules specific for large screens */</span>
  <span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">60%</span>; <span class="hljs-comment">/* Adjust layout for narrower container width on desktops */</span>
  }
}

<span class="hljs-comment">/* Extra Large Screens (Large Desktops) */</span>
<span class="hljs-keyword">@media</span> <span class="hljs-keyword">only</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">1441px</span>) {
  <span class="hljs-comment">/* CSS rules specific for extra large screens */</span>
  <span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">50%</span>; <span class="hljs-comment">/* Adjust layout for even narrower container width on large desktops */</span>
  }
}
</code></pre>
<p>In this example:</p>
<ul>
<li>Each media query targets a specific range of viewport widths to adjust the layout and styling of the <code>.container</code> element accordingly.</li>
<li>The percentages used for <code>width</code> in the examples demonstrate how designers can progressively adjust content presentation to optimize user experience across various devices and screen sizes.</li>
</ul>
<h2 id="heading-factors-to-consider-when-choosing-the-right-breakpoints-for-your-project">Factors to Consider When Choosing the Right Breakpoints for Your Project</h2>
<p>Choosing the right breakpoints for your project involves considering several factors:</p>
<h3 id="heading-target-audience-and-devices">Target Audience and Devices</h3>
<p>Understand the devices your target audience uses. This includes screen sizes of smartphones, tablets, laptops, and desktops. Prioritize breakpoints that align with these devices to ensure a seamless user experience.</p>
<h3 id="heading-content-complexity">Content Complexity</h3>
<p>Evaluate how your content responds to different screen sizes. Complex layouts may require additional breakpoints to maintain readability and usability across devices.</p>
<h3 id="heading-design-requirements">Design Requirements</h3>
<p>Your design specifications play an important role. Consider breakpoints that accommodate specific design elements such as navigation menus, images, forms, and grids. Ensure that these elements adapt well to different screen sizes.</p>
<h3 id="heading-analyzing-device-usage-statistics">Analyzing Device Usage Statistics</h3>
<p>Use analytics to determine the most common screen sizes among your audience. Focus on breakpoints that optimize user experience on these prevalent devices.</p>
<h2 id="heading-basic-structure-of-a-media-query">Basic Structure of a Media Query</h2>
<p>Implementing breakpoints with media queries is essential for creating responsive web designs that adapt to different screen sizes and devices. </p>
<p>A media query allows you to apply CSS styles based on certain conditions, such as screen width, height, device orientation, etc. The basic syntax of a media query is:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@media</span> media-type <span class="hljs-keyword">and</span> (media-feature) {
  <span class="hljs-comment">/* CSS styles */</span>
}
</code></pre>
<p>Where:</p>
<ul>
<li><code>media-type</code> specifies the type of media, typically <code>screen</code> for devices with screens.</li>
<li><code>media-feature</code> defines the condition, such as <code>width</code>, <code>min-width</code>, <code>max-width</code>, <code>orientation</code>, and so on.</li>
</ul>
<p>Now let's talk about how you can structure and use media queries effectively.</p>
<h3 id="heading-using-min-width-and-max-width-for-breakpoints">Using min-width and max-width for Breakpoints</h3>
<p>The most common approach to defining breakpoints is using <code>min-width</code> and <code>max-width</code> media features.</p>
<p><strong><code>min-width</code></strong>: Specifies the minimum width at which the styles should apply. It targets screens wider than the specified width.</p>
<p>Example:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">768px</span>) {
  <span class="hljs-comment">/* Styles for screens wider than 768px */</span>
}
</code></pre>
<p><strong><code>max-width</code></strong>: Specifies the maximum width at which the styles should apply. It targets screens narrower than the specified width.</p>
<p>Example:</p>
<pre><code class="lang-css"><span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">1024px</span>) {
  <span class="hljs-comment">/* Styles for screens narrower than or equal to 1024px */</span>
}
</code></pre>
<h3 id="heading-media-queries-for-different-breakpoint-ranges">Media Queries for Different Breakpoint Ranges</h3>
<p>To create a responsive design that adapts to various devices, you typically define multiple breakpoints to cover different screen sizes:</p>
<h4 id="heading-small-screens-mobile-phones">Small Screens (Mobile Phones):</h4>
<pre><code class="lang-css"><span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">576px</span>) {
  <span class="hljs-comment">/* Styles for small screens */</span>
}
</code></pre>
<h4 id="heading-medium-screens-tablets">Medium Screens (Tablets):</h4>
<pre><code class="lang-css"><span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">577px</span>) <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">992px</span>) {
  <span class="hljs-comment">/* Styles for medium screens */</span>
}
</code></pre>
<h4 id="heading-large-screens-desktops-and-laptops">Large Screens (Desktops and Laptops):</h4>
<pre><code class="lang-css"><span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">993px</span>) {
  <span class="hljs-comment">/* Styles for large screens */</span>
}
</code></pre>
<h4 id="heading-extra-large-screens-large-desktops-and-monitors">Extra Large Screens (Large Desktops and Monitors):</h4>
<pre><code class="lang-css"><span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">1200px</span>) {
  <span class="hljs-comment">/* Styles for extra large screens */</span>
}
</code></pre>
<h3 id="heading-example-comprehensive-media-queries">Example: Comprehensive Media Queries</h3>
<p>Here’s an example of how you might implement media queries for a responsive layout:</p>
<pre><code class="lang-css"><span class="hljs-comment">/* Default styles for all screens */</span>
<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
}

<span class="hljs-comment">/* Small screens (phones) */</span>
<span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">576px</span>) {
  <span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">14px</span>;
  }
}

<span class="hljs-comment">/* Medium screens (tablets) */</span>
<span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">577px</span>) <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">992px</span>) {
  <span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>;
  }
}

<span class="hljs-comment">/* Large screens (desktops and laptops) */</span>
<span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">993px</span>) {
  <span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">18px</span>;
  }
}

<span class="hljs-comment">/* Extra large screens (large desktops and monitors) */</span>
<span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">1200px</span>) {
  <span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">20px</span>;
  }
}
</code></pre>
<p>In this example:</p>
<ul>
<li>Font sizes adjust based on the screen size to ensure readability and optimal user experience.</li>
<li>Each media query targets specific ranges of screen widths using <code>min-width</code> and <code>max-width</code>.</li>
<li>Adjustments in font size are used here for demonstration purposes, but you can apply any CSS styles needed for your design.</li>
</ul>
<h2 id="heading-advanced-breakpoint-techniques">Advanced Breakpoint Techniques</h2>
<p>Implementing advanced breakpoint techniques enhances the responsiveness and adaptability of your web designs. </p>
<p>Here are several techniques you can use:</p>
<h3 id="heading-1-container-queries-adapting-to-content-width">1. Container Queries (Adapting to Content Width)</h3>
<p><strong>Container queries</strong> allow elements to respond not to the viewport size but to their own container's dimensions. This is particularly useful when you want elements to adapt based on their parent container's width rather than the overall screen width.</p>
<p>Example using a hypothetical container query syntax (not currently natively supported, but evolving in standards like CSS Houdini):</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
  <span class="hljs-comment">/* Apply styles based on container width */</span>
}

<span class="hljs-keyword">@container</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">600px</span>) {
  <span class="hljs-selector-class">.container</span> {
    <span class="hljs-comment">/* Adjust styles for containers wider than 600px */</span>
  }
}
</code></pre>
<p>Container queries are highly anticipated as they provide more granular control over responsive design within individual components or sections.</p>
<h3 id="heading-2-flexible-units-ems-rems-for-responsive-layouts">2. Flexible Units (ems, rems) for Responsive Layouts</h3>
<p><strong>Flexible units</strong> like <code>em</code> (relative to the font-size of the element) and <code>rem</code> (relative to the font-size of the root element) are essential for creating scalable and responsive layouts.</p>
<h4 id="heading-using-em-and-rem">Using em and rem:</h4>
<ul>
<li><code>em</code> units scale relative to their parent element's font size. This can be useful for creating modular designs where elements resize proportionally.</li>
<li><code>rem</code> units are relative to the root element (<code>html</code>), providing a consistent base for scaling across the entire document.</li>
</ul>
<pre><code class="lang-css"><span class="hljs-comment">/* Example using rem for scalable font sizes */</span>
<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">16px</span>; <span class="hljs-comment">/* Base font size */</span>
}

<span class="hljs-selector-tag">h1</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">2rem</span>; <span class="hljs-comment">/* 32px on 16px base */</span>
}

<span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.5rem</span>; <span class="hljs-comment">/* 24px on 16px base */</span>
}

<span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">768px</span>) {
  <span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">14px</span>; <span class="hljs-comment">/* Adjust base font size for smaller screens */</span>
  }
}
</code></pre>
<h3 id="heading-3-using-css-grid-and-flexbox-for-responsive-design">3. Using CSS Grid and Flexbox for Responsive Design</h3>
<p><strong>CSS Grid</strong> and <strong>Flexbox</strong> are powerful layout tools that offer flexible and responsive design options.</p>
<p><strong>CSS Grid</strong>: Ideal for two-dimensional layouts, allowing precise control over rows and columns. Grids can adapt to different screen sizes with media queries or grid-auto-flow properties.</p>
<p>Example of responsive grid layout:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</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">250px</span>, <span class="hljs-number">1</span>fr));
  <span class="hljs-attribute">grid-gap</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">768px</span>) {
  <span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-number">1</span>fr;
  }
}
</code></pre>
<p><strong>Flexbox</strong>: Best for simpler one-dimensional layouts or aligning items within a container. It’s great for navigation bars, sidebars, and elements within a grid cell.</p>
<p>Example of responsive Flexbox layout:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: space-between;
}

<span class="hljs-keyword">@media</span> screen <span class="hljs-keyword">and</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">768px</span>) {
  <span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">flex-direction</span>: column;
  }
}
</code></pre>
<ul>
<li><strong>Container Queries</strong> are evolving and promise more precise control over responsive design elements based on their container's size.</li>
<li><strong>Flexible Units</strong> (<code>em</code>, <code>rem</code>) allow scalable and accessible typography and layout proportions across various screen sizes.</li>
<li><strong>CSS Grid</strong> and <strong>Flexbox</strong> provide robust layout options for creating responsive designs that adapt to different devices and viewport sizes.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, breakpoints play a pivotal role in crafting a responsive web design that adapts seamlessly across different devices and screen sizes. </p>
<p>The flexibility offered by media queries, utilizing <code>min-width</code> and <code>max-width</code> to define breakpoints, allows for precise control over how content and layouts respond to varying viewport dimensions. </p>
<p>Advanced techniques like container queries (as they evolve), flexible units (<code>em</code>, <code>rem</code>), and leveraging CSS Grid and Flexbox further enhance the adaptability and scalability of designs.</p>
<p>In essence, breakpoints are not just technical specifications but critical decisions that impact user interaction and satisfaction. </p>
<p>Connect with me on <a target="_blank" href="https://www.linkedin.com/in/joanayebola">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are Controlled and Uncontrolled Components in React.js? ]]>
                </title>
                <description>
                    <![CDATA[ In React.js, managing form inputs and user interactions is a crucial part of building dynamic web applications.  Two key concepts that developers need to understand are controlled and uncontrolled components. These concepts define how form data is ha... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-controlled-and-uncontrolled-components-in-react/</link>
                <guid isPermaLink="false">66c4c41fbd556981b1bdc443</guid>
                
                    <category>
                        <![CDATA[ components ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Fri, 21 Jun 2024 20:18:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/Ivory-and-Blue-Lavender-Aesthetic-Photo-Collage-Presentation--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In React.js, managing form inputs and user interactions is a crucial part of building dynamic web applications. </p>
<p>Two key concepts that developers need to understand are controlled and uncontrolled components. These concepts define how form data is handled within a React component. </p>
<p>Controlled components rely on React state to manage the form data, while uncontrolled components use the DOM itself to handle form data. </p>
<p>In this article, we will explore the differences between controlled and uncontrolled components, how to implement them, and some best practices for using each approach in your React applications.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-are-controlled-components">What are Controlled Components</a>?</li>
<li><a class="post-section-overview" href="#heading-how-controlled-components-work">How Controlled Components Work</a> </li>
<li><a class="post-section-overview" href="#heading-benefits-of-using-controlled-components">Benefits of using Controlled Components</a></li>
<li><a class="post-section-overview" href="#heading-examples-of-controlled-components">Examples of Controlled Components</a></li>
<li><a class="post-section-overview" href="#heading-what-are-uncontrolled-components">What are Uncontrolled Components</a>?</li>
<li><a class="post-section-overview" href="#heading-how-uncontrolled-components-work">How Uncontrolled Components Work</a></li>
<li><a class="post-section-overview" href="#heading-when-to-use-uncontrolled-components">When to use Uncontrolled Components</a></li>
<li><a class="post-section-overview" href="#heading-limitations-of-uncontrolled-components">Limitations to Uncontrolled Components</a></li>
<li><a class="post-section-overview" href="#heading-examples-of-uncontrolled-components">Examples of Uncontrolled Components</a></li>
<li><a class="post-section-overview" href="#heading-factors-to-consider-when-choosing-between-controlled-and-uncontrolled-components">Factors to Consider When Choosing Between Controlled and Uncontrolled Components</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-are-controlled-components">What are Controlled Components?</h2>
<p>Controlled components are form elements (like <code>input</code>, <code>textarea</code>, or <code>select</code>) that are managed by React state. This means that the value of the form element is set and updated through React state, making React the "single source of truth" for the form data. </p>
<p>By controlling form elements via state, you gain more control over user interactions and can easily enforce validation, format data, and respond to changes.</p>
<p>Here's an example of a controlled component:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { 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">ControlledComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [value, setValue] = useState(<span class="hljs-string">''</span>);

  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setValue(event.target.value);
  };

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    event.preventDefault();
    alert(<span class="hljs-string">'A name was submitted: '</span> + value);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>
        Name:
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ControlledComponent;
</code></pre>
<p>In this example:</p>
<ul>
<li>The <code>value</code> state holds the current value of the input field.</li>
<li>The <code>handleChange</code> function updates the state whenever the user types in the input field.</li>
<li>The <code>handleSubmit</code> function handles the form submission, using the current state value.</li>
</ul>
<h2 id="heading-how-controlled-components-work">How Controlled Components Work</h2>
<p>Controlled components in React ensure that the form data is handled by the React state, providing a consistent and predictable way to manage user input. </p>
<p>Here’s a breakdown of how these components work, including state management in the parent component, passing values as props to child components, handling user input with event handlers, and updating state in the parent component.</p>
<h3 id="heading-state-management-in-the-parent-component">State Management in the Parent Component</h3>
<p>State management is often handled in the parent component, especially when multiple child components need to interact or share state. The parent component maintains the state and passes it down to child components via props.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> ChildComponent <span class="hljs-keyword">from</span> <span class="hljs-string">'./ChildComponent'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [inputValue, setInputValue] = useState(<span class="hljs-string">''</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>Controlled Component Example<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{inputValue}</span> <span class="hljs-attr">setValue</span>=<span class="hljs-string">{setInputValue}</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> ParentComponent;
</code></pre>
<h3 id="heading-passing-values-as-props-to-a-child-component">Passing Values as Props to a Child Component</h3>
<p>The parent component passes the state value and a state updater function to the child component as props. This allows the child component to display the current state and update it when needed.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">{ value, setValue }</span>) </span>{
  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setValue(event.target.value);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>
        Name:
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ChildComponent;
</code></pre>
<h3 id="heading-handling-user-input-with-event-handlers">Handling User Input with Event Handlers</h3>
<p>Event handlers are used to manage user input. When the user types into the input field, the <code>onChange</code> event triggers the <code>handleChange</code> function, which updates the state in the parent component.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChildComponent</span>(<span class="hljs-params">{ value, setValue }</span>) </span>{
  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setValue(event.target.value);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>
        Name:
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}
</code></pre>
<h3 id="heading-updating-state-in-a-parent-component">Updating State in a Parent Component</h3>
<p>When the state updater function (<code>setValue</code>) is called in the child component, it updates the state in the parent component. This causes the parent component to re-render, which in turn re-renders the child component with the new state value.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [inputValue, setInputValue] = useState(<span class="hljs-string">''</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>Controlled Component Example<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{inputValue}</span> <span class="hljs-attr">setValue</span>=<span class="hljs-string">{setInputValue}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h3 id="heading-putting-it-all-together">Putting It All Together</h3>
<p>Here's the complete example showing how controlled components work with state management in the parent component:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// ParentComponent.jsx</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">import</span> ChildComponent <span class="hljs-keyword">from</span> <span class="hljs-string">'./ChildComponent'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ParentComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [inputValue, setInputValue] = useState(<span class="hljs-string">''</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>Controlled Component Example<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ChildComponent</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{inputValue}</span> <span class="hljs-attr">setValue</span>=<span class="hljs-string">{setInputValue}</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> ParentComponent;

<span class="hljs-comment">// ChildComponent.jsx</span>
<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">ChildComponent</span>(<span class="hljs-params">{ value, setValue }</span>) </span>{
  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setValue(event.target.value);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>
        Name:
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ChildComponent;
</code></pre>
<p>Controlled components in React provide a good way to manage form data by using React state as the single source of truth. This approach involves managing state in the parent component, passing values and state updater functions as props to child components, handling user input with event handlers, and updating state in the parent component. </p>
<p>This method ensures consistent and predictable form behavior, making it easier to implement validation, conditional rendering, and other interactive features.</p>
<h2 id="heading-benefits-of-using-controlled-components">Benefits of Using Controlled Components</h2>
<p>Controlled components offer several advantages that can significantly improve the development experience and functionality of React applications. Here are the key benefits:</p>
<h3 id="heading-predictable-state-management">Predictable State Management</h3>
<p>Using controlled components ensures that the form data is always in sync with the React state. This predictability comes from having a single source of truth for the data, which is the state itself. </p>
<p>Since the state drives the UI, any change in the state immediately reflects in the form elements and vice versa. This makes it easier to debug and understand how data flows through your application.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { 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">PredictableForm</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">''</span>);

  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setName(event.target.value);
  };

  <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">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{name}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Current value: {name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>In this example, the input field and the displayed text are always synchronized, providing a predictable behavior.</p>
<h3 id="heading-easier-form-validation">Easier Form Validation</h3>
<p>Controlled components make it straightforward to implement form validation. Since the form data is stored in the component state, you can easily validate it before updating the state or on form submission. This approach allows you to provide real-time feedback to users as they interact with the form.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { 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">ValidatedForm</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [email, setEmail] = useState(<span class="hljs-string">''</span>);
  <span class="hljs-keyword">const</span> [error, setError] = useState(<span class="hljs-string">''</span>);

  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> value = event.target.value;
    setEmail(value);

    <span class="hljs-keyword">if</span> (!value.includes(<span class="hljs-string">'@'</span>)) {
      setError(<span class="hljs-string">'Invalid email address'</span>);
    } <span class="hljs-keyword">else</span> {
      setError(<span class="hljs-string">''</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">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{email}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span> /&gt;</span>
      {error &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">color:</span> '<span class="hljs-attr">red</span>' }}&gt;</span>{error}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Here, the validation logic runs on every change, providing immediate feedback to the user if the input is invalid.</p>
<h3 id="heading-integration-with-complex-ui-libraries">Integration with Complex UI Libraries</h3>
<p>Controlled components integrate seamlessly with complex UI libraries and frameworks, such as Redux for state management or Formik for handling forms. </p>
<p>By managing form data in the component state, you can easily connect your forms to these libraries and benefit from their advanced features like global state management, asynchronous data fetching, and more.</p>
<p><strong>Example with Formik:</strong></p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { Formik, Form, Field, ErrorMessage } <span class="hljs-keyword">from</span> <span class="hljs-string">'formik'</span>;
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> Yup <span class="hljs-keyword">from</span> <span class="hljs-string">'yup'</span>;

<span class="hljs-keyword">const</span> SignupForm = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Formik</span>
    <span class="hljs-attr">initialValues</span>=<span class="hljs-string">{{</span> <span class="hljs-attr">email:</span> '' }}
    <span class="hljs-attr">validationSchema</span>=<span class="hljs-string">{Yup.object({</span>
      <span class="hljs-attr">email:</span> <span class="hljs-attr">Yup.string</span>()<span class="hljs-attr">.email</span>('<span class="hljs-attr">Invalid</span> <span class="hljs-attr">email</span> <span class="hljs-attr">address</span>')<span class="hljs-attr">.required</span>('<span class="hljs-attr">Required</span>'),
    })}
    <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{(values,</span> { <span class="hljs-attr">setSubmitting</span> }) =&gt;</span> {
      setTimeout(() =&gt; {
        alert(JSON.stringify(values, null, 2));
        setSubmitting(false);
      }, 400);
    }}
  &gt;
    {({ isSubmitting }) =&gt; (
      <span class="hljs-tag">&lt;<span class="hljs-name">Form</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">htmlFor</span>=<span class="hljs-string">"email"</span>&gt;</span>Email<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Field</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">ErrorMessage</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">component</span>=<span class="hljs-string">"div"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">disabled</span>=<span class="hljs-string">{isSubmitting}</span>&gt;</span>
          Submit
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">Form</span>&gt;</span>
    )}
  <span class="hljs-tag">&lt;/<span class="hljs-name">Formik</span>&gt;</span></span>
);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> SignupForm;
</code></pre>
<p>In this example, Formik handles form state and validation, demonstrating how controlled components can be part of more complex setups.</p>
<p>Controlled components provide predictable state management, easier form validation, and seamless integration with complex UI libraries. </p>
<p>By keeping the form data in the React state, you ensure consistency and control over your application's behavior, making it easier to build and maintain interactive and dynamic user interfaces.</p>
<h2 id="heading-examples-of-controlled-components">Examples of Controlled Components</h2>
<p>Controlled components are fundamental in React for handling form inputs in a predictable and manageable way. </p>
<p>Here are some examples of how you can implement controlled components for various types of form inputs, including text fields, email fields, password fields, select menus, checkboxes, and radio buttons.</p>
<h3 id="heading-input-fields-text-email-password">Input Fields (Text, Email, Password)</h3>
<h5 id="heading-text-input">Text Input</h5>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { 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">TextInput</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [text, setText] = useState(<span class="hljs-string">''</span>);

  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setText(event.target.value);
  };

  <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">label</span>&gt;</span>
        Text:
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{text}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Entered Text: {text}<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> TextInput;
</code></pre>
<h5 id="heading-email-input">Email Input</h5>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { 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">EmailInput</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [email, setEmail] = useState(<span class="hljs-string">''</span>);

  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setEmail(event.target.value);
  };

  <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">label</span>&gt;</span>
        Email:
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{email}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Entered Email: {email}<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> EmailInput;
</code></pre>
<h5 id="heading-password-input">Password Input</h5>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { 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">PasswordInput</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [password, setPassword] = useState(<span class="hljs-string">''</span>);

  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setPassword(event.target.value);
  };

  <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">label</span>&gt;</span>
        Password:
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{password}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Entered Password: {password}<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> PasswordInput;
</code></pre>
<h4 id="heading-select-menus">Select Menus</h4>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { 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">SelectMenu</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [option, setOption] = useState(<span class="hljs-string">'option1'</span>);

  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setOption(event.target.value);
  };

  <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">label</span>&gt;</span>
        Choose an option:
        <span class="hljs-tag">&lt;<span class="hljs-name">select</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{option}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"option1"</span>&gt;</span>Option 1<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"option2"</span>&gt;</span>Option 2<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"option3"</span>&gt;</span>Option 3<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Selected Option: {option}<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> SelectMenu;
</code></pre>
<h4 id="heading-checkboxes">Checkboxes</h4>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { 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">Checkbox</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [isChecked, setIsChecked] = useState(<span class="hljs-literal">false</span>);

  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setIsChecked(event.target.checked);
  };

  <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">label</span>&gt;</span>
        Accept Terms:
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">checked</span>=<span class="hljs-string">{isChecked}</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Checked: {isChecked ? 'Yes' : 'No'}<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> Checkbox;
</code></pre>
<h4 id="heading-radio-buttons">Radio Buttons</h4>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { 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">RadioButton</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [selectedOption, setSelectedOption] = useState(<span class="hljs-string">'option1'</span>);

  <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setSelectedOption(event.target.value);
  };

  <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">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span>
          <span class="hljs-attr">value</span>=<span class="hljs-string">"option1"</span>
          <span class="hljs-attr">checked</span>=<span class="hljs-string">{selectedOption</span> === <span class="hljs-string">'option1'</span>}
          <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span>
        /&gt;</span>
        Option 1
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span>
          <span class="hljs-attr">value</span>=<span class="hljs-string">"option2"</span>
          <span class="hljs-attr">checked</span>=<span class="hljs-string">{selectedOption</span> === <span class="hljs-string">'option2'</span>}
          <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span>
        /&gt;</span>
        Option 2
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"radio"</span>
          <span class="hljs-attr">value</span>=<span class="hljs-string">"option3"</span>
          <span class="hljs-attr">checked</span>=<span class="hljs-string">{selectedOption</span> === <span class="hljs-string">'option3'</span>}
          <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span>
        /&gt;</span>
        Option 3
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Selected Option: {selectedOption}<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> RadioButton;
</code></pre>
<p>Controlled components provide a clear and consistent way to handle form inputs in React. By using React state to manage the values of input fields, select menus, checkboxes, and radio buttons, you ensure that the UI remains in sync with the state. </p>
<p>This approach simplifies validation, makes data handling predictable, and facilitates integration with complex UI libraries.</p>
<h2 id="heading-what-are-uncontrolled-components">What are Uncontrolled Components?</h2>
<p>Uncontrolled components in React manage their own state internally rather than relying on React state. This approach is useful for simple forms where you don't need to manipulate the input data through React state updates.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UncontrolledComponent</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-built_in">super</span>(props);
    <span class="hljs-comment">// Create a ref to hold the input DOM element</span>
    <span class="hljs-built_in">this</span>.inputRef = React.createRef();
  }

  handleSubmit = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Access the input value using the ref</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.inputRef.current.value);
  }

  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        {/* Use ref attribute to attach the ref to the input element */}
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> 
          <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> 
          <span class="hljs-attr">ref</span>=<span class="hljs-string">{this.inputRef}</span> 
        /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.handleSubmit}</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}
</code></pre>
<ul>
<li><strong>Ref Usage:</strong> In uncontrolled components, we use the <code>ref</code> attribute to create a reference (<code>this.inputRef</code>) to the DOM node of the input field.</li>
<li><strong>Handling Input:</strong> When the user enters data and clicks "Submit", <code>this.inputRef.current.value</code> allows us to directly access the current value of the input field without involving React state.</li>
<li><strong>Advantages:</strong> Uncontrolled components can be simpler and faster for basic form handling. They are often used when the form data is not needed in React state for any processing or validation.</li>
</ul>
<p><strong>Key Points:</strong></p>
<ul>
<li><strong>Internal State:</strong> Uncontrolled components manage their state internally with the help of refs, not with React state updates.</li>
<li><strong>Direct DOM Access:</strong> Accessing form data is done directly through DOM refs (<code>this.inputRef.current.value</code>).</li>
<li><strong>Simplicity:</strong> They are straightforward for simple forms where real-time validation or complex form interactions are not necessary.</li>
</ul>
<p>Uncontrolled components are handy in scenarios where you want a lightweight approach to handling form data without the overhead of managing state in React.</p>
<h2 id="heading-how-uncontrolled-components-work">How Uncontrolled Components Work</h2>
<p>Uncontrolled components manage their state internally using DOM refs (<code>useRef</code> hook in functional components or <code>React.createRef()</code> in class components) to access form element values directly. </p>
<p>Unlike controlled components, where form data is managed through React state and updated via <code>setState</code>, uncontrolled components bypass React's state management for handling form inputs.</p>
<h3 id="heading-direct-dom-access-with-useref-hook">Direct DOM Access with useRef Hook</h3>
<p>In functional components, the <code>useRef</code> hook allows us to create a mutable reference that persists across renders. We can use this ref to directly access DOM nodes, such as input fields.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { 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">UncontrolledComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> inputRef = useRef(<span class="hljs-literal">null</span>); <span class="hljs-comment">// Create a ref to hold the input DOM element</span>

  <span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// Access the input value using the ref</span>
    <span class="hljs-built_in">console</span>.log(inputRef.current.value);
  };

  <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">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputRef}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> UncontrolledComponent;
</code></pre>
<h3 id="heading-accessing-an-elements-value-on-submit">Accessing an Element's Value on Submit</h3>
<p>In the example above:</p>
<ul>
<li><strong>Creating a Ref:</strong> <code>const inputRef = useRef(null);</code> initializes a ref named <code>inputRef</code> to hold the reference to the input DOM element.</li>
<li><strong>Handling Submit:</strong> When the "Submit" button is clicked (<code>onClick={handleSubmit}</code>), the <code>handleSubmit</code> function retrieves the current value of the input field using <code>inputRef.current.value</code>.</li>
</ul>
<p><strong>Key Points:</strong></p>
<ul>
<li><strong>DOM Access:</strong> The <code>useRef</code> hook allows direct access to DOM elements, enabling us to interact with them without updating React state.</li>
<li><strong>Form Submission:</strong> On form submission (<code>onClick={handleSubmit}</code>), the function accesses the current value of the input field through <code>inputRef.current.value</code>.</li>
<li><strong>Simplicity:</strong> Uncontrolled components are straightforward for basic form handling scenarios where direct DOM manipulation suffices, avoiding the need for managing state updates in React.</li>
</ul>
<p>Using uncontrolled components with <code>useRef</code> is particularly useful for handling forms where real-time validation or complex interactions aren't necessary, focusing instead on simplicity and performance.</p>
<h2 id="heading-when-to-use-uncontrolled-components">When to Use Uncontrolled Components</h2>
<p>Uncontrolled components are ideal in specific scenarios where simplicity and direct DOM manipulation are advantageous over managing state with React. </p>
<p>Here are the key situations when using uncontrolled components is beneficial:</p>
<h3 id="heading-1-simple-forms-with-limited-interactions">1. Simple Forms with Limited Interactions</h3>
<p>Uncontrolled components shine in scenarios where:</p>
<ul>
<li><strong>The Forms Arent' That Complex:</strong> The form is straightforward with minimal input fields and does not require complex validation or dynamic updates based on other form inputs.</li>
<li><strong>Performance is Important:</strong> Directly accessing form values via DOM refs (<code>useRef</code> or <code>React.createRef()</code>) can be more performant than updating React state for each input change, especially in large forms.</li>
<li><strong>You want Simplicity:</strong> When you prefer a simpler implementation without managing state updates and re-renders for form inputs.</li>
</ul>
<h3 id="heading-2-focus-management-selecting-text">2. Focus Management (Selecting Text)</h3>
<p>In some cases, you might need to manage user interaction such as selecting text within an input field or programmatically focusing on a specific input without triggering React state updates unnecessarily. </p>
<p>Uncontrolled components allow you to:</p>
<ul>
<li><strong>Directly manipulate the DOM:</strong> Use DOM methods like <code>select()</code> on the input element directly via refs to manage focus or text selection.</li>
<li><strong>Handling focus and text selection directly with refs</strong>: This can be more efficient and straightforward compared to triggering state updates and managing focus state in React components.</li>
</ul>
<h4 id="heading-example-use-case">Example Use Case:</h4>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { 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">UncontrolledComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> inputRef = useRef(<span class="hljs-literal">null</span>); <span class="hljs-comment">// Create a ref to hold the input DOM element</span>

  <span class="hljs-keyword">const</span> handleFocus = <span class="hljs-function">() =&gt;</span> {
    inputRef.current.select(); <span class="hljs-comment">// Selects all text in the input field</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">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputRef}</span> <span class="hljs-attr">defaultValue</span>=<span class="hljs-string">"Initial Value"</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleFocus}</span>&gt;</span>Select Text<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> UncontrolledComponent;
</code></pre>
<p>In this example, clicking the "Select Text" button calls <code>inputRef.current.select()</code> to select all text within the input field directly, without involving React state updates. This is a simple yet effective use of uncontrolled components for managing focus and text selection.</p>
<h2 id="heading-limitations-of-uncontrolled-components">Limitations of Uncontrolled Components</h2>
<p>Using uncontrolled components in React can offer simplicity and performance benefits in certain scenarios, but they also come with limitations that are important to consider:</p>
<h3 id="heading-difficulty-in-form-validation">Difficulty in Form Validation:</h3>
<ul>
<li>Uncontrolled components can make form validation more challenging compared to controlled components. Since the form data is managed internally by the DOM rather than React state, validating and ensuring data consistency across multiple inputs can be complex.</li>
<li>Validation logic often involves accessing and checking each input's value directly through refs (<code>ref.current.value</code>). This approach can lead to more manual and error-prone validation code, especially in forms with complex validation requirements.</li>
</ul>
<h3 id="heading-less-predictable-state-management">Less Predictable State Management:</h3>
<ul>
<li>Uncontrolled components bypass React's state management, which can lead to less predictable state handling in complex applications. Changes in form data are not automatically synchronized with React's state updates or other component state, potentially leading to inconsistencies.</li>
<li>This lack of synchronization can make it challenging to maintain a single source of truth for form data across different components or when integrating with other state management solutions like Redux or Context API.</li>
</ul>
<h3 id="heading-limited-react-ecosystem-integration">Limited React Ecosystem Integration:</h3>
<ul>
<li>Uncontrolled components may not fully leverage React's ecosystem features, such as state persistence, time-travel debugging (with Redux), or seamless integration with third-party libraries designed for controlled components.</li>
<li>Components relying on React state benefit from these features, enhancing developer productivity and application maintainability.</li>
</ul>
<h2 id="heading-examples-of-uncontrolled-components">Examples of Uncontrolled Components</h2>
<p>Uncontrolled components in React are particularly useful for handling input fields and textarea elements where direct DOM manipulation suffices, and React state management isn't necessary. </p>
<p>Here are examples of how uncontrolled components can be applied:</p>
<h3 id="heading-1-input-fields-read-only-or-pre-filled-data">1. Input Fields (Read-only or Pre-filled Data)</h3>
<p>Uncontrolled components can be used when you need to display read-only or pre-filled data in an input field without managing its state in React.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { 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">UncontrolledInput</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> initialValue = <span class="hljs-string">'Hello, World!'</span>;
  <span class="hljs-keyword">const</span> inputRef = useRef(<span class="hljs-literal">null</span>); <span class="hljs-comment">// Create a ref to hold the input DOM element</span>

  <span class="hljs-keyword">const</span> handleFocus = <span class="hljs-function">() =&gt;</span> {
    inputRef.current.select(); <span class="hljs-comment">// Selects all text in the input field on focus</span>
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      {/* Using defaultValue for pre-filled data */}
      <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{inputRef}</span> <span class="hljs-attr">defaultValue</span>=<span class="hljs-string">{initialValue}</span> <span class="hljs-attr">readOnly</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleFocus}</span>&gt;</span>Select Text<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> UncontrolledInput;
</code></pre>
<p>In this example:</p>
<ul>
<li>The <code>defaultValue</code> attribute sets the initial value of the input field.</li>
<li><code>readOnly</code> attribute prevents users from editing the input field, making it read-only.</li>
<li><code>useRef</code> hook manages focus and selection of text within the input field using <code>inputRef.current</code>.</li>
</ul>
<h3 id="heading-2-textarea-elements">2. Textarea Elements</h3>
<p>Uncontrolled components are also applicable to textarea elements, especially when dealing with multiline text input where immediate state updates are not necessary.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { 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">UncontrolledTextarea</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> initialText = <span class="hljs-string">'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'</span>;
  <span class="hljs-keyword">const</span> textareaRef = useRef(<span class="hljs-literal">null</span>); <span class="hljs-comment">// Create a ref to hold the textarea DOM element</span>

  <span class="hljs-keyword">const</span> handleClear = <span class="hljs-function">() =&gt;</span> {
    textareaRef.current.value = <span class="hljs-string">''</span>; <span class="hljs-comment">// Clear textarea content directly</span>
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      {/* Using defaultValue for pre-filled content */}
      <span class="hljs-tag">&lt;<span class="hljs-name">textarea</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">{textareaRef}</span> <span class="hljs-attr">defaultValue</span>=<span class="hljs-string">{initialText}</span> <span class="hljs-attr">rows</span>=<span class="hljs-string">{4}</span> <span class="hljs-attr">cols</span>=<span class="hljs-string">{50}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClear}</span>&gt;</span>Clear Text<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> UncontrolledTextarea;
</code></pre>
<p>In this example:</p>
<ul>
<li>The <code>defaultValue</code> attribute sets the initial content of the textarea.</li>
<li><code>useRef</code> hook manages direct manipulation of textarea content using <code>textareaRef.current</code>.</li>
<li><code>rows</code> and <code>cols</code> attributes define the dimensions of the textarea.</li>
</ul>
<p><strong>Key points:</strong></p>
<ul>
<li><strong>Direct DOM Access:</strong> Uncontrolled components leverage <code>useRef</code> to directly manipulate DOM elements for managing input fields and textarea content.</li>
<li><strong>Performance:</strong> Suitable for scenarios where real-time updates or complex state management aren't required, enhancing performance by avoiding unnecessary state updates.</li>
<li><strong>Simplicity:</strong> Provides a straightforward approach to handling form elements with default or read-only values, maintaining simplicity in component logic.</li>
</ul>
<p>These examples demonstrate how uncontrolled components can handle input fields and textarea elements effectively in React applications, focusing on simplicity and direct DOM manipulation for specific use cases.</p>
<h2 id="heading-factors-to-consider-when-choosing-between-controlled-and-uncontrolled-components">Factors to Consider When Choosing Between Controlled and Uncontrolled Components</h2>
<p>When deciding between controlled and uncontrolled components in React, several factors should be considered to determine which approach best suits your application's requirements. Here are key considerations for each factor:</p>
<h3 id="heading-1-complexity-of-form">1. Complexity of Form</h3>
<h4 id="heading-controlled-components">Controlled Components:</h4>
<ul>
<li><strong>Advantages:</strong> Suitable for complex forms where you need precise control over the form state and its interaction with other components.</li>
<li><strong>Usage:</strong> Use controlled components when form inputs depend on each other, require validation, or when you need to synchronize form state across multiple components or pages.</li>
</ul>
<h4 id="heading-uncontrolled-components">Uncontrolled Components:</h4>
<ul>
<li><strong>Advantages:</strong> Simplify implementation for basic forms with minimal interactivity or where direct DOM manipulation suffices.</li>
<li><strong>Usage:</strong> Ideal for simple forms without complex validation or when managing form state in React isn't necessary for your use case.</li>
</ul>
<h3 id="heading-2-need-for-form-validation">2. Need for Form Validation</h3>
<h4 id="heading-controlled-components-1">Controlled Components:</h4>
<ul>
<li><strong>Advantages:</strong> Easier integration with form validation libraries (for example, Formik, Yup) since form state is managed within React state.</li>
<li><strong>Usage:</strong> Use controlled components when implementing complex validation rules, such as conditional validation or asynchronous validation logic.</li>
</ul>
<h4 id="heading-uncontrolled-components-1">Uncontrolled Components:</h4>
<ul>
<li><strong>Challenges:</strong> Handling form validation can be more manual and less integrated, as form data is managed directly through DOM manipulation.</li>
<li><strong>Usage:</strong> Consider uncontrolled components for simple forms where validation requirements are minimal or where custom validation logic can be managed without relying heavily on React state updates.</li>
</ul>
<h3 id="heading-3-integration-with-external-libraries">3. Integration with External Libraries</h3>
<h4 id="heading-controlled-components-2">Controlled Components:</h4>
<ul>
<li><strong>Advantages:</strong> Seamlessly integrates with external state management solutions like Redux or React's Context API for managing global application state.</li>
<li><strong>Usage:</strong> Prefer controlled components when your application requires integration with third-party libraries or when leveraging advanced React ecosystem features (for example, time-travel debugging with Redux).</li>
</ul>
<h4 id="heading-uncontrolled-components-2">Uncontrolled Components:</h4>
<ul>
<li><strong>Considerations:</strong> May require additional effort to integrate with external libraries that assume controlled component behavior.</li>
<li><strong>Usage:</strong> Use uncontrolled components when external state management isn't necessary, focusing on lightweight implementation and minimizing dependencies.</li>
</ul>
<h3 id="heading-additional-considerations">Additional Considerations:</h3>
<h4 id="heading-performance">Performance:</h4>
<p>Controlled components may incur overhead due to frequent state updates, whereas uncontrolled components can offer better performance for simple forms by reducing re-renders.</p>
<h4 id="heading-developer-preference">Developer Preference:</h4>
<p>Consider team familiarity and preferences with React state management patterns when deciding between controlled and uncontrolled components.</p>
<h3 id="heading-summary">Summary:</h3>
<p><strong>Choose Controlled Components</strong> for complex forms, robust validation needs, and seamless integration with external state management and validation libraries.</p>
<p><strong>Opt for Uncontrolled Components</strong> for simpler forms, minimal validation requirements, and when direct DOM manipulation provides sufficient functionality without the need for managing form state in React.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The choice between controlled and uncontrolled components in React hinges on several critical factors that determine the optimal approach for form management within your application.</p>
<p>Ultimately, the decision should align with your project's specific needs, considering factors such as form complexity, validation requirements, integration with external libraries, and developer preferences. </p>
<p>By carefully assessing these factors, you can implement the most effective form handling strategy in React that balances functionality, performance, and ease of maintenance.</p>
<p>Connect with me on <a target="_blank" href="https://linkedin.com/in/joanayebola">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use WeakMap and WeakSet in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript offers a number of tools for organizing and managing data. And while developers often use widely recognized tools like Maps and Sets, they may often overlook certain other valuable resources.  For example, are you familiar with WeakMap and... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/weakmap-and-weakset-in-javascript/</link>
                <guid isPermaLink="false">66c4c41a1b22d2d8d9040eaf</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Fri, 07 Jun 2024 16:57:53 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/Ivory-and-Blue-Lavender-Aesthetic-Photo-Collage-Presentation.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript offers a number of tools for organizing and managing data. And while developers often use widely recognized tools like Maps and Sets, they may often overlook certain other valuable resources. </p>
<p>For example, are you familiar with WeakMap and WeakSet? They're special tools in JavaScript that help store and manage data in unique ways.</p>
<p>This article explores WeakMap and WeakSet in a clear and comprehensive way. We'll start by understanding the concept of weak references and how they differ from traditional data structures. Then, we'll dive deeper into each concept, explaining what they are, how to create them, and the methods they offer. </p>
<p>Along the way, we'll see practical examples of how WeakMap and WeakSet can streamline your code and unlock new possibilities.</p>
<p>Whether you're a JavaScript pro or just starting out, understanding WeakMap and WeakSet empowers you to write cleaner, more efficient code.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#heading-what-is-a-weakmap">What is a WeakMap?</a><br>– <a class="post-section-overview" href="#heading-key-characteristics-of-weakmap">Key Characteristics of WeakMap</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-weakmap-using-the-new-weakmap-constructor">How to Create a WeakMap using the <code>new WeakMap()</code> Constructor</a></li>
<li><a class="post-section-overview" href="#heading-common-use-cases-for-weakmap">Common Use Cases for WeakMap</a></li>
<li><a class="post-section-overview" href="#heading-methods-of-weakmap">Methods of WeakMap</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-weakset">What is a WeakSet?</a><br>– <a class="post-section-overview" href="#heading-key-characteristics-of-weakset">Key Characteristics of WeakSet</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-weakset-using-the-new-weakset-constructor">How to Create a WeakSet using the <code>new WeakSet()</code> constructor</a></li>
<li><a class="post-section-overview" href="#heading-common-use-cases-for-weakset">Common Use Cases for WeakSet</a></li>
<li><a class="post-section-overview" href="#heading-methods-of-weakset">Methods of WeakSet</a></li>
<li><a class="post-section-overview" href="#heading-weakset-vs-weakmap">WeakSet vs. WeakMap</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-is-a-weakmap">What is a WeakMap?</h2>
<p>WeakMap is a built-in JavaScript data structure introduced in ECMAScript 6 (ES6). It's meant for storing key-value pairs where the keys must be objects and the values can be arbitrary. </p>
<p>It differs from a regular Map in that it allows for weak references to its keys. This means that if an object is used as a key and there are no other references to it, it can be garbage collected.</p>
<h3 id="heading-key-characteristics-of-weakmap">Key Characteristics of WeakMap</h3>
<h4 id="heading-object-only-keys">Object-only Keys:</h4>
<p>WeakMap accepts only objects as keys. If you attempt to use a non-object key, such as a string or number, it will result in a TypeError.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> weakMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();
<span class="hljs-keyword">const</span> key = {}; <span class="hljs-comment">// Valid key, as it's an object</span>
<span class="hljs-keyword">const</span> invalidKey = <span class="hljs-string">'string'</span>; <span class="hljs-comment">// Invalid key, as it's not an object</span>
weakMap.set(key, <span class="hljs-string">'value'</span>); <span class="hljs-comment">// This will work</span>
weakMap.set(invalidKey, <span class="hljs-string">'value'</span>); <span class="hljs-comment">// TypeError: Invalid value used as weak map key</span>
</code></pre>
<h4 id="heading-garbage-collection-of-keys">Garbage Collection of Keys:</h4>
<p>WeakMap allows keys to be garbage collected when there are no other references to them. This means that if an object used as a key in a WeakMap is no longer referenced anywhere else in the program, it can be automatically removed from the WeakMap.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> key = {<span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>};
<span class="hljs-keyword">const</span> weakMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();
weakMap.set(key, <span class="hljs-string">'value'</span>);
key = <span class="hljs-literal">null</span>; <span class="hljs-comment">// Removing the reference to the key</span>
<span class="hljs-comment">// At this point, since there are no other references to the key object,</span>
<span class="hljs-comment">// it can be garbage collected, and the key-value pair in the WeakMap will be automatically removed</span>
</code></pre>
<h4 id="heading-no-enumeration-of-keys">No Enumeration of Keys:</h4>
<p>Unlike regular Map objects, WeakMap does not expose methods for enumerating its keys, such as <code>keys()</code>, <code>values()</code>, or <code>entries()</code>. This is because the keys might be subject to garbage collection, and exposing them would prevent their collection.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> weakMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();
<span class="hljs-keyword">const</span> key = {};
weakMap.set(key, <span class="hljs-string">'value'</span>);
<span class="hljs-built_in">console</span>.log(weakMap.keys()); <span class="hljs-comment">// TypeError: weakMap.keys is not a function</span>
</code></pre>
<h4 id="heading-no-size-property">No Size Property:</h4>
<p>WeakMap does not have a <code>size</code> property like regular Map objects. Again, this is because the size of the WeakMap could change as keys are garbage collected.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> weakMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();
<span class="hljs-built_in">console</span>.log(weakMap.size); <span class="hljs-comment">// undefined</span>
</code></pre>
<h4 id="heading-memory-management">Memory Management:</h4>
<p>WeakMap is particularly useful in scenarios where you need to associate additional data with objects but do not want to prevent those objects from being garbage collected when they are no longer needed. This makes it useful for caching, private data storage, and other memory-sensitive operations.</p>
<h2 id="heading-how-to-create-a-weakmap-using-the-new-weakmap-constructor">How to Create a WeakMap using the <code>new WeakMap()</code> Constructor</h2>
<p>Creating a WeakMap using the <code>new WeakMap()</code> constructor is straightforward. Here's how you can do it:</p>
<p>Firstly, let's break down the syntax of creating a WeakMap using the <code>new WeakMap()</code> constructor:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> weakMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();
</code></pre>
<ul>
<li><code>new WeakMap()</code>: This is the constructor call that creates a new instance of WeakMap.</li>
<li><code>const weakMap</code>: This declares a variable named <code>weakMap</code> to hold the reference to the newly created WeakMap instance.</li>
<li><code>=</code>: This is the assignment operator, which assigns the newly created WeakMap instance to the variable <code>weakMap</code>.</li>
</ul>
<p>Now, let's create a WeakMap example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Creating a new WeakMap</span>
<span class="hljs-keyword">const</span> weakMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();

<span class="hljs-comment">// Creating objects to use as keys</span>
<span class="hljs-keyword">const</span> user1 = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
<span class="hljs-keyword">const</span> user2 = { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span> };

<span class="hljs-comment">// Setting key-value pairs in the WeakMap</span>
weakMap.set(user1, <span class="hljs-string">'John'</span>);
weakMap.set(user2, <span class="hljs-string">'Alice'</span>);

<span class="hljs-comment">// Retrieving values from the WeakMap</span>
<span class="hljs-built_in">console</span>.log(weakMap.get(user1)); <span class="hljs-comment">// Output: John</span>
<span class="hljs-built_in">console</span>.log(weakMap.get(user2)); <span class="hljs-comment">// Output: Alice</span>

<span class="hljs-comment">// Deleting a key-value pair from the WeakMap</span>
weakMap.delete(user1);

<span class="hljs-comment">// Trying to retrieve the value after deletion</span>
<span class="hljs-built_in">console</span>.log(weakMap.get(user1)); <span class="hljs-comment">// Output: undefined</span>
</code></pre>
<p>In this example:</p>
<ul>
<li>We create a new WeakMap instance using the <code>new WeakMap()</code> constructor.</li>
<li>Two objects <code>user1</code> and <code>user2</code> are created to serve as keys in the WeakMap.</li>
<li>Key-value pairs are set in the WeakMap using the <code>set()</code> method, associating each user object with a corresponding name.</li>
<li>We retrieve the values associated with <code>user1</code> and <code>user2</code> using the <code>get()</code> method.</li>
<li>Then, we delete the key-value pair associated with <code>user1</code> using the <code>delete()</code> method.</li>
<li>Finally, we attempt to retrieve the value associated with <code>user1</code> again, which returns <code>undefined</code> since the key-value pair has been deleted.</li>
</ul>
<p>Remember that WeakMap only accepts objects as keys. If you try to use a non-object as a key, it will result in a TypeError. </p>
<p>Also, WeakMap does not support methods like <code>keys()</code>, <code>values()</code>, or <code>entries()</code>, nor does it have properties like <code>size</code>. This is because WeakMap keys may be subject to garbage collection, and exposing them would interfere with this process.</p>
<h2 id="heading-common-use-cases-for-weakmap">Common Use Cases for WeakMap</h2>
<p>WeakMap is a specialized data structure in JavaScript designed for specific use cases where you need to associate additional data with objects without preventing those objects from being garbage collected. </p>
<p>Here are some common scenarios where WeakMap is particularly useful:</p>
<h3 id="heading-private-data-storage">Private Data Storage:</h3>
<p>WeakMap can be used to store private data associated with objects. This is often used in libraries or frameworks to attach private data to objects without exposing it to the outside world. </p>
<p>Since WeakMap keys are weakly held, the private data will be automatically removed when the object is garbage collected.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> privateData = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        privateData.set(<span class="hljs-built_in">this</span>, { <span class="hljs-attr">secret</span>: <span class="hljs-string">'my secret data'</span> });
    }

    getSecretData() {
        <span class="hljs-keyword">return</span> privateData.get(<span class="hljs-built_in">this</span>).secret;
    }
}

<span class="hljs-keyword">const</span> obj = <span class="hljs-keyword">new</span> MyClass();
<span class="hljs-built_in">console</span>.log(obj.getSecretData()); <span class="hljs-comment">// Output: my secret data</span>
</code></pre>
<h3 id="heading-caching-mechanism">Caching Mechanism:</h3>
<p>WeakMap can be used for caching data where the cached values can be garbage collected if they are no longer needed. </p>
<p>This can be particularly useful in scenarios where you want to cache data associated with specific objects or computations but want to ensure that the cache does not prevent those objects from being garbage collected when they are no longer needed.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> cache = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">expensiveCalculation</span>(<span class="hljs-params">obj</span>) </span>{
    <span class="hljs-keyword">if</span> (!cache.has(obj)) {
        <span class="hljs-keyword">const</span> result = <span class="hljs-comment">// perform expensive calculation</span>
        cache.set(obj, result);
    }
    <span class="hljs-keyword">return</span> cache.get(obj);
}

<span class="hljs-keyword">const</span> data = { <span class="hljs-comment">/* some data */</span> };
<span class="hljs-built_in">console</span>.log(expensiveCalculation(data)); <span class="hljs-comment">// Performs expensive calculation</span>
<span class="hljs-built_in">console</span>.log(expensiveCalculation(data)); <span class="hljs-comment">// Returns cached result</span>
</code></pre>
<h3 id="heading-dom-element-management">DOM Element Management:</h3>
<p>WeakMap can be used to keep track of DOM elements without preventing them from being garbage collected when they are removed from the DOM. </p>
<p>This is particularly useful in scenarios where you want to associate additional data or behavior with DOM elements but want to ensure that those associations do not prevent the elements from being properly cleaned up when they are no longer needed.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> elementData = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">attachEventListener</span>(<span class="hljs-params">element, callback</span>) </span>{
    element.addEventListener(<span class="hljs-string">'click'</span>, callback);
    elementData.set(element, { callback });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">detachEventListener</span>(<span class="hljs-params">element</span>) </span>{
    <span class="hljs-keyword">const</span> data = elementData.get(element);
    <span class="hljs-keyword">if</span> (data) {
        element.removeEventListener(<span class="hljs-string">'click'</span>, data.callback);
        elementData.delete(element);
    }
}

<span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myButton'</span>);
attachEventListener(button, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Button clicked'</span>);
});
</code></pre>
<h3 id="heading-memoization">Memoization:</h3>
<p>WeakMap can be used for memoization in functions where the cached values can be automatically cleared if they are no longer needed. </p>
<p>This is useful in scenarios where you want to cache the results of expensive function calls but want to ensure that the cache does not grow indefinitely and consume excessive memory.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> memoizationCache = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">memoizedFunction</span>(<span class="hljs-params">obj</span>) </span>{
    <span class="hljs-keyword">if</span> (!memoizationCache.has(obj)) {
        <span class="hljs-keyword">const</span> result = <span class="hljs-comment">// perform expensive computation</span>
        memoizationCache.set(obj, result);
    }
    <span class="hljs-keyword">return</span> memoizationCache.get(obj);
}

<span class="hljs-keyword">const</span> data = { <span class="hljs-comment">/* some data */</span> };
<span class="hljs-built_in">console</span>.log(memoizedFunction(data)); <span class="hljs-comment">// Performs expensive computation</span>
<span class="hljs-built_in">console</span>.log(memoizedFunction(data)); <span class="hljs-comment">// Returns cached result</span>
</code></pre>
<h2 id="heading-methods-of-weakmap">Methods of WeakMap</h2>
<p>WeakMap in JavaScript has a limited set of methods compared to other data structures like Map.</p>
<p>Here are the methods available for WeakMap:</p>
<h3 id="heading-setkey-value"><code>set(key, value)</code>:</h3>
<p>This method sets a new key-value pair in the WeakMap. The key must be an object, and the value can be any data type.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> weakMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();
<span class="hljs-keyword">const</span> key = {};
weakMap.set(key, <span class="hljs-string">'value'</span>);
</code></pre>
<h3 id="heading-getkey"><code>get(key)</code>:</h3>
<p>This method retrieves the value associated with the specified key in the WeakMap. If the key is not found, it returns undefined.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> weakMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();
<span class="hljs-keyword">const</span> key = {};
weakMap.set(key, <span class="hljs-string">'value'</span>);
<span class="hljs-built_in">console</span>.log(weakMap.get(key)); <span class="hljs-comment">// Output: value</span>
</code></pre>
<h3 id="heading-haskey"><code>has(key)</code>:</h3>
<p>This method checks whether the specified key exists in the WeakMap. It returns true if the key exists and false otherwise.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> weakMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();
<span class="hljs-keyword">const</span> key = {};
weakMap.set(key, <span class="hljs-string">'value'</span>);
<span class="hljs-built_in">console</span>.log(weakMap.has(key)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<h3 id="heading-deletekey"><code>delete(key)</code>:</h3>
<p>This method removes the specified key and its associated value from the WeakMap. It returns true if the key existed and was removed successfully, and false otherwise.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> weakMap = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();
<span class="hljs-keyword">const</span> key = {};
weakMap.set(key, <span class="hljs-string">'value'</span>);
<span class="hljs-built_in">console</span>.log(weakMap.delete(key)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>Remember that WeakMap does not have methods like <code>keys()</code>, <code>values()</code>, <code>entries()</code>, or properties like <code>size</code>. This is because WeakMap keys may be subject to garbage collection, and exposing them would interfere with this process.<br>Also, WeakMap does not allow iteration over its keys or values for the same reason.</p>
<h2 id="heading-what-is-a-weakset">What is a WeakSet?</h2>
<p>WeakSet is another specialized data structure introduced in ECMAScript 6 (ES6) alongside WeakMap. It's designed to work with collections of objects. </p>
<p>Unlike Set, WeakSet allows only objects to be stored, and like WeakMap, it holds weak references to these objects. This means that if an object stored in a WeakSet has no other references elsewhere in the program, it can be automatically garbage collected. This makes WeakSet particularly useful in scenarios where you need to maintain a collection of objects without preventing them from being cleaned up when they are no longer needed.</p>
<h3 id="heading-key-characteristics-of-weakset">Key Characteristics of WeakSet</h3>
<h4 id="heading-object-only-values">Object-only Values:</h4>
<p>WeakSet allows only objects to be stored as values. If you attempt to add a non-object value, such as a primitive or another type of data, it will result in a TypeError.</p>
<h4 id="heading-weak-references">Weak References:</h4>
<p>Similar to WeakMap, WeakSet holds weak references to its elements. This means that if an object stored in a WeakSet has no other references elsewhere in the program, it can be automatically garbage collected.</p>
<h4 id="heading-no-enumeration">No Enumeration:</h4>
<p>WeakSet does not provide methods like <code>keys()</code>, <code>values()</code>, or <code>entries()</code>, nor does it support iteration with <code>forEach()</code>. This is because the contents of a WeakSet may change as objects are garbage collected, and exposing them would interfere with this process.</p>
<h4 id="heading-no-size-property-1">No Size Property:</h4>
<p>WeakSet does not have a <code>size</code> property like Set objects. This is because the size of a WeakSet could change as objects are garbage collected, and exposing the size property would not provide accurate information.</p>
<h4 id="heading-memory-management-1">Memory Management:</h4>
<p>WeakSet is useful for scenarios where you need to maintain a collection of objects but do not want to prevent those objects from being garbage collected when they are no longer needed. </p>
<p>This can be particularly useful in scenarios such as event handling, where objects may be added to the set temporarily and then removed later.</p>
<h2 id="heading-how-to-create-a-weakset-using-the-new-weakset-constructor">How to Create a WeakSet using the <code>new WeakSet()</code> Constructor</h2>
<p>Firstly, let's break down the syntax:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> weakSet = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>();
</code></pre>
<ul>
<li><code>new WeakSet()</code>: This is the constructor call that creates a new instance of WeakSet.</li>
<li><code>const weakSet</code>: This declares a variable named <code>weakSet</code> to hold the reference to the newly created WeakSet instance.</li>
<li><code>=</code>: This is the assignment operator, which assigns the newly created WeakSet instance to the variable <code>weakSet</code>.</li>
</ul>
<p>Now, let's create a WeakMap example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Creating a new WeakSet</span>
<span class="hljs-keyword">const</span> weakSet = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>();

<span class="hljs-comment">// Creating some objects to add to the WeakSet</span>
<span class="hljs-keyword">const</span> obj1 = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
<span class="hljs-keyword">const</span> obj2 = { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span> };
<span class="hljs-keyword">const</span> obj3 = { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span> };

<span class="hljs-comment">// Adding objects to the WeakSet</span>
weakSet.add(obj1);
weakSet.add(obj2);
weakSet.add(obj3);

<span class="hljs-comment">// Checking if an object exists in the WeakSet</span>
<span class="hljs-built_in">console</span>.log(weakSet.has(obj1)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(weakSet.has(obj2)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(weakSet.has(obj3)); <span class="hljs-comment">// Output: true</span>

<span class="hljs-comment">// Deleting an object from the WeakSet</span>
weakSet.delete(obj2);

<span class="hljs-comment">// Checking if the deleted object still exists</span>
<span class="hljs-built_in">console</span>.log(weakSet.has(obj2)); <span class="hljs-comment">// Output: false</span>
</code></pre>
<p>In this example:</p>
<ul>
<li>We first create a new WeakSet instance using the <code>new WeakSet()</code> constructor.</li>
<li>Then, we create three different objects <code>obj1</code>, <code>obj2</code>, and <code>obj3</code> that we want to add to the WeakSet.</li>
<li>We add these objects to the WeakSet using the <code>add()</code> method.</li>
<li>We check if each object exists in the WeakSet using the <code>has()</code> method.</li>
<li>Next, we delete <code>obj2</code> from the WeakSet using the <code>delete()</code> method.</li>
<li>Finally, we check if <code>obj2</code> still exists in the WeakSet, which returns <code>false</code> since it has been deleted.</li>
</ul>
<h2 id="heading-common-use-cases-for-weakset">Common Use Cases for WeakSet</h2>
<p>WeakSet in JavaScript serves specific purposes due to its ability to hold weak references to objects. </p>
<p>Here are some common use cases where WeakSet can be particularly useful:</p>
<h3 id="heading-object-membership-checking">Object Membership Checking:</h3>
<p>WeakSet is useful for tracking the membership of objects in a collection without preventing them from being garbage collected when they are no longer needed. </p>
<p>This can be helpful in scenarios where you need to keep track of a dynamic set of objects, such as managing event handlers or tracking temporary data associations.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> eventHandlers = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addEventHandler</span>(<span class="hljs-params">element, handler</span>) </span>{
    eventHandlers.add(handler);
    element.addEventListener(<span class="hljs-string">'click'</span>, handler);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">removeEventHandler</span>(<span class="hljs-params">element, handler</span>) </span>{
    eventHandlers.delete(handler);
    element.removeEventListener(<span class="hljs-string">'click'</span>, handler);
}
</code></pre>
<h3 id="heading-preventing-object-duplication">Preventing Object Duplication:</h3>
<p>WeakSet can be used to ensure that objects are not duplicated within a collection. Since WeakSet can only hold unique objects, attempting to add the same object multiple times will have no effect.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> uniqueObjects = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addObject</span>(<span class="hljs-params">obj</span>) </span>{
    <span class="hljs-keyword">if</span> (!uniqueObjects.has(obj)) {
        uniqueObjects.add(obj);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Object added:'</span>, obj);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Object already exists:'</span>, obj);
    }
}

<span class="hljs-keyword">const</span> obj1 = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
<span class="hljs-keyword">const</span> obj2 = { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span> };
addObject(obj1); <span class="hljs-comment">// Output: Object added: { id: 1 }</span>
addObject(obj1); <span class="hljs-comment">// Output: Object already exists: { id: 1 }</span>
addObject(obj2); <span class="hljs-comment">// Output: Object added: { id: 2 }</span>
</code></pre>
<h3 id="heading-managing-weak-references-in-caches">Managing Weak References in Caches:</h3>
<p>WeakSet can be used to hold weak references to objects stored in a cache. This allows the cached objects to be garbage collected when they are no longer needed, preventing memory leaks.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> cache = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addToCache</span>(<span class="hljs-params">obj</span>) </span>{
    cache.add(obj);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isCached</span>(<span class="hljs-params">obj</span>) </span>{
    <span class="hljs-keyword">return</span> cache.has(obj);
}

<span class="hljs-keyword">const</span> cachedObj = { <span class="hljs-attr">data</span>: <span class="hljs-string">'cached data'</span> };
addToCache(cachedObj);
<span class="hljs-built_in">console</span>.log(isCached(cachedObj)); <span class="hljs-comment">// Output: true</span>

<span class="hljs-comment">// After removing all references to cachedObj</span>
cachedObj = <span class="hljs-literal">null</span>;
<span class="hljs-built_in">console</span>.log(isCached(cachedObj)); <span class="hljs-comment">// Output: false (cachedObj is garbage collected)</span>
</code></pre>
<h3 id="heading-managing-object-references-in-data-structures">Managing Object References in Data Structures:</h3>
<p>WeakSet can be used to manage object references in various data structures, such as graphs or tree-like structures, where objects may be dynamically added and removed.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> references = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addReference</span>(<span class="hljs-params">obj</span>) </span>{
    references.add(obj);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">removeReference</span>(<span class="hljs-params">obj</span>) </span>{
    references.delete(obj);
}

<span class="hljs-keyword">const</span> obj1 = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
<span class="hljs-keyword">const</span> obj2 = { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span> };
addReference(obj1);
addReference(obj2);
removeReference(obj1);
</code></pre>
<h2 id="heading-methods-of-weakset">Methods of WeakSet</h2>
<p>WeakSet in JavaScript has a limited set of methods compared to other data structures like Set. Here are the methods available for WeakSet:</p>
<h3 id="heading-addvalue"><code>add(value)</code>:</h3>
<p>This method adds the specified value (which must be an object) to the WeakSet. If the value is already present in the WeakSet, the method has no effect.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> weakSet = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>();
<span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
weakSet.add(obj);
</code></pre>
<h3 id="heading-deletevalue"><code>delete(value)</code>:</h3>
<p>This method removes the specified value from the WeakSet, if it exists. It returns <code>true</code> if the value was successfully removed, and <code>false</code> otherwise.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> weakSet = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>();
<span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
weakSet.add(obj);
<span class="hljs-built_in">console</span>.log(weakSet.delete(obj)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<h3 id="heading-hasvalue"><code>has(value)</code>:</h3>
<p>This method checks whether the specified value exists in the WeakSet. It returns <code>true</code> if the value is present, and <code>false</code> otherwise.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> weakSet = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakSet</span>();
<span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span> };
weakSet.add(obj);
<span class="hljs-built_in">console</span>.log(weakSet.has(obj)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>WeakSet does not have methods like <code>values()</code> or <code>forEach()</code> for iteration, nor does it have properties like <code>size</code>. This is because WeakSet is designed for holding weak references to objects, and exposing its contents would interfere with this process. Also, WeakSet does not allow iteration over its values for similar reasons.</p>
<h2 id="heading-weakset-vs-weakmap">WeakSet vs. WeakMap</h2>
<p>Both WeakSet and WeakMap are specialized data structures in JavaScript that hold weak references to objects, but they serve slightly different purposes. </p>
<p>Here's a comparison between the two:</p>
<h3 id="heading-1-purpose">1. Purpose:</h3>
<p><strong>WeakSet:</strong> Designed for storing a collection of objects where each object may occur only once in the set. WeakSet is useful when you need to track the existence of objects without storing additional data associated with them.</p>
<p><strong>WeakMap:</strong> Designed for storing key-value pairs where the keys must be objects and the values can be arbitrary. WeakMap is useful when you need to associate additional data with objects but want to allow those objects to be garbage collected when they are no longer needed.</p>
<h3 id="heading-2-contents">2. Contents:</h3>
<p><strong>WeakSet:</strong> Holds only objects as values. The values in a WeakSet can be checked for existence, but there is no associated data.</p>
<p><strong>WeakMap:</strong> Holds key-value pairs, where the keys must be objects and the values can be any data type. Each key-value pair represents an association between an object and some data.</p>
<h3 id="heading-3-iteration">3. Iteration:</h3>
<p><strong>WeakSet:</strong> Does not support methods like <code>keys()</code>, <code>values()</code>, or <code>forEach()</code>. WeakSet does not allow direct iteration over its values, as exposing the values would interfere with the weak reference mechanism.</p>
<p><strong>WeakMap:</strong> Also does not support methods like <code>keys()</code>, <code>values()</code>, or <code>forEach()</code> for similar reasons. WeakMap does not allow direct iteration over its keys or values to avoid interference with the weak reference mechanism.</p>
<h3 id="heading-4-usage">4. Usage:</h3>
<p><strong>WeakSet:</strong> Commonly used for managing collections of objects, such as tracking event handlers, managing unique object references, or preventing object duplication within a collection.</p>
<p><strong>WeakMap:</strong> Commonly used for associating additional data with objects, such as caching data related to specific objects, storing private data associated with objects, or managing object references in data structures like graphs or trees.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>While familiar data structures like Map and Set excel in JavaScript, WeakMap and WeakSet offer a unique approach. These structures utilize weak references to automatically manage memory associated with objects.</p>
<p>This can be particularly beneficial for short-lived objects or those involved in circular references. </p>
<p>In this article, we explored how to create and use WeakMap and WeakSet, along with their common use cases, empowering you to write cleaner, more memory-efficient JavaScript code.</p>
<p>Connect with me on <a target="_blank" href="https://ng.linkedin.com/in/joan-ayebola">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create Objects in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ In programming, objects are fundamental building blocks used to represent real-world entities or concepts. JavaScript, a versatile and popular language, offers various ways to create these objects.  This article dives deep into these methods, equippi... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-create-objects-in-javascript/</link>
                <guid isPermaLink="false">66c4c3d71b22d2d8d9040eaa</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Fri, 10 May 2024 06:22:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/Ivory-and-Blue-Lavender-Aesthetic-Photo-Collage-Presentation--9-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In programming, objects are fundamental building blocks used to represent real-world entities or concepts. JavaScript, a versatile and popular language, offers various ways to create these objects. </p>
<p>This article dives deep into these methods, equipping you with the knowledge to craft objects tailored to your programming needs.</p>
<p>We'll begin by exploring the concept of objects in JavaScript and the benefits they bring. Then, we'll go through the different creation methods: object literals, constructor functions, and the <code>Object.create()</code> method. Each method will be explained in detail, along with examples to solidify your understanding.</p>
<p>By the end of this comprehensive guide, you'll be able to confidently choose the most suitable approach for creating objects in your JavaScript projects. Not only will you gain the technical know-how, but you'll also discover best practices to ensure your object-oriented code is efficient and well-structured.</p>
<h2 id="heading-table-of-contents">Table of contents</h2>
<ol>
<li><strong><a class="post-section-overview" href="#heading-what-are-objects-in-javascript">What are Objects in JavaScript?</a></strong></li>
<li><p><strong><a class="post-section-overview" href="#heading-how-to-create-objects-with-object-literals">How to Create Objects in JavaScript</a></strong></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-add-properties-and-methods">How to add Properties and Methods</a></p>
</li>
<li><a class="post-section-overview" href="#heading-how-to-nest-objects-and-arrays">How to nest Objects and Arrays</a></li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-a-person-object-example">How to create a Person Object Example</a></p>
</li>
<li><p><strong><a class="post-section-overview" href="#heading-how-to-use-constructor-functions-to-create-objects">How to Use Constructor Functions to Create Objects</a></strong></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-define-a-constructor-function">How to define a Constructor Function</a></p>
</li>
<li><a class="post-section-overview" href="#how-to-use-the-new-keyword-">How to use the <code>new</code> Keyword</a></li>
<li><a class="post-section-overview" href="#heading-how-to-add-properties-and-methods-to-the-prototype">How to add Properties and Methods to the Prototype</a></li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-a-handbag-object-example">How to create a Handbag Object Example</a></p>
</li>
<li><p><strong><a class="post-section-overview" href="#heading-how-to-use-the-objectcreate-method-to-create-objects">How to Use the <code>Object.create()</code> Method to Create Objects</a></strong></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-specify-a-prototype-object">How to specify a Prototype Object</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-an-object-with-a-specific-prototype-example">How to create an Object with a specific Prototype Example</a></p>
</li>
<li><p><strong><a class="post-section-overview" href="#heading-why-create-objects-in-javascript">Why Create Objects in JavaScript?</a></strong></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-choose-the-right-method-for-creating-objects-in-javascript">How to Choose the Right Method for Creating Objects</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-object-literals">When to use Object Literals</a></p>
</li>
<li><a class="post-section-overview" href="#heading-when-to-use-constructor-functions-and-classes">When to use Constructor Functions and Classes</a></li>
<li><a class="post-section-overview" href="#heading-when-to-use-objectcreate">When to Use <code>Object.create()</code></a></li>
<li><p><a class="post-section-overview" href="#heading-example-scenarios">Example Scenarios</a></p>
</li>
<li><p><strong><a class="post-section-overview" href="#heading-best-practices-for-object-creation-in-javascript">Best Practices for Object Creation in JavaScript</a></strong></p>
</li>
<li><p><strong><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></strong></p>
</li>
</ol>
<h2 id="heading-what-are-objects-in-javascript">What are Objects in JavaScript?</h2>
<p>In JavaScript, objects are data structures that store collections of related data and functionality. They are made up of key-value pairs, where each key is a string (or symbol) and each value can be any data type, including other objects, arrays, functions, and more. </p>
<p>Objects are versatile and commonly used to represent real-world entities or concepts in code. </p>
<h2 id="heading-how-to-create-objects-with-object-literals">How to Create Objects with Object Literals</h2>
<p>In JavaScript, you can create objects using object literals. The syntax for creating an object literal is as follows:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> objectName = {
  <span class="hljs-attr">key1</span>: value1,
  <span class="hljs-attr">key2</span>: value2,
  <span class="hljs-comment">// More key-value pairs as needed</span>
};
</code></pre>
<ul>
<li><code>objectName</code>: This is the name you assign to your object variable.</li>
<li><code>{ key1: value1, key2: value2 }</code>: This part is enclosed in curly braces <code>{}</code> and represents the object literal. Each key-value pair is separated by a colon <code>:</code> and individual pairs are separated by commas <code>,</code>.</li>
</ul>
<h3 id="heading-how-to-add-properties-and-methods">How to add Properties and Methods</h3>
<p>You can add properties and methods to your object literal by specifying them as key-value pairs. Properties hold data values, while methods are functions associated with the object:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> objectName = {
  <span class="hljs-attr">property1</span>: value1,
  <span class="hljs-attr">property2</span>: value2,
  <span class="hljs-attr">method1</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Method definition</span>
  }
};
</code></pre>
<h3 id="heading-how-to-nest-objects-and-arrays">How to nest Objects and Arrays</h3>
<p>You can nest objects and arrays within an object literal to create more complex data structures:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> objectName = {
  <span class="hljs-attr">property1</span>: value1,
  <span class="hljs-attr">nestedObject</span>: {
    <span class="hljs-attr">nestedProperty</span>: nestedValue
  },
  <span class="hljs-attr">nestedArray</span>: [item1, item2, item3]
};
</code></pre>
<h3 id="heading-how-to-create-a-person-object-example">How to create a Person Object Example</h3>
<p>Let's create an example of a person object using object literals:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Creating a person object</span>
<span class="hljs-keyword">let</span> person = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Bella Nwachukwu"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">29</span>,
  <span class="hljs-attr">address</span>: {
    <span class="hljs-attr">street</span>: <span class="hljs-string">"123 Ade Street"</span>,
    <span class="hljs-attr">city</span>: <span class="hljs-string">"Lagos"</span>,
    <span class="hljs-attr">zip</span>: <span class="hljs-string">"10001"</span>
  },
  <span class="hljs-attr">hobbies</span>: [<span class="hljs-string">"reading"</span>, <span class="hljs-string">"traveling"</span>, <span class="hljs-string">"coding"</span>],
  <span class="hljs-attr">greet</span>: <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-string">"Hello, my name is "</span> + <span class="hljs-built_in">this</span>.name + <span class="hljs-string">" and I am "</span> + <span class="hljs-built_in">this</span>.age + <span class="hljs-string">" years old."</span>;
  }
};

<span class="hljs-comment">// Accessing properties and method of the person object</span>
<span class="hljs-built_in">console</span>.log(person.name); <span class="hljs-comment">// Output: Bella Nwachukwu</span>
<span class="hljs-built_in">console</span>.log(person.address.city); <span class="hljs-comment">// Output: Lagos</span>
<span class="hljs-built_in">console</span>.log(person.hobbies[<span class="hljs-number">0</span>]); <span class="hljs-comment">// Output: reading</span>
<span class="hljs-built_in">console</span>.log(person.greet()); <span class="hljs-comment">// Output: Hello, my name is Bella Nwachukwu and I am 29 years old.</span>
</code></pre>
<p>In this example:</p>
<ul>
<li>We've created a <code>person</code> object with properties like <code>name</code>, <code>age</code>, <code>address</code>, <code>hobbies</code>, and a method <code>greet</code>.</li>
<li>The <code>address</code> property is itself an object with nested properties.</li>
<li>The <code>hobbies</code> property is an array containing multiple items.</li>
<li>The <code>greet</code> method returns a greeting message using the person's name and age.</li>
</ul>
<h2 id="heading-how-to-use-constructor-functions-to-create-objects">How to Use Constructor Functions to Create Objects</h2>
<h3 id="heading-how-to-define-a-constructor-function">How to define a Constructor Function</h3>
<p>A constructor function is a JavaScript function that is used to create and initialize objects. It serves as a blueprint for creating multiple objects with similar properties and methods:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ConstructorName</span>(<span class="hljs-params">param1, param2</span>) </span>{
  <span class="hljs-built_in">this</span>.property1 = param1;
  <span class="hljs-built_in">this</span>.property2 = param2;
  <span class="hljs-comment">// Additional properties and methods as needed</span>
}
</code></pre>
<ul>
<li><code>ConstructorName</code>: This is the name you assign to your constructor function.</li>
<li><code>param1, param2</code>: These are parameters that the constructor function accepts to initialize the object properties.</li>
</ul>
<h3 id="heading-how-to-use-the-new-keyword">How to use the <code>new</code> Keyword</h3>
<p>You can create an instance of an object using the <code>new</code> keyword followed by the constructor function name and passing any required parameters.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> instanceName = <span class="hljs-keyword">new</span> ConstructorName(value1, value2);
</code></pre>
<ul>
<li><code>instanceName</code>: This is the variable name assigned to the newly created object instance.</li>
</ul>
<h3 id="heading-how-to-add-properties-and-methods-to-the-prototype">How to add Properties and Methods to the Prototype</h3>
<p>To add properties and methods shared across all instances of objects created from the constructor function, you can use the prototype property of the constructor function:</p>
<pre><code class="lang-javascript">ConstructorName.prototype.methodName = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Method definition</span>
};
</code></pre>
<h3 id="heading-how-to-create-a-handbag-object-example">How to create a Handbag Object Example</h3>
<p>Let's create an example using a constructor function to represent a <code>Handbag</code> object, as handbags are something I love:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Define the constructor function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Handbag</span>(<span class="hljs-params">brand, color, price</span>) </span>{
  <span class="hljs-built_in">this</span>.brand = brand;
  <span class="hljs-built_in">this</span>.color = color;
  <span class="hljs-built_in">this</span>.price = price;
}

<span class="hljs-comment">// Add a method to the prototype</span>
Handbag.prototype.getDescription = <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-string">"A "</span> + <span class="hljs-built_in">this</span>.color + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.brand + <span class="hljs-string">" handbag, priced at $"</span> + <span class="hljs-built_in">this</span>.price + <span class="hljs-string">"."</span>;
};

<span class="hljs-comment">// Create an instance of the Handbag object</span>
<span class="hljs-keyword">let</span> myHandbag = <span class="hljs-keyword">new</span> Handbag(<span class="hljs-string">'Louis Vuitton'</span>, <span class="hljs-string">'brown'</span>, <span class="hljs-number">2000</span>);

<span class="hljs-comment">// Accessing properties and method of the handbag object</span>
<span class="hljs-built_in">console</span>.log(myHandbag.brand); <span class="hljs-comment">// Output: Louis Vuitton</span>
<span class="hljs-built_in">console</span>.log(myHandbag.getDescription()); <span class="hljs-comment">// Output: A brown Louis Vuitton handbag, priced at $2000.</span>
</code></pre>
<p>In this example:</p>
<ul>
<li>We define a <code>Handbag</code> constructor function that accepts <code>brand</code>, <code>color</code>, and <code>price</code> parameters to initialize handbag objects.</li>
<li>We add a <code>getDescription</code> method to the prototype of the <code>Handbag</code> constructor function to return a description of the handbag.</li>
<li>We create an instance of the <code>Handbag</code> object named <code>myHandbag</code> using the <code>new</code> keyword and provide values for the parameters.</li>
<li>We then access the properties and method of the <code>myHandbag</code> object using dot notation.</li>
</ul>
<h2 id="heading-how-to-use-the-objectcreate-method-to-create-objects">How to Use the <code>Object.create()</code> Method to Create Objects</h2>
<p>The <code>Object.create()</code> method is used to create a new object with the specified prototype object and optionally additional properties. Its syntax is as follows:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Object</span>.create(proto[, propertiesObject])
</code></pre>
<ul>
<li><code>proto</code>: The prototype object to use for creating the new object. It can be <code>null</code> or an object.</li>
<li><code>propertiesObject</code> (optional): An object whose properties define additional properties to be added to the newly created object. Properties of this object correspond to the properties to be added to the created object, with their values being property descriptors.</li>
</ul>
<h3 id="heading-how-to-specify-a-prototype-object">How to specify a Prototype Object</h3>
<p>By passing a prototype object as the first argument to <code>Object.create()</code>, you can specify the prototype of the newly created object. </p>
<p>The prototype object serves as a template from which the new object inherits properties.</p>
<h3 id="heading-how-to-create-an-object-with-a-specific-prototype-example">How to create an Object with a specific Prototype Example</h3>
<p>Let's create an example of using <code>Object.create()</code> to create an object with a specific prototype:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Define a prototype object</span>
<span class="hljs-keyword">let</span> personPrototype = {
  <span class="hljs-attr">greet</span>: <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-string">"Hello, my name is "</span> + <span class="hljs-built_in">this</span>.name + <span class="hljs-string">"."</span>;
  }
};

<span class="hljs-comment">// Create a new object using the personPrototype as its prototype</span>
<span class="hljs-keyword">let</span> john = <span class="hljs-built_in">Object</span>.create(personPrototype);

<span class="hljs-comment">// Add properties to the new object</span>
john.name = <span class="hljs-string">"John"</span>;

<span class="hljs-comment">// Accessing properties and method of the john object</span>
<span class="hljs-built_in">console</span>.log(john.name); <span class="hljs-comment">// Output: John</span>
<span class="hljs-built_in">console</span>.log(john.greet()); <span class="hljs-comment">// Output: Hello, my name is John.</span>
</code></pre>
<p>In this example:</p>
<ul>
<li>We define a <code>personPrototype</code> object with a <code>greet</code> method.</li>
<li>We create a new object named <code>john</code> using <code>Object.create(personPrototype)</code>, which sets <code>personPrototype</code> as the prototype of <code>john</code>.</li>
<li>We add a <code>name</code> property to the <code>john</code> object.</li>
<li>We then access the properties and method of the <code>john</code> object using dot notation.</li>
</ul>
<h2 id="heading-why-create-objects-in-javascript">Why Create Objects in JavaScript?</h2>
<p>Creating objects in JavaScript allows you to organize and manage data in a structured way. Here are a few reasons why creating objects is beneficial:</p>
<ul>
<li><strong>Organization</strong>: Objects help organize related data and functionality into a single entity. For example, if you're working with information about a person, you can store their name, age, address, and other details within a single object.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example of organizing related data into an object</span>
<span class="hljs-keyword">let</span> person = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>,
  <span class="hljs-attr">address</span>: {
    <span class="hljs-attr">street</span>: <span class="hljs-string">"123 Main St"</span>,
    <span class="hljs-attr">city</span>: <span class="hljs-string">"New York"</span>,
    <span class="hljs-attr">zip</span>: <span class="hljs-string">"10001"</span>
  }
};

<span class="hljs-comment">// Accessing properties of the person object</span>
<span class="hljs-built_in">console</span>.log(person.name); <span class="hljs-comment">// Output: John Doe</span>
<span class="hljs-built_in">console</span>.log(person.address.city); <span class="hljs-comment">// Output: New York</span>
</code></pre>
<ul>
<li><strong>Encapsulation</strong>: Objects encapsulate data and related behavior, which promotes cleaner and more modular code. Instead of having scattered variables and functions, you can group them together within an object, making your code easier to understand and maintain.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example of encapsulating data and behavior within an object</span>
<span class="hljs-keyword">let</span> calculator = {
  <span class="hljs-attr">add</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">return</span> a + b;
  },
  <span class="hljs-attr">subtract</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">return</span> a - b;
  }
};

<span class="hljs-comment">// Using the calculator object to perform calculations</span>
<span class="hljs-built_in">console</span>.log(calculator.add(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// Output: 8</span>
<span class="hljs-built_in">console</span>.log(calculator.subtract(<span class="hljs-number">10</span>, <span class="hljs-number">4</span>)); <span class="hljs-comment">// Output: 6</span>
</code></pre>
<ul>
<li><strong>Reusability</strong>: Once you've created an object, you can reuse it throughout your codebase. This saves you from writing repetitive code and promotes code reuse, which is a fundamental principle of good software engineering.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example of reusing an object definition multiple times</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createPerson</span>(<span class="hljs-params">name, age</span>) </span>{
  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">name</span>: name,
    <span class="hljs-attr">age</span>: age,
    <span class="hljs-attr">greet</span>: <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-string">"Hello, my name is "</span> + <span class="hljs-built_in">this</span>.name + <span class="hljs-string">" and I am "</span> + <span class="hljs-built_in">this</span>.age + <span class="hljs-string">" years old."</span>;
    }
  };
}

<span class="hljs-keyword">let</span> person1 = createPerson(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">30</span>);
<span class="hljs-keyword">let</span> person2 = createPerson(<span class="hljs-string">"Bob"</span>, <span class="hljs-number">25</span>);

<span class="hljs-built_in">console</span>.log(person1.greet()); <span class="hljs-comment">// Output: Hello, my name is Alice and I am 30 years old.</span>
<span class="hljs-built_in">console</span>.log(person2.greet()); <span class="hljs-comment">// Output: Hello, my name is Bob and I am 25 years old.</span>
</code></pre>
<ul>
<li><strong>Flexibility</strong>: Objects in JavaScript are dynamic, meaning you can easily add, modify, or remove properties and methods at runtime. This flexibility allows you to adapt your code to changing requirements or scenarios without much hassle.</li>
<li><strong>Passing by Reference</strong>: Objects are passed by reference in JavaScript, which means when you assign an object to a variable or pass it as an argument to a function, you're actually passing a reference to the same object in memory. This can be useful for working with complex data structures or implementing advanced programming techniques.</li>
</ul>
<h2 id="heading-how-to-choose-the-right-method-for-creating-objects-in-javascript">How to Choose the Right Method for Creating Objects in JavaScript</h2>
<p>This depends on various factors, including the complexity of your application, your coding style preferences, and the specific requirements of your project. Here's a general guideline on when to use each method:</p>
<h3 id="heading-when-to-use-object-literals">When to use Object Literals</h3>
<p>Use object literals when you need a simple and straightforward way to create objects with a fixed set of properties and methods. Object literals are ideal for:</p>
<ul>
<li>Creating small, one-off objects.</li>
<li>Defining configuration objects.</li>
<li>Creating objects with a known structure that won't change frequently.</li>
</ul>
<h3 id="heading-when-to-use-constructor-functions-and-classes">When to use Constructor Functions and Classes</h3>
<p>Use constructor functions and ES6 classes when you need to create multiple instances of objects with shared properties and methods. Constructor functions and classes are suitable for:</p>
<ul>
<li>Creating objects with behavior and state.</li>
<li>Implementing inheritance and polymorphism.</li>
<li>Creating reusable components and modules.</li>
<li>Organizing code in a more object-oriented manner.</li>
</ul>
<h3 id="heading-when-to-use-objectcreate">When to Use <code>Object.create()</code></h3>
<p>Use <code>Object.create()</code> when you need finer control over the prototype chain or when you want to create objects with specific prototypes. <code>Object.create()</code> is suitable for:</p>
<ul>
<li>Creating objects with a specific prototype without invoking a constructor function.</li>
<li>Implementing prototype-based inheritance.</li>
<li>Creating objects with shared properties and methods.</li>
</ul>
<h3 id="heading-example-scenarios">Example Scenarios</h3>
<ul>
<li><strong>Object Literals</strong>: Use when creating a configuration object for a small utility function:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> config = {
  <span class="hljs-attr">apiUrl</span>: <span class="hljs-string">"https://example.com/api"</span>,
  <span class="hljs-attr">timeout</span>: <span class="hljs-number">5000</span>
};
</code></pre>
<ul>
<li><strong>Constructor Functions and Classes</strong>: Use when creating instances of complex objects with behavior:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  <span class="hljs-keyword">constructor</span>(name, age) {
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-built_in">this</span>.age = age;
  }

  greet() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Hello, my name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> and I am <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old.`</span>;
  }
}

<span class="hljs-keyword">let</span> person1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">30</span>);
</code></pre>
<ul>
<li><strong>Object.create()</strong>: Use when creating objects with specific prototypes:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> animal = {
  speak() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Some sound"</span>;
  }
};

<span class="hljs-keyword">let</span> dog = <span class="hljs-built_in">Object</span>.create(animal);
dog.breed = <span class="hljs-string">"Labrador"</span>;
</code></pre>
<h2 id="heading-best-practices-for-object-creation-in-javascript">Best Practices for Object Creation in JavaScript</h2>
<h3 id="heading-1-use-object-literals-for-simple-structures">1. Use Object Literals for Simple Structures</h3>
<p>For simple data structures with a fixed set of properties, use object literals. They provide a concise syntax for defining objects.</p>
<h3 id="heading-2-prefer-constructor-functions-or-classes-for-complex-objects">2. Prefer Constructor Functions or Classes for Complex Objects</h3>
<p>For objects with behavior and shared properties, use constructor functions or ES6 classes. They allow for encapsulation, inheritance, and polymorphism.</p>
<h3 id="heading-3-favor-classes-for-modern-javascript">3. Favor Classes for Modern JavaScript</h3>
<p>In modern JavaScript, ES6 classes provide a cleaner syntax for defining object blueprints. They are easier to understand and maintain compared to traditional constructor functions.</p>
<h3 id="heading-4-use-factory-functions-for-object-creation">4. Use Factory Functions for Object Creation</h3>
<p>Factory functions are functions that return new objects. They provide a way to encapsulate object creation logic and allow for more flexibility in creating instances.</p>
<h3 id="heading-5-use-objectcreate-for-explicit-prototypal-inheritance">5. Use <code>Object.create()</code> for Explicit Prototypal Inheritance</h3>
<p>Use <code>Object.create()</code> when you need to explicitly define the prototype chain or create objects with specific prototypes. This is particularly useful for prototype-based inheritance.</p>
<h3 id="heading-6-encapsulate-initialization-logic">6. Encapsulate Initialization Logic</h3>
<p>If an object requires complex initialization logic, encapsulate it within the constructor function or a factory function to keep the object creation process clean and understandable.</p>
<h3 id="heading-7-avoid-excessive-mutation">7. Avoid Excessive Mutation</h3>
<p>Minimize direct mutation of object properties, especially shared objects. Instead, favor immutability or use techniques like getters and setters for controlled access.</p>
<h3 id="heading-8-follow-naming-conventions">8. Follow Naming Conventions</h3>
<p>Follow naming conventions for constructor functions, classes, and factory functions. Use PascalCase for constructor functions and classes, and camelCase for factory functions.</p>
<h3 id="heading-9-favor-composition-over-inheritance">9. Favor Composition over Inheritance</h3>
<p>Prefer composition over inheritance when structuring complex objects. Composition promotes code reuse and is often more flexible than inheritance.</p>
<h3 id="heading-10-document-object-structures-and-behavior">10. Document Object Structures and Behavior</h3>
<p>Document the structure and behavior of your objects, including properties, methods, and their intended usage. This helps other developers understand and use your code effectively.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, we've explored object literals, constructor functions, the <code>Object.create()</code> method, and ES6 classes, each with its strengths and use cases.</p>
<p>Now, you can strategically choose the right approach to object-oriented structures in your JavaScript applications.</p>
<p>Remember, object literals excel at creating simple objects, while constructor functions and classes are ideal for reusable object blueprints with shared properties and methods. The <code>Object.create()</code> method offers more granular control over object inheritance.</p>
<p>Keep these best practices in mind, leverage object properties and methods effectively, prioritize code readability, and don't hesitate to revisit this guide as a reference. </p>
<p>Connect with me on <a target="_blank" href="https://ng.linkedin.com/in/joan-ayebola">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are Higher Order Functions in JavaScript? Explained With Examples ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript offers a powerful feature known as higher order functions (HOFs). These functions elevate your code by treating other functions as citizens of the language itself.  In simpler terms, HOFs can accept functions as arguments and even return f... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/higher-order-functions-explained/</link>
                <guid isPermaLink="false">66c4c3d1d788a9c53d88d2be</guid>
                
                    <category>
                        <![CDATA[ functions ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Thu, 02 May 2024 18:31:54 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/Ivory-and-Blue-Lavender-Aesthetic-Photo-Collage-Presentation--7-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript offers a powerful feature known as higher order functions (HOFs). These functions elevate your code by treating other functions as citizens of the language itself.  In simpler terms, HOFs can accept functions as arguments and even return functions as results. This ability allows developers to write clean, reusable, and expressive code.</p>
<p>This article comprehensively discusses higher order functions in JavaScript. We'll begin by establishing a clear understanding of HOFs, their core concepts, and the advantages they bring to your development process.  We'll then explore some of the most commonly used HOFs in JavaScript, like <code>map</code>, <code>filter</code>, and <code>reduce</code>, providing detailed explanations, syntax breakdowns, and practical examples to solidify your grasp.</p>
<h2 id="heading-what-are-higher-order-functions">What are Higher Order Functions?</h2>
<p>Higher order functions (HOFs) in JavaScript are functions that can do at least one of the following:</p>
<ul>
<li>Accept other functions as arguments.</li>
<li>Return a function as a result.</li>
</ul>
<h2 id="heading-core-concepts-of-higher-order-functions">Core concepts of Higher Order Functions</h2>
<h3 id="heading-1-accepting-functions-as-arguments">1. Accepting Functions as Arguments</h3>
<p>Higher order functions can accept other functions as arguments. This allows for dynamic behavior, where the behavior of the higher order function can be customized based on the function passed as an argument.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Higher Order Function that accepts a callback function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">higherOrderFunction</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-comment">// Performing some operations</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Executing the higher order function..."</span>);

  <span class="hljs-comment">// Calling the callback function</span>
  callback();
}

<span class="hljs-comment">// Callback function to be passed to the higher order function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callbackFunction</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Executing the callback function..."</span>);
}

<span class="hljs-comment">// Calling the higher order function with the callback function as argument</span>
higherOrderFunction(callbackFunction);
</code></pre>
<p>In this example, <code>higherOrderFunction</code> is a higher order function that accepts another function (<code>callback</code>) as an argument. When <code>higherOrderFunction</code> is called, it executes some operations and then calls the <code>callback</code> function passed to it. This allows for customizing the behavior of <code>higherOrderFunction</code> by passing different callback functions.</p>
<h3 id="heading-2-returning-functions">2. Returning Functions</h3>
<p>Higher order functions can also return functions. This enables the creation of functions dynamically based on certain conditions or parameters.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Higher Order Function that returns a function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createGreeter</span>(<span class="hljs-params">greeting</span>) </span>{
  <span class="hljs-comment">// Returning a new function</span>
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${greeting}</span>, <span class="hljs-subst">${name}</span>!`</span>);
  };
}

<span class="hljs-comment">// Creating a greeter function with a specific greeting</span>
<span class="hljs-keyword">const</span> greetHello = createGreeter(<span class="hljs-string">"Hello"</span>);
greetHello(<span class="hljs-string">"John"</span>); <span class="hljs-comment">// Output: Hello, John!</span>

<span class="hljs-comment">// Creating another greeter function with a different greeting</span>
<span class="hljs-keyword">const</span> greetGoodbye = createGreeter(<span class="hljs-string">"Goodbye"</span>);
greetGoodbye(<span class="hljs-string">"Alice"</span>); <span class="hljs-comment">// Output: Goodbye, Alice!</span>
</code></pre>
<p>In this example, <code>createGreeter</code> is a higher order function that returns a new function. The returned function (<code>greetHello</code> and <code>greetGoodbye</code>) takes a <code>name</code> parameter and logs a greeting message with the specified greeting passed to <code>createGreeter</code>. This allows for creating different greeter functions with different greetings dynamically.</p>
<h3 id="heading-3-abstraction">3. Abstraction</h3>
<p>Higher order functions promote abstraction by encapsulating common patterns or behaviors into reusable functions. This leads to cleaner and more modular code.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Higher Order Function for performing a specified operation on each element of an array</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">performOperationOnArray</span>(<span class="hljs-params">array, operation</span>) </span>{
  <span class="hljs-keyword">return</span> array.map(operation);
}

<span class="hljs-comment">// Callback function for doubling each element of an array</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">double</span>(<span class="hljs-params">number</span>) </span>{
  <span class="hljs-keyword">return</span> number * <span class="hljs-number">2</span>;
}

<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> doubledNumbers = performOperationOnArray(numbers, double);
<span class="hljs-built_in">console</span>.log(doubledNumbers); <span class="hljs-comment">// Output: [2, 4, 6, 8, 10]</span>
</code></pre>
<p>In this example, <code>performOperationOnArray</code> is a higher order function that accepts an array and an <code>operation</code> function as arguments. It then applies the <code>operation</code> function to each element of the array using the <code>map</code> method and returns the result. This promotes code reusability and abstraction by allowing different operations to be performed on arrays without having to rewrite the logic for iterating over the array.</p>
<h2 id="heading-why-use-higher-order-functions">Why use Higher Order Functions?</h2>
<p>Using HOFs in JavaScript provides several advantages that can enhance the flexibility, reusability, and maintainability of your codebase. Let's explore these benefits:</p>
<h3 id="heading-code-reusability">Code Reusability</h3>
<p>HOFs promote code reusability by allowing you to abstract common patterns into reusable functions. This reduces code duplication and makes your codebase more maintainable.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: HOF for filtering elements based on a condition</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">filterArray</span>(<span class="hljs-params">array, condition</span>) </span>{
  <span class="hljs-keyword">return</span> array.filter(condition);
}

<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-comment">// Using filterArray to filter even numbers</span>
<span class="hljs-keyword">const</span> evenNumbers = filterArray(numbers, <span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(evenNumbers); <span class="hljs-comment">// Output: [2, 4]</span>
</code></pre>
<p>Instead of writing a custom filtering logic each time, you can create a reusable <code>filterArray</code> function that accepts an array and a condition function. This promotes code reusability as you can use <code>filterArray</code> with different conditions to filter arrays based on various criteria.</p>
<h3 id="heading-modularity">Modularity</h3>
<p>HOFs help in breaking down complex tasks into smaller, more manageable functions, promoting modular code design.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: HOF for performing a series of operations on an array</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processArray</span>(<span class="hljs-params">array, operations</span>) </span>{
  <span class="hljs-keyword">return</span> operations.reduce(<span class="hljs-function">(<span class="hljs-params">acc, operation</span>) =&gt;</span> operation(acc), array);
}

<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-comment">// Using processArray to perform multiple operations</span>
<span class="hljs-keyword">const</span> result = processArray(numbers, [
  <span class="hljs-function"><span class="hljs-params">arr</span> =&gt;</span> arr.map(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num * <span class="hljs-number">2</span>),
  <span class="hljs-function"><span class="hljs-params">arr</span> =&gt;</span> arr.filter(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num % <span class="hljs-number">3</span> === <span class="hljs-number">0</span>)
]);
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: [6]</span>
</code></pre>
<p>By encapsulating individual operations as functions and passing them to a higher-order function like <code>processArray</code>, you can break down complex tasks into smaller, more manageable units. This promotes modular code design, making your codebase easier to understand, maintain, and extend.</p>
<h3 id="heading-flexibility">Flexibility</h3>
<p>HOFs allow for dynamic behavior by accepting functions as arguments or returning functions as results. This flexibility enables you to customize the behavior of a function at runtime.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: HOF for creating a multiplier function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createMultiplier</span>(<span class="hljs-params">factor</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">number</span>) </span>{
    <span class="hljs-keyword">return</span> number * factor;
  };
}

<span class="hljs-keyword">const</span> double = createMultiplier(<span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(double(<span class="hljs-number">5</span>)); <span class="hljs-comment">// Output: 10</span>
</code></pre>
<p>By returning a function from <code>createMultiplier</code>, you can dynamically generate a new function with a specific multiplication factor. This provides flexibility as you can create multiple multiplier functions with different factors without having to redefine the logic each time.</p>
<h2 id="heading-popular-higher-order-functions-in-javascript">Popular Higher Order Functions in JavaScript</h2>
<p>Let's explore the popular higher order functions in JavaScript along with their descriptions, syntax, and practical usage examples:</p>
<h3 id="heading-1-arrayprototypemap">1. Array.prototype.map()</h3>
<p>The <code>map()</code> method creates a new array by calling a provided function on every element in the calling array.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newArray = array.map(callback(currentValue, index, array));
</code></pre>
<p><strong>Usage:</strong></p>
<ul>
<li>Iterating over arrays and transforming elements.</li>
</ul>
<p><strong>Examples:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Doubling each number in an array</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> doubledNumbers = numbers.map(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num * <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(doubledNumbers); <span class="hljs-comment">// Output: [2, 4, 6, 8, 10]</span>

<span class="hljs-comment">// Example 2: Converting an array of strings to uppercase</span>
<span class="hljs-keyword">const</span> words = [<span class="hljs-string">"hello"</span>, <span class="hljs-string">"world"</span>, <span class="hljs-string">"javascript"</span>];
<span class="hljs-keyword">const</span> uppercaseWords = words.map(<span class="hljs-function"><span class="hljs-params">word</span> =&gt;</span> word.toUpperCase());
<span class="hljs-built_in">console</span>.log(uppercaseWords); <span class="hljs-comment">// Output: ["HELLO", "WORLD", "JAVASCRIPT"]</span>
</code></pre>
<h3 id="heading-2-arrayprototypefilter">2. Array.prototype.filter()</h3>
<p>The <code>filter()</code> method creates a new array with all elements that pass the test implemented by the provided function.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newArray = array.filter(callback(element, index, array));
</code></pre>
<p><strong>Usage:</strong></p>
<ul>
<li>Creating new arrays based on specific conditions.</li>
</ul>
<p><strong>Examples:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Filtering even numbers from an array</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> evenNumbers = numbers.filter(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(evenNumbers); <span class="hljs-comment">// Output: [2, 4]</span>

<span class="hljs-comment">// Example 2: Filtering words longer than 5 characters</span>
<span class="hljs-keyword">const</span> words = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"grape"</span>, <span class="hljs-string">"kiwi"</span>, <span class="hljs-string">"orange"</span>];
<span class="hljs-keyword">const</span> longWords = words.filter(<span class="hljs-function"><span class="hljs-params">word</span> =&gt;</span> word.length &gt; <span class="hljs-number">5</span>);
<span class="hljs-built_in">console</span>.log(longWords); <span class="hljs-comment">// Output: ["banana", "orange"]</span>
</code></pre>
<h3 id="heading-3-arrayprototypereduce">3. Array.prototype.reduce()</h3>
<p>The <code>reduce()</code> method applies a function against an accumulator and each element in the array to reduce it to a single value.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> result = array.reduce(callback(accumulator, currentValue, index, array), initialValue);
</code></pre>
<p><strong>Usage:</strong></p>
<ul>
<li>Accumulating a single value from an array.</li>
</ul>
<p><strong>Examples:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Finding the sum of numbers in an array</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> sum = numbers.reduce(<span class="hljs-function">(<span class="hljs-params">acc, num</span>) =&gt;</span> acc + num, <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(sum); <span class="hljs-comment">// Output: 15</span>

<span class="hljs-comment">// Example 2: Finding the average of numbers in an array</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>, <span class="hljs-number">50</span>];
<span class="hljs-keyword">const</span> average = numbers.reduce(<span class="hljs-function">(<span class="hljs-params">acc, num, index, array</span>) =&gt;</span> {
  acc += num;
  <span class="hljs-keyword">if</span> (index === array.length - <span class="hljs-number">1</span>) {
    <span class="hljs-keyword">return</span> acc / array.length;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> acc;
  }
}, <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(average); <span class="hljs-comment">// Output: 30</span>
</code></pre>
<h3 id="heading-4-arrayprototypeforeach">4. Array.prototype.forEach()</h3>
<p>The <code>forEach()</code> method executes a provided function once for each array element.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript">array.forEach(callback(currentValue, index, array));
</code></pre>
<p><strong>Usage:</strong></p>
<ul>
<li>Iterating over arrays and performing side effects (e.g., logging).</li>
</ul>
<p><strong>Examples:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Logging each element of an array</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
numbers.forEach(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(num));

<span class="hljs-comment">// Example 2: Capitalizing and logging each word of an array</span>
<span class="hljs-keyword">const</span> words = [<span class="hljs-string">"hello"</span>, <span class="hljs-string">"world"</span>, <span class="hljs-string">"javascript"</span>];
words.forEach(<span class="hljs-function"><span class="hljs-params">word</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(word.toUpperCase()));
</code></pre>
<h3 id="heading-5-arrayprototypesome">5. Array.prototype.some()</h3>
<p>The <code>some()</code> method tests whether at least one element in the array passes the test implemented by the provided function.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> result = array.some(callback(element, index, array));
</code></pre>
<p><strong>Usage:</strong></p>
<ul>
<li>Checking if at least one element in an array meets a condition.</li>
</ul>
<p><strong>Examples:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Checking if any number in the array is greater than 10</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">5</span>, <span class="hljs-number">8</span>, <span class="hljs-number">12</span>, <span class="hljs-number">7</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> isAnyNumberGreaterThan10 = numbers.some(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num &gt; <span class="hljs-number">10</span>);
<span class="hljs-built_in">console</span>.log(isAnyNumberGreaterThan10); <span class="hljs-comment">// Output: true</span>

<span class="hljs-comment">// Example 2: Checking if any word in the array starts with "a"</span>
<span class="hljs-keyword">const</span> words = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"grape"</span>, <span class="hljs-string">"kiwi"</span>, <span class="hljs-string">"orange"</span>];
<span class="hljs-keyword">const</span> startsWithA = words.some(<span class="hljs-function"><span class="hljs-params">word</span> =&gt;</span> word.startsWith(<span class="hljs-string">"a"</span>));
<span class="hljs-built_in">console</span>.log(startsWithA); <span class="hljs-comment">// Output: true</span>
</code></pre>
<h3 id="heading-6-arrayprototypeevery">6. Array.prototype.every()</h3>
<p>The <code>every()</code> method tests whether all elements in the array pass the test implemented by the provided function.</p>
<p><strong>Syntax:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> result = array.every(callback(element, index, array));
</code></pre>
<p><strong>Usage:</strong></p>
<ul>
<li>Checking if all elements in an array meet a condition.</li>
</ul>
<p><strong>Examples:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 1: Checking if all numbers in the array are positive</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">5</span>, <span class="hljs-number">8</span>, <span class="hljs-number">12</span>, <span class="hljs-number">7</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> areAllNumbersPositive = numbers.every(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num &gt; <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(areAllNumbersPositive); <span class="hljs-comment">// Output: true</span>

<span class="hljs-comment">// Example 2: Checking if all words in the array have length greater than 3</span>
<span class="hljs-keyword">const</span> words = [<span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"grape"</span>, <span class="hljs-string">"kiwi"</span>, <span class="hljs-string">"orange"</span>];
<span class="hljs-keyword">const</span> allWordsHaveLengthGreaterThan3 = words.every(<span class="hljs-function"><span class="hljs-params">word</span> =&gt;</span> word.length &gt; <span class="hljs-number">3</span>);
<span class="hljs-built_in">console</span>.log(allWordsHaveLengthGreaterThan3); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>These popular higher order functions in JavaScript provide powerful tools for working with arrays, enabling you to perform various operations such as mapping, filtering, reducing, iterating, and checking conditions with ease and flexibility.</p>
<h2 id="heading-advanced-techniques-with-higher-order-functions">Advanced Techniques with Higher Order Functions</h2>
<h3 id="heading-1-function-composition-chaining-hofs">1. Function Composition (Chaining HOFs)</h3>
<p>Function composition involves chaining multiple higher order functions together to create more complex operations or transformations.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-comment">// Chaining map() and filter() to get even numbers squared</span>
<span class="hljs-keyword">const</span> result = numbers
  .filter(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>) <span class="hljs-comment">// Filter even numbers</span>
  .map(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num * num); <span class="hljs-comment">// Square each number</span>
<span class="hljs-built_in">console</span>.log(result); <span class="hljs-comment">// Output: [4, 16]</span>
</code></pre>
<p>In this example, we chained the <code>filter()</code> and <code>map()</code> functions together. First, <code>filter()</code> is used to filter out even numbers, and then <code>map()</code> squares each of the filtered numbers. This creates a pipeline of operations, allowing us to perform complex transformations in a concise and readable manner.</p>
<h3 id="heading-2-creating-custom-hofs">2. Creating Custom HOFs</h3>
<p>You can create custom higher order functions tailored to your specific requirements, encapsulating common patterns or behaviors into reusable functions.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Custom HOF for filtering based on multiple conditions</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">customFilter</span>(<span class="hljs-params">array, conditionFn</span>) </span>{
  <span class="hljs-keyword">return</span> array.filter(conditionFn);
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> evenGreaterThanTwo = customFilter(numbers, <span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num % <span class="hljs-number">2</span> === <span class="hljs-number">0</span> &amp;&amp; num &gt; <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(evenGreaterThanTwo); <span class="hljs-comment">// Output: [4]</span>
</code></pre>
<p>In this example, <code>customFilter</code> is a custom higher order function that accepts an array and a condition function. It filters the array based on the condition specified in the <code>conditionFn</code>. This allows for creating custom filtering logic tailored to specific requirements.</p>
<h3 id="heading-3-hofs-and-functional-programming-paradigms">3. HOFs and Functional Programming Paradigms:</h3>
<p>Higher order functions are fundamental to functional programming paradigms, emphasizing the use of pure functions, immutability, and declarative programming style.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Functional programming paradigm using HOFs</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-comment">// Using reduce() for summing numbers</span>
<span class="hljs-keyword">const</span> sum = numbers.reduce(<span class="hljs-function">(<span class="hljs-params">acc, num</span>) =&gt;</span> acc + num, <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(sum); <span class="hljs-comment">// Output: 15</span>

<span class="hljs-comment">// Using map() for doubling numbers</span>
<span class="hljs-keyword">const</span> doubled = numbers.map(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num * <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(doubled); <span class="hljs-comment">// Output: [2, 4, 6, 8, 10]</span>
</code></pre>
<p>In this example, we demonstrate functional programming paradigms using higher order functions. The <code>reduce()</code> function is used for summing numbers, emphasizing immutability and accumulation, while the <code>map()</code> function is used for doubling numbers, promoting declarative and pure functional style.</p>
<h2 id="heading-benefits-of-hofs-in-writing-cleaner-and-more-declarative-code">Benefits of HOFs in Writing Cleaner and More Declarative Code</h2>
<p>Higher order functions enable writing cleaner, more declarative, and expressive code by promoting code reuse, modularity, and functional programming principles.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Declarative code using HOFs</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-comment">// Using map() for squaring each number</span>
<span class="hljs-keyword">const</span> squared = numbers.map(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num * num);
<span class="hljs-built_in">console</span>.log(squared); <span class="hljs-comment">// Output: [1, 4, 9, 16, 25]</span>
</code></pre>
<p>In this example, the <code>map()</code> function is used to square each number in the array. This approach is declarative, clearly expressing the intention of the operation without low-level imperative details, leading to cleaner and more maintainable code.</p>
<h2 id="heading-best-practices-and-considerations-when-working-with-higher-order-functions">Best Practices and Considerations when Working with Higher Order Functions</h2>
<h3 id="heading-1-choosing-the-right-hof-for-the-job">1. Choosing the Right HOF for the Job</h3>
<p>Selecting the appropriate higher order function based on the desired operation is crucial for writing efficient and readable code. Consider factors such as the specific task at hand, the expected output, and any additional requirements.</p>
<p><strong>Example:</strong></p>
<ul>
<li>Use <code>map()</code> for transforming elements in an array.</li>
<li>Use <code>filter()</code> for selecting elements based on a condition.</li>
<li>Use <code>reduce()</code> for aggregating values into a single result.</li>
<li>Use <code>forEach()</code> for performing side effects without returning a new array.</li>
</ul>
<h3 id="heading-2-avoiding-overuse-of-hofs-for-readability-concerns">2. Avoiding Overuse of HOFs for Readability Concerns</h3>
<p>While higher order functions can improve code readability and maintainability, overusing them can lead to code that is hard to understand. Use HOFs judiciously, and favor readability over excessive abstraction.</p>
<p><strong>Example:</strong></p>
<ul>
<li>Choose a simple <code>for</code> loop over chaining multiple HOFs if it enhances clarity and understanding.</li>
</ul>
<h3 id="heading-3-understanding-callback-functions-in-hofs">3. Understanding Callback Functions in HOFs:</h3>
<p>Callback functions play a vital role within higher order functions, as they define the behavior or logic to be executed by the HOF.</p>
<p><strong>Example:</strong></p>
<ul>
<li>In <code>map()</code>, the callback function defines the transformation applied to each element.</li>
<li>In <code>filter()</code>, the callback function specifies the condition for selecting elements.</li>
<li>In <code>reduce()</code>, the callback function determines how values are aggregated into the final result.</li>
</ul>
<h3 id="heading-4-writing-efficient-and-clear-callback-functions">4. Writing Efficient and Clear Callback Functions</h3>
<p>Ensure that callback functions used within HOFs are efficient, clear, and focused on a single responsibility. Write them in a way that enhances readability and promotes code maintainability.</p>
<p><strong>Example:</strong></p>
<ul>
<li>Use descriptive variable names within callback functions to improve code clarity.</li>
<li>Break down complex operations into smaller, more manageable functions if necessary.</li>
<li>Consider using arrow functions for concise and readable syntax when defining callback functions.</li>
</ul>
<h3 id="heading-5-error-handling-and-edge-cases-with-hofs">5. Error Handling and Edge Cases with HOFs</h3>
<p>Handle potential errors and edge cases gracefully when using higher order functions to ensure robustness and reliability of your code.</p>
<p><strong>Example:</strong></p>
<ul>
<li>Validate input parameters before applying higher order functions to prevent unexpected behavior.</li>
<li>Implement error handling mechanisms within callback functions to handle exceptional cases.</li>
<li>Test your HOF implementations thoroughly to cover edge cases and ensure correct behavior in all scenarios.</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Throughout this article, you've explored the core concepts of HOFs, discussed popular functions like <code>map</code> and <code>reduce</code>, and discovered advanced techniques like function composition and custom HOF creation. You've also gained valuable insights into best practices, ensuring you leverage HOFs effectively and address potential pitfalls.</p>
<p>As you move forward, keep these powerful tools in your JavaScript arsenal. By mastering HOFs, you'll write cleaner, more concise, and expressive code, propelling your development skills to new heights.  Remember, the journey doesn't end here! Explore functional programming concepts that seamlessly integrate with HOFs. There's always more to learn and discover.</p>
<p>Connect with me on <a target="_blank" href="https://ng.linkedin.com/in/joan-ayebola">LinkedIn</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Difference Between <b> and <Strong> in HTML – Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ Bold text is a common formatting technique used to grab attention and highlight important information on webpages.  In HTML, we have two seemingly interchangeable tags for bold formatting: <b> and <strong>. While they may achieve a similar visual out... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/difference-between-b-and-strong-in-html/</link>
                <guid isPermaLink="false">66c4c3c5bd556981b1bdc439</guid>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Fri, 26 Apr 2024 23:24:38 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/Ivory-and-Blue-Lavender-Aesthetic-Photo-Collage-Presentation--6-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Bold text is a common formatting technique used to grab attention and highlight important information on webpages. </p>
<p>In HTML, we have two seemingly interchangeable tags for bold formatting: <code>&lt;b&gt;</code> and <code>&lt;strong&gt;</code>. While they may achieve a similar visual outcome, there's a crucial difference between them. </p>
<p>This article dives deep into the distinction between <code>&lt;b&gt;</code> and <code>&lt;strong&gt;</code> in HTML, exploring their semantic meaning, rendering, accessibility, and best practices for their use.</p>
<h2 id="heading-what-is-the-b-tag-in-html">What is the <code>b</code> Tag in HTML?</h2>
<p>The <code>&lt;b&gt;</code> tag is an HTML element used to apply bold formatting to text content. It stands for "bold" and is a part of the set of inline elements in HTML. When you wrap text within <code>&lt;b&gt;</code> tags, the enclosed text is rendered in a bold font style by web browsers.</p>
<p>But it's essential to note that the <code>&lt;b&gt;</code> tag doesn't convey any specific semantic meaning to the text it wraps. Unlike other elements like <code>&lt;strong&gt;</code>, which indicates strong importance or emphasis, the <code>&lt;b&gt;</code> tag is primarily used for stylistic purposes. It simply instructs the browser to display the enclosed text in bold, without implying any inherent significance or importance.</p>
<p>For example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is <span class="hljs-tag">&lt;<span class="hljs-name">b</span>&gt;</span>bold<span class="hljs-tag">&lt;/<span class="hljs-name">b</span>&gt;</span> text.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>This is <b>bold</b> text.</p>


<p>In this case, the word "bold" will be visually emphasized, but the <code>&lt;b&gt;</code> tag doesn't provide any additional information about why the text is bolded. Because of this, it's crucial to use the <code>&lt;b&gt;</code> tag judiciously, especially when conveying meaningful emphasis or importance in your HTML document.</p>
<h2 id="heading-what-is-the-strong-tag-in-html">What is the <code>strong</code> Tag in HTML?</h2>
<p>The <code>&lt;strong&gt;</code> tag is an HTML element used to denote text with strong importance, emphasis, or relevance. It is one of the semantic markup elements in HTML designed to convey meaning beyond mere presentation. </p>
<p>When you enclose text within <code>&lt;strong&gt;</code> tags, it tells web browsers and assistive technologies that the enclosed text should be treated as having strong importance or emphasis.</p>
<p>Unlike the <code>&lt;b&gt;</code> tag, which is primarily used for stylistic purposes to apply bold formatting, the <code>&lt;strong&gt;</code> tag carries semantic meaning. While browsers typically render text within <code>&lt;strong&gt;</code> tags in a bold font, the primary purpose of the tag is to provide additional context about the significance of the enclosed text.</p>
<p>For example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>important<span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span> text.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>This is <strong>important</strong> text.</p>


<p>In this case, the word "important" is not only visually emphasized with a bold font but also marked as having strong importance or emphasis within the document structure. </p>
<p>This semantic meaning can be beneficial for accessibility purposes, as screen readers and other assistive technologies can interpret the significance of the text and convey it to users who may not be able to see the visual styling.</p>
<h2 id="heading-purpose-of-bold-text-formatting">Purpose of Bold Text Formatting</h2>
<p>The purpose of bold text formatting in HTML is primarily to visually emphasize certain words or phrases within a block of text. When text is formatted in bold, it stands out more prominently compared to the surrounding text, drawing the reader's attention to it. </p>
<p>This emphasis can serve various purposes, such as indicating importance, highlighting key points, or distinguishing headings and subheadings from body text.</p>
<p>Bold text formatting can be particularly useful for:</p>
<ul>
<li><strong>Highlighting Important Information:</strong> Bold text is often used to emphasize critical information or key concepts within a paragraph or document, making it easier for readers to identify and comprehend essential points.</li>
<li><strong>Improving Readability:</strong> By visually separating important elements from the rest of the text, bold formatting can enhance the overall readability of the content, especially in lengthy passages.</li>
<li><strong>Creating Visual Hierarchy:</strong> Bold text can help establish a hierarchy of information within a document, with headings and subheadings appearing bolder than regular text, thus guiding readers through the structure of the content.</li>
<li><strong>Emphasizing Call-to-Action:</strong> In web design, bold text is frequently used to draw attention to call-to-action (CTA) buttons or links, prompting users to take specific actions such as making a purchase, signing up for a newsletter, or navigating to another page.</li>
</ul>
<h2 id="heading-can-browser-styles-override">Can Browser Styles Override?</h2>
<p>Yes, browser styles can override the default rendering of HTML elements, including the <code>&lt;b&gt;</code> and <code>&lt;strong&gt;</code> tags.</p>
<p>Web browsers have their own default stylesheets (user agent stylesheets) that define how HTML elements should be displayed if no specific styles are provided by the webpage itself. These default stylesheets may specify the font size, font family, color, and other visual properties for various HTML elements.</p>
<p>When you use the <code>&lt;b&gt;</code> or <code>&lt;strong&gt;</code> tags without providing custom styles, browsers will typically apply their default styles for bold text. But these default styles can be overridden by CSS styles defined within the webpage's stylesheet or inline styles applied directly to the elements.</p>
<p>For example, if you have the following HTML:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>important<span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span> text.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>And you apply custom CSS styles to override the default bold formatting:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">strong</span> {
    <span class="hljs-attribute">font-weight</span>: normal; <span class="hljs-comment">/* Override bold font weight */</span>
    <span class="hljs-attribute">color</span>: red; <span class="hljs-comment">/* Change text color */</span>
}
</code></pre>
<p>
</p>
<p></p>
<p>This is <strong>important</strong> text.</p>


<p>The text within the <code>&lt;strong&gt;</code> tag will no longer appear bold and will be displayed in red, as specified by the CSS rules.</p>
<p>Similarly, you can override the default styles for the <code>&lt;b&gt;</code> tag using CSS, although it's less common to do so since the <code>&lt;b&gt;</code> tag is typically used for purely presentational purposes without conveying semantic meaning.</p>
<p>Screen readers interpret the <code>&lt;strong&gt;</code> tag as indicating text with strong importance or emphasis. When encountering content enclosed within <code>&lt;strong&gt;</code> tags, screen reader software will typically announce the text with additional emphasis, indicating to users that the enclosed content is particularly important or relevant within the context of the document.</p>
<p>This semantic markup is crucial for accessibility purposes, as it enables users who rely on screen readers to understand the significance of the text without relying solely on visual cues. By conveying the importance or emphasis of the text through semantic markup like <code>&lt;strong&gt;</code>, screen readers can provide a more accurate and informative representation of the content to users who may be visually impaired or otherwise unable to view the visual styling of the webpage.</p>
<p>For example, if a screen reader encounters the following HTML:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is <span class="hljs-tag">&lt;<span class="hljs-name">strong</span>&gt;</span>important<span class="hljs-tag">&lt;/<span class="hljs-name">strong</span>&gt;</span> text.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>It would announce the text "important" with additional emphasis, such as by adjusting the speech rate or volume, to indicate to the user that this particular text is of heightened significance within the document.</p>
<h2 id="heading-potential-issues-with">Potential Issues with <code>&lt;b&gt;</code></h2>
<p>Using the <code>&lt;b&gt;</code> tag can lead to several potential issues, particularly in terms of accessibility and semantic markup:</p>
<p><strong>Lack of Semantic Meaning:</strong> The <code>&lt;b&gt;</code> tag is purely presentational and does not convey any specific semantic meaning about the enclosed text. This can be problematic for users who rely on assistive technologies like screen readers to access web content, as the bold formatting provided by the <code>&lt;b&gt;</code> tag does not provide any indication of the importance or emphasis of the text.</p>
<p><strong>Accessibility Concerns:</strong> Screen readers may not interpret text enclosed within <code>&lt;b&gt;</code> tags as being more important or relevant than surrounding text, potentially leading to a loss of context or understanding for users with disabilities. Without semantic markup to convey the significance of the text, users may struggle to understand the intended meaning of the content.</p>
<p><strong>SEO Impact:</strong> Search engines may not give as much weight to content styled with the <code>&lt;b&gt;</code> tag compared to content marked up with semantic elements like <code>&lt;strong&gt;</code>. This could potentially affect search engine rankings, as search engines rely on semantic markup to understand the relevance and importance of content on webpages.</p>
<p><strong>Maintenance Challenges:</strong> Overuse of the <code>&lt;b&gt;</code> tag for purely presentational purposes can lead to maintenance challenges, as it may be difficult to distinguish between text that is bolded for stylistic reasons and text that is genuinely important or emphasized within the document. This lack of clarity can make it harder for developers to maintain and update the content in the future.</p>
<p>Overall, while the <code>&lt;b&gt;</code> tag can be useful for adding bold formatting to text, it's important to use it judiciously and consider the potential implications for accessibility, SEO, and document structure</p>
<h2 id="heading-does-impact-seo">Does <code>&lt;strong&gt;</code> Impact SEO?</h2>
<p>Yes, the <code>&lt;strong&gt;</code> tag can indirectly impact SEO (Search Engine Optimization) in several ways, while using <code>&lt;strong&gt;</code> may indirectly impact SEO by improving content readability and accessibility, it's not a direct ranking factor.</p>
<p><strong>Semantic Markup:</strong> Search engines like Google aim to understand the content of web pages to deliver relevant search results to users. Semantic markup, such as the <code>&lt;strong&gt;</code> tag, provides additional context and clarity about the importance or emphasis of text within a document. When you use <code>&lt;strong&gt;</code>, you're signaling to search engines that the enclosed text is of strong importance or relevance, potentially influencing how they interpret and index your content.</p>
<p><strong>Content Readability:</strong> Clear and well-structured content improves readability, which is a key factor in SEO. By using <code>&lt;strong&gt;</code> to emphasize important keywords or phrases, you can enhance the readability and comprehension of your content for both users and search engines.</p>
<p><strong>User Engagement:</strong> Content that effectively communicates key points using semantic markup like <code>&lt;strong&gt;</code> may result in increased user engagement, such as longer time spent on the page or higher click-through rates. Search engines may consider user engagement metrics as indicators of content quality, which can positively impact SEO rankings.</p>
<p><strong>Accessibility:</strong> Semantic markup improves accessibility for users with disabilities, including those using screen readers. By properly marking up important content with <code>&lt;strong&gt;</code>, you're ensuring that all users, regardless of their abilities, can understand the significance of the text. Improved accessibility can lead to better user experiences, potentially resulting in higher rankings in search engine results pages (SERPs).</p>
<h3 id="heading-when-to-use">When to Use <code>&lt;strong&gt;</code></h3>
<p>You should use the <code>&lt;strong&gt;</code> tag when you want to emphasize text that carries strong importance or relevance within the context of your document. Here are some scenarios when using <code>&lt;strong&gt;</code> would be appropriate:</p>
<ul>
<li><strong>Important Keywords:</strong> Use <code>&lt;strong&gt;</code> to highlight important keywords or phrases that are central to the topic or main point of your content. This helps both readers and search engines understand the significance of those terms.</li>
<li><strong>Key Points:</strong> Use <code>&lt;strong&gt;</code> to emphasize key points, arguments, or conclusions within your content. This draws attention to critical information and makes it more memorable for readers.</li>
<li><strong>Warnings or Notices:</strong> Use <code>&lt;strong&gt;</code> to highlight warnings, notices, or alerts that require immediate attention from your audience. This ensures that important messages stand out and are not overlooked.</li>
<li><strong>Calls to Action:</strong> Use <code>&lt;strong&gt;</code> to emphasize calls to action (CTAs) such as "Buy Now," "Sign Up," or "Learn More." This encourages user engagement and increases the likelihood of conversion.</li>
<li><strong>Headings and Subheadings:</strong> Use <code>&lt;strong&gt;</code> within headings and subheadings to give them additional emphasis and hierarchy within your document structure. This helps users quickly scan and understand the organization of your content.</li>
<li><strong>Quotations or Citations:</strong> Use <code>&lt;strong&gt;</code> to emphasize quotations or citations from authoritative sources, indicating their importance or relevance to your content.</li>
</ul>
<h3 id="heading-when-might-be-acceptable">When Might <code>&lt;b&gt;</code> Be Acceptable?</h3>
<p><code>&lt;b&gt;</code> might be acceptable for purely stylistic bold formatting when no specific semantic meaning is intended.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, understanding the subtle yet crucial differences between <code>&lt;b&gt;</code> and <code>&lt;strong&gt;</code> is essential for crafting well-structured and semantic HTML. </p>
<p>By prioritizing the <code>&lt;strong&gt;</code> tag for conveying importance and reserving <code>&lt;b&gt;</code> for situations where emphasis is purely visual, you contribute to a clearer and more accessible web experience for all users. </p>
<p>Remember, semantic HTML not only benefits users with disabilities but can also play a role in search engine optimization. So, make a conscious choice: use <code>&lt;strong&gt;</code> to highlight what truly matters, and leverage CSS for fine-tuning the visual presentation of your bold text. </p>
<p>By embracing semantic coding practices, you'll create webpages that are not only informative but also speak a clear language to both users and search engines.</p>
<p>Connect with me on <a target="_blank" href="https://ng.linkedin.com/in/joan-ayebola">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
