<?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" version="2.0"><channel><title><![CDATA[Roblog | Personal Blog]]></title><description><![CDATA[Roblog is a platform where I share my knowledge and passion for programming with visitors from all around the world, completely free. So, Never Stop Learning, because Life never stops teaching.]]></description><link>https://robiul.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1667807426091/aDtJOty_8.png</url><title>Roblog | Personal Blog</title><link>https://robiul.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Tue, 14 Apr 2026 21:43:51 GMT</lastBuildDate><atom:link href="https://robiul.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[PM2: A Journey from Basics to Advanced Node.js Process Management]]></title><description><![CDATA[Welcome to your journey with PM2, the powerful process manager for Node.js applications. Whether you're a beginner just starting with Node.js or an experienced developer looking to optimize your application management, this guide will walk you throug...]]></description><link>https://robiul.dev/pm2-a-journey-from-basics-to-advanced-nodejs-process-management</link><guid isPermaLink="true">https://robiul.dev/pm2-a-journey-from-basics-to-advanced-nodejs-process-management</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[MERN Stack]]></category><category><![CDATA[Next.js]]></category><category><![CDATA[React]]></category><category><![CDATA[Express]]></category><category><![CDATA[pm2]]></category><category><![CDATA[MongoDB]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Thu, 14 Nov 2024 01:41:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1731546921739/a0fb7d8d-ff4d-4e99-aa41-0f8655d017db.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to your journey with <a target="_blank" href="https://pm2.keymetrics.io/">PM2</a>, the powerful process manager for Node.js applications. Whether you're a beginner just starting with Node.js or an experienced developer looking to optimize your application management, this guide will walk you through PM2 from the ground up. We'll focus primarily on managing a MERN (<a target="_blank" href="https://www.mongodb.com/">MongoDB</a>, Express, React, Node.js) stack application, but the principles apply to any Node.js project.</p>
<p>Ok, before discussing other things. Let’s answer the main question that you may have in your mind and that is - <strong>What is PM2</strong>?</p>
<p><strong>PM2</strong> is a production-grade process manager for Node.js applications. It is designed to help manage, monitor, and keep applications running continuously. PM2 provides features such as automatic application restarts on failure, and comprehensive log management. This tool simplifies the deployment and management of Node.js applications by enabling efficient resource use and ensuring high availability, making it especially useful for managing web servers, APIs, and complex Node.js services in production environments.</p>
<h2 id="heading-step-1-installing-pm2">Step 1: Installing PM2</h2>
<p>Let's begin our journey by installing PM2. Open your terminal and run:</p>
<pre><code class="lang-bash">npm install -g pm2
</code></pre>
<p>This command installs PM2 globally on your system, making it available for all your projects.</p>
<h2 id="heading-step-2-running-your-first-nodejs-file-with-pm2">Step 2: Running Your First Node.js File with PM2</h2>
<p>Let's start with a simple Node.js file. Create a file named <code>app.js</code> with the following content:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello, PM2!'</span>);
<span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"'I'm still running!"</span>);
}, <span class="hljs-number">5000</span>);
</code></pre>
<p>Now, let's run this file with PM2:</p>
<pre><code class="lang-bash">pm2 start app.js
</code></pre>
<p>Congratulations! You've just started your first process with PM2.</p>
<h2 id="heading-step-3-running-npm-scripts-with-pm2">Step 3: Running npm Scripts with PM2</h2>
<p>As your projects grow more complex, you'll often use npm scripts defined in your <code>package.json</code> file to start your application. PM2 can manage these scripts just as easily as it manages individual files.</p>
<p>Let's use a Next.js application as an example:</p>
<ol>
<li>First, ensure your <code>package.json</code> has a start script. For a Next.js app, it typically looks like this:</li>
</ol>
<pre><code class="lang-json">{
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"next dev"</span>,
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"next build"</span>,
    <span class="hljs-attr">"start"</span>: <span class="hljs-string">"next start"</span>
  }
}
</code></pre>
<ol start="2">
<li>To run the production version of your Next.js app with PM2, use the following command:</li>
</ol>
<pre><code class="lang-bash">pm2 start npm --name <span class="hljs-string">"next-app"</span> -- start
</code></pre>
<p>This tells PM2 to run the <code>npm start</code> command, which in turn runs <code>next start</code> for a Next.js application.</p>
<ul>
<li><p><code>pm2 start npm</code>: Runs the <code>npm</code> command using PM2.</p>
</li>
<li><p><code>--name "next-app"</code>: Names the process for easy identification.</p>
</li>
<li><p><code>-- start</code>: Passes <code>start</code> as an argument to <code>npm</code>, ensuring that <code>npm</code> runs the <code>start</code> script defined in your <code>package.json</code>.</p>
</li>
</ul>
<ol start="3">
<li>If you want to run the development version, you can use:</li>
</ol>
<pre><code class="lang-bash">pm2 start npm --name <span class="hljs-string">"next-app-dev"</span> -- run dev
</code></pre>
<p>This runs <code>npm run dev</code>, which starts the Next.js development server.</p>
<ol start="4">
<li>You can apply the same principle to other npm scripts. For example, if you have a custom script called <code>server</code>:</li>
</ol>
<pre><code class="lang-bash">pm2 start npm --name <span class="hljs-string">"custom-server"</span> -- run server
</code></pre>
<p>This approach is not limited to Next.js. You can use it with any <a target="_blank" href="https://nodejs.org/en">Node.js</a> application that uses <a target="_blank" href="https://www.npmjs.com/">npm</a> scripts, such as Express.js servers, React applications, or even custom Node.js scripts.</p>
<h2 id="heading-step-4-managing-multiple-npm-scripts">Step 4: Managing Multiple npm Scripts</h2>
<p>For complex projects with multiple components, such as a <a target="_blank" href="https://www.simplilearn.com/tutorials/mongodb-tutorial/what-is-mern-stack-introduction-and-examples">MERN</a> (MongoDB, Express, <a target="_blank" href="https://react.dev/">React</a>, Node.js) stack application, you'll often need to manage several npm scripts simultaneously. PM2's ecosystem file feature is perfect for this scenario, allowing you to define and manage multiple processes in a single configuration file.</p>
<p>Create a file named <code>ecosystem.config.js</code> in your project root. This file will define all the processes PM2 should manage. Here's an expanded example:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">apps</span>: [
    {
      <span class="hljs-attr">name</span>: <span class="hljs-string">"next-app"</span>,
      <span class="hljs-attr">script</span>: <span class="hljs-string">"npm"</span>,
      <span class="hljs-attr">args</span>: <span class="hljs-string">"start"</span>,
      <span class="hljs-attr">cwd</span>: <span class="hljs-string">"./frontend"</span>,
      <span class="hljs-attr">env</span>: {
        <span class="hljs-attr">NODE_ENV</span>: <span class="hljs-string">"production"</span>,
        <span class="hljs-attr">PORT</span>: <span class="hljs-number">3000</span>
      },
      <span class="hljs-attr">env_development</span>: {
        <span class="hljs-attr">NODE_ENV</span>: <span class="hljs-string">"development"</span>,
        <span class="hljs-attr">PORT</span>: <span class="hljs-number">3000</span>
      }
    },
    {
      <span class="hljs-attr">name</span>: <span class="hljs-string">"express-server"</span>,
      <span class="hljs-attr">script</span>: <span class="hljs-string">"npm"</span>,
      <span class="hljs-attr">args</span>: <span class="hljs-string">"run server"</span>,
      <span class="hljs-attr">cwd</span>: <span class="hljs-string">"./backend"</span>,
      <span class="hljs-attr">env</span>: {
        <span class="hljs-attr">NODE_ENV</span>: <span class="hljs-string">"production"</span>,
        <span class="hljs-attr">PORT</span>: <span class="hljs-number">5000</span>
      },
      <span class="hljs-attr">env_development</span>: {
        <span class="hljs-attr">NODE_ENV</span>: <span class="hljs-string">"development"</span>,
        <span class="hljs-attr">PORT</span>: <span class="hljs-number">5000</span>
      }
    },
  ]
}
</code></pre>
<p>Let's break down the configuration options:</p>
<ul>
<li><p><code>name</code>: A unique identifier for each process.</p>
</li>
<li><p><code>script</code>: The command to run. Use <code>"npm"</code> for npm scripts.</p>
</li>
<li><p><code>args</code>: Arguments to pass to the script. For npm scripts, use <code>"start"</code>, <code>"run server"</code>, etc.</p>
</li>
<li><p><code>cwd</code>: The working directory for the process. Useful when your frontend and backend are in separate directories.</p>
</li>
<li><p><code>env</code>: Environment variables for production.</p>
</li>
<li><p><code>env_development</code>: Environment variables for development.</p>
</li>
</ul>
<p>To start all processes defined in your ecosystem file:</p>
<pre><code class="lang-bash">pm2 start ecosystem.config.js
</code></pre>
<p>To start processes in development mode:</p>
<pre><code class="lang-bash">pm2 start ecosystem.config.js --env development
</code></pre>
<p>This approach gives you the flexibility to manage complex applications with multiple components, all through PM2.</p>
<h2 id="heading-step-5-basic-pm2-commands">Step 5: Basic PM2 Commands</h2>
<p>Now that we have a process running, let's learn some basic PM2 commands:</p>
<ol>
<li>List running processes:</li>
</ol>
<pre><code class="lang-bash">pm2 list
</code></pre>
<ol start="2">
<li>Stop a specific process::</li>
</ol>
<pre><code class="lang-bash">pm2 stop next-app
</code></pre>
<ol start="3">
<li>Restart a specific process:</li>
</ol>
<pre><code class="lang-bash">pm2 restart next-app
</code></pre>
<ol start="4">
<li>Delete a specific process from PM2:</li>
</ol>
<pre><code class="lang-bash">pm2 delete next-app
</code></pre>
<ol start="5">
<li>Stop all processes:</li>
</ol>
<pre><code class="lang-bash">pm2 stop all
</code></pre>
<ol start="6">
<li>Restart all processes:</li>
</ol>
<pre><code class="lang-bash"> pm2 restart all
</code></pre>
<ol start="7">
<li>Delete all processes:</li>
</ol>
<pre><code class="lang-bash">pm2 delete all
</code></pre>
<h2 id="heading-step-6-monitoring-your-application">Step 6: Monitoring Your Application</h2>
<ol>
<li>PM2 provides a real-time monitoring tool. Try it out:</li>
</ol>
<pre><code class="lang-bash">pm2 monit
</code></pre>
<p>This command opens an interface where you can see CPU usage, memory consumption, and logs for your running processes.</p>
<ol start="2">
<li>Display process details:</li>
</ol>
<pre><code class="lang-bash">pm2 show next-app
</code></pre>
<p>This command provides detailed information about a specific process, including its configuration, metadata, and recent logs.</p>
<h2 id="heading-step-7-reloading-without-downtime">Step 7: Reloading Without Downtime</h2>
<p>To update your application with zero downtime:</p>
<pre><code class="lang-bash">pm2 reload ecosystem.config.js
</code></pre>
<p>This command gracefully reloads all processes defined in your ecosystem file, ensuring that your application remains available during updates.</p>
<h2 id="heading-step-8-managing-logs">Step 8: Managing Logs</h2>
<p>Logs are crucial for understanding what's happening in your application. Here's how to view them:</p>
<ol>
<li>View logs:</li>
</ol>
<pre><code class="lang-bash">pm2 logs
</code></pre>
<ol start="2">
<li>View logs for a specific application:</li>
</ol>
<pre><code class="lang-bash">pm2 logs next-app
</code></pre>
<ol start="3">
<li>Clear log files:</li>
</ol>
<pre><code class="lang-bash">pm2 flush
</code></pre>
<ol start="4">
<li>To view only error logs:</li>
</ol>
<pre><code class="lang-bash">pm2 logs --err
</code></pre>
<h2 id="heading-step-9-automatic-restart-on-crashes"><strong>Step 9: Automatic Restart on Crashes</strong></h2>
<p>One of PM2's most powerful features is its ability to automatically restart applications that crash or stop unexpectedly. This feature ensures high availability and reliability for your Node.js applications.</p>
<p>Here's how it works:</p>
<ol>
<li><p>PM2 constantly monitors the processes it manages.</p>
</li>
<li><p>If a process crashes or exits with an error code, PM2 will automatically restart it.</p>
</li>
<li><p>This happens without any manual intervention, minimizing downtime.</p>
</li>
</ol>
<p>Here are some key options that allow you to fine-tune the automatic restart behavior. These options can be added to your <code>ecosystem.config.js</code> file or specified when starting an application.</p>
<ol>
<li><p><code>max_restarts</code>: Sets the maximum number of restarts within a time frame.</p>
</li>
<li><p><code>min_uptime</code>: Minimum uptime of the app to be considered started.</p>
</li>
<li><p><code>max_memory_restart</code>: Restarts the app if it exceeds a specified memory limit.</p>
</li>
<li><p><code>restart_delay</code>: Delay between automatic restarts (in milliseconds).</p>
</li>
<li><p><code>autorestart</code>: Enables or disables the automatic restart feature.</p>
</li>
</ol>
<p>Let's update the <code>ecosystem.config.js</code> file to include these options:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">apps</span>: [{
    <span class="hljs-attr">name</span>: <span class="hljs-string">"my-app"</span>,
    <span class="hljs-attr">script</span>: <span class="hljs-string">"app.js"</span>,
    <span class="hljs-attr">max_restarts</span>: <span class="hljs-number">10</span>,
    <span class="hljs-attr">min_uptime</span>: <span class="hljs-string">"5s"</span>,
    <span class="hljs-attr">max_memory_restart</span>: <span class="hljs-string">"200M"</span>,
    <span class="hljs-attr">restart_delay</span>: <span class="hljs-number">4000</span>,
    <span class="hljs-attr">autorestart</span>: <span class="hljs-literal">true</span>
  }]
}
</code></pre>
<p>In this configuration:</p>
<ul>
<li><p>The app will restart a maximum of 10 times.</p>
</li>
<li><p>The app must run for at least 5 seconds to be considered successfully started.</p>
</li>
<li><p>If the app uses more than 200MB of memory, it will be restarted.</p>
</li>
<li><p>There will be a 4-second delay between restarts.</p>
</li>
<li><p>Automatic restarts are enabled (this is the default, but we're explicitly setting it here).</p>
</li>
</ul>
<p>You can also set these options when starting an app from the command line:</p>
<pre><code class="lang-bash">pm2 start app.js --max-restarts 10 --min-uptime 5000 --max-memory-restart 200M --restart-delay 4000
</code></pre>
<h3 id="heading-example-demonstrating-automatic-restart">Example: Demonstrating Automatic Restart</h3>
<p>Let's create a simple Node.js application that will crash periodically to demonstrate PM2's automatic restart feature.</p>
<ol>
<li><p>Create a new file named <code>crash-test.js</code> with the following content:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;

 <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Running for <span class="hljs-subst">${count}</span> seconds`</span>);
   count++;

   <span class="hljs-keyword">if</span> (count % <span class="hljs-number">10</span> === <span class="hljs-number">0</span>) {
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Simulating a crash..."</span>);
     <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Application crashed!"</span>);
   }
 }, <span class="hljs-number">1000</span>);
</code></pre>
<p> This script will run for 10 seconds and then simulate a crash by throwing an error.</p>
</li>
<li><p>Create an <code>ecosystem.config.js</code> file with the following content:</p>
<pre><code class="lang-javascript"> <span class="hljs-built_in">module</span>.exports = {
   <span class="hljs-attr">apps</span>: [{
     <span class="hljs-attr">name</span>: <span class="hljs-string">"crash-test"</span>,
     <span class="hljs-attr">script</span>: <span class="hljs-string">"crash-test.js"</span>,
     <span class="hljs-attr">max_restarts</span>: <span class="hljs-number">5</span>,
     <span class="hljs-attr">min_uptime</span>: <span class="hljs-string">"3s"</span>,
     <span class="hljs-attr">restart_delay</span>: <span class="hljs-number">2000</span>
   }]
 }
</code></pre>
</li>
<li><p>Start the application with PM2:</p>
<pre><code class="lang-bash"> pm2 start ecosystem.config.js
</code></pre>
</li>
<li><p>Monitor the application:</p>
<pre><code class="lang-bash"> pm2 monit
</code></pre>
<p> You'll see in the monitoring interface that every 10 seconds, the application crashes and PM2 automatically restarts it, with a 2-second delay between restarts.</p>
</li>
<li><p>To view the logs and see the crash and restart events:</p>
<pre><code class="lang-bash"> pm2 logs crash-test
</code></pre>
<p> You'll see output similar to this:</p>
<pre><code class="lang-bash"> 0|crash-test  | Running <span class="hljs-keyword">for</span> 8 seconds
 0|crash-test  | Running <span class="hljs-keyword">for</span> 9 seconds
 0|crash-test  | Simulating a crash...
 0|crash-test  | Error: Application crashed!
 0|crash-test  |     at Timeout._onTimeout (/path/to/crash-test.js:8:11)
 0|crash-test  |     at listOnTimeout (node:internal/timers:559:17)
 0|crash-test  |     at processTimers (node:internal/timers:502:7)
 PM2        | App [crash-test:0] exited with code [1] via signal [SIGINT]
 PM2        | App [crash-test:0] starting <span class="hljs-keyword">in</span> -fork mode-
 0|crash-test  | Running <span class="hljs-keyword">for</span> 0 seconds
 0|crash-test  | Running <span class="hljs-keyword">for</span> 1 seconds
</code></pre>
</li>
</ol>
<p>This example demonstrates how PM2 automatically restarts your application when it crashes, ensuring continuous operation even in the face of unexpected errors. The configuration options we've set limit the number of restarts to 5 and introduce a 2-second delay between restarts, helping to prevent rapid restart loops in case of persistent issues.</p>
<h2 id="heading-real-world-example-mern-stack">Real-world Example: MERN Stack</h2>
<p>Here's how you might set up an ecosystem file for a typical MERN stack application:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">apps</span>: [
    {
      <span class="hljs-attr">name</span>: <span class="hljs-string">"react-frontend"</span>,
      <span class="hljs-attr">script</span>: <span class="hljs-string">"npm"</span>,
      <span class="hljs-attr">args</span>: <span class="hljs-string">"start"</span>,
      <span class="hljs-attr">cwd</span>: <span class="hljs-string">"./client"</span>,
      <span class="hljs-attr">env</span>: {
        <span class="hljs-attr">NODE_ENV</span>: <span class="hljs-string">"production"</span>,
        <span class="hljs-attr">PORT</span>: <span class="hljs-number">3000</span>
      }
    },
    {
      <span class="hljs-attr">name</span>: <span class="hljs-string">"express-backend"</span>,
      <span class="hljs-attr">script</span>: <span class="hljs-string">"npm"</span>,
      <span class="hljs-attr">args</span>: <span class="hljs-string">"run server"</span>,
      <span class="hljs-attr">cwd</span>: <span class="hljs-string">"./server"</span>,
      <span class="hljs-attr">env</span>: {
        <span class="hljs-attr">NODE_ENV</span>: <span class="hljs-string">"production"</span>,
        <span class="hljs-attr">PORT</span>: <span class="hljs-number">5000</span>,
        <span class="hljs-attr">MONGODB_URI</span>: <span class="hljs-string">"mongodb://localhost:27017/myapp"</span>
      }
    },
    {
      <span class="hljs-attr">name</span>: <span class="hljs-string">"mongodb"</span>,
      <span class="hljs-attr">script</span>: <span class="hljs-string">"mongod"</span>,
      <span class="hljs-attr">args</span>: <span class="hljs-string">"--port 27017"</span>
    }
  ]
}
</code></pre>
<p>This configuration starts a React frontend, an <a target="_blank" href="https://expressjs.com/">Express.js</a> backend, and a MongoDB instance, all managed by PM2.</p>
<p>By leveraging PM2's ecosystem files, you can efficiently manage complex, multi-component applications, ensuring all parts of your stack start together and are monitored effectively. This approach simplifies deployment, improves maintainability, and gives you fine-grained control over each component of your application.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Congratulations! You've completed your journey from PM2 basics to advanced usage. You've learned how to start simple scripts, manage complex applications, handle logs, use environment variables, and even tackle a full MERN stack. Remember, PM2 is a powerful tool with many more features to explore. As you continue your development journey, don't hesitate to dive into the PM2 documentation for more advanced usage and optimizations.</p>
<p>Happy coding, and may your applications always stay up and running with PM2!</p>
]]></content:encoded></item><item><title><![CDATA[Next Cloudinary: A Game-Changer for Client-Side File Handling]]></title><description><![CDATA[Cloudinary has long been a robust solution for managing assets like images and videos in web applications. Its features allow for smooth asset management and optimization, but they stepped up their game to accommodate Next.js with a dedicated library...]]></description><link>https://robiul.dev/next-cloudinary-a-game-changer-for-client-side-file-handling</link><guid isPermaLink="true">https://robiul.dev/next-cloudinary-a-game-changer-for-client-side-file-handling</guid><category><![CDATA[Next.js]]></category><category><![CDATA[cloudinary]]></category><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Sun, 29 Sep 2024 07:09:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727593301797/56b87688-2471-4e74-9459-8f2353e880a7.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Cloudinary has long been a robust solution for managing assets like images and videos in web applications. Its features allow for smooth asset management and optimization, but they stepped up their game to accommodate Next.js with a dedicated library called <strong>Next Cloudinary</strong>. After exploring it, I was thoroughly impressed. Although it’s not yet widely used, <strong>Next Cloudinary</strong> is an incredibly powerful tool that integrates perfectly with Next.js applications, making it a must-try for developers looking to streamline their asset management workflows.</p>
<h3 id="heading-next-cloudinary-clduploadwidget">Next Cloudinary <code>CldUploadWidget</code></h3>
<p>Next Cloudinary has provided a widget called <code>CldUploadWidget</code> which creates a new instance of the <a target="_blank" href="https://cloudinary.com/documentation/upload_widget">Cloudinary Upload Widget</a> which gives an easy way to add upload capabilities to the Next.js app.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1727593553056/62546c2e-230e-48e8-b555-51784b32a530.webp" alt="Next Cloudinary CldUploadWidget" class="image--center mx-auto" /></p>
<p>Whether the files are stored locally, accessed via URLs, or retrieved from third-party sources like Google Drive, this component can handle them seamlessly. This broad integration means users can interact with various file sources without needing complex configurations on the server.</p>
<p>CldUploadWidget supports two options: signed and unsigned. These options allow us to control the security and restrictions.</p>
<h3 id="heading-powerful-image-optimization-with-cldimage">Powerful Image Optimization with <code>CldImage</code></h3>
<p>Another component <code>CldImage</code> is an evolution of Next.js’s native <code>&lt;Image /&gt;</code> component. It goes beyond basic image rendering, allowing for advanced optimization, transformations, and real-time manipulations. What sets <code>CldImage</code> apart is how easily you can implement image effects like cropping, adding filters, or adjusting colors with just a few props. These enhancements don't just simplify image handling; they also significantly improve application performance by reducing image payloads and enhancing load times—important factors for SEO and user experience.</p>
<p>For example, with <code>CldImage</code>, you can add a blur effect, resize images, or apply custom transformations on the fly, which would otherwise require extensive backend processing or third-party image editing tools. Here’s a quick comparison of what makes <code>CldImage</code> a 'pro' version of the Next.js <code>&lt;Image /&gt;</code> tag:</p>
<ul>
<li><p><strong>Automatic Image Optimization:</strong> Like Next.js’s image component, but with the added flexibility of Cloudinary’s extensive transformations.</p>
</li>
<li><p><strong>Advanced Effects:</strong> Supports filters, overlays, and cropping using Cloudinary’s powerful API.</p>
</li>
<li><p><strong>Real-Time Adjustments:</strong> You can tweak images without needing to re-upload or manipulate them manually.</p>
</li>
</ul>
<p>This feature set is essential for developers dealing with dynamic content or user-generated uploads, where having tools to manage, optimize, and enhance images can dramatically reduce overhead.</p>
<p>In <code>CIdImage</code> component we can render responsive Images just by using the <code>sizes</code> prop. With the <code>sizes</code> prop, we can configure as we want the sizes for our application, Here is an example:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">import</span> { CldImage } <span class="hljs-keyword">from</span> <span class="hljs-string">'next-cloudinary'</span>;

  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">CldImage</span>
    <span class="hljs-attr">width</span>=<span class="hljs-string">"960"</span>
    <span class="hljs-attr">height</span>=<span class="hljs-string">"600"</span>
    <span class="hljs-attr">src</span>=<span class="hljs-string">"&lt;Your Public ID&gt;"</span>
    <span class="hljs-attr">sizes</span>=<span class="hljs-string">"(max-width: 768px) 100vw,
          (max-width: 1200px) 50vw,
          33vw"</span>
    <span class="hljs-attr">alt</span>=<span class="hljs-string">"Description"</span>
  /&gt;</span></span>
</code></pre>
<p>This would give us roughly full-width images on mobile, a 2-column layout on tablets, and a 3-column layout on desktop views.</p>
<p>For the above code, the output would look like:</p>
<pre><code class="lang-javascript">&lt;img
  alt=<span class="hljs-string">"Turtle"</span>
  loading=<span class="hljs-string">"lazy"</span>
  width=<span class="hljs-string">"960"</span>
  height=<span class="hljs-string">"600"</span>
  decoding=<span class="hljs-string">"async"</span>
  data-nimg=<span class="hljs-string">"1"</span>
  style=<span class="hljs-string">"color:transparent"</span>
  sizes=<span class="hljs-string">"(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"</span>
  srcset=<span class="hljs-string">"
    https://res.cloudinary.com/&lt;Cloud Name&gt;/image/upload/c_limit,w_256/f_auto/q_auto/v1/&lt;Public ID&gt; 256w,
    https://res.cloudinary.com/&lt;Cloud Name&gt;/image/upload/c_limit,w_384/f_auto/q_auto/v1/&lt;Public ID&gt; 384w,
    https://res.cloudinary.com/&lt;Cloud Name&gt;/image/upload/c_limit,w_640/f_auto/q_auto/v1/&lt;Public ID&gt; 640w,
    https://res.cloudinary.com/&lt;Cloud Name&gt;/image/upload/c_limit,w_750/f_auto/q_auto/v1/&lt;Public ID&gt; 750w,
    https://res.cloudinary.com/&lt;Cloud Name&gt;/image/upload/c_limit,w_828/f_auto/q_auto/v1/&lt;Public ID&gt; 828w,
    https://res.cloudinary.com/&lt;Cloud Name&gt;/image/upload/c_limit,w_1080/f_auto/q_auto/v1/&lt;Public ID&gt; 1080w,
    https://res.cloudinary.com/&lt;Cloud Name&gt;/image/upload/c_limit,w_1200/f_auto/q_auto/v1/&lt;Public ID&gt; 1200w,
    https://res.cloudinary.com/&lt;Cloud Name&gt;/image/upload/c_limit,w_1920/f_auto/q_auto/v1/&lt;Public ID&gt; 1920w,
    https://res.cloudinary.com/&lt;Cloud Name&gt;/image/upload/c_limit,w_2048/f_auto/q_auto/v1/&lt;Public ID&gt; 2048w,
    https://res.cloudinary.com/&lt;Cloud Name&gt;/image/upload/c_limit,w_3840/f_auto/q_auto/v1/&lt;Public ID&gt; 3840w
  "</span>
  src=<span class="hljs-string">"https://res.cloudinary.com/&lt;Cloud Name&gt;/image/upload/c_limit,w_3840/f_auto/q_auto/v1/&lt;Public ID&gt;"</span>
&gt;
</code></pre>
<p>Where the image is automatically generated on the fly with Cloudinary by passing in a URL parameter of <code>w_&lt;width&gt;</code>.</p>
<h3 id="heading-additional-functionalities">Additional Functionalities</h3>
<p><code>Next Cloudinary</code> is more than file uploading and image optimization. It offers a range of additional features, like video transformations, responsive media handling, and even watermarking, which makes it incredibly versatile. By directly leveraging Cloudinary’s core strengths in Next.js, you can build highly performant, scalable applications without worrying about intricate asset management.</p>
<h3 id="heading-a-common-mistake-that-i-made-should-be-aware">A Common Mistake That I Made - Should Be Aware</h3>
<p>When configuring <strong>Next Cloudinary</strong> in your project, one easy-to-overlook step involves setting the correct environment variables. Specifically, when you configure Cloudinary with the cloud name, API key, and secret key, make sure that the <code>cloud_name</code> and <code>api_key</code> values are prefixed with <code>NEXT_PUBLIC_</code>. This ensures that they are exposed to both the client and server environments in Next.js.</p>
<p>Here’s the correct way to set up the configuration:</p>
<pre><code class="lang-javascript">cloudinary.config({
    <span class="hljs-attr">cloud_name</span>: process.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME,
    <span class="hljs-attr">api_key</span>: process.env.NEXT_PUBLIC_CLOUDINARY_API_KEY,
    <span class="hljs-attr">api_secret</span>: process.env.CLOUDINARY_API_SECRET,
});
</code></pre>
<p>If you skip this prefix for the <code>cloud_name</code> or <code>api_key</code>, you’ll likely encounter an error such as:</p>
<pre><code class="lang-bash">vbnetCopy codeError: A Cloudinary API Key is required <span class="hljs-keyword">for</span> signed requests, please make sure your environment variable is <span class="hljs-built_in">set</span> and configured <span class="hljs-keyword">in</span> your environment.
</code></pre>
<p>In my case, I mistakenly forgot to add the <code>NEXT_PUBLIC_</code> prefix to the API key, leading to the above error. Here's what my incorrect code looked like:</p>
<pre><code class="lang-javascript">cloudinary.config({
    <span class="hljs-attr">cloud_name</span>: process.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME,
    <span class="hljs-attr">api_key</span>: process.env.CLOUDINARY_API_KEY,       <span class="hljs-comment">// Missing NEXT_PUBLIC_ prefix</span>
    <span class="hljs-attr">api_secret</span>: process.env.CLOUDINARY_API_SECRET,
});
</code></pre>
<p>Ensuring that the environment variables are correctly prefixed with <code>NEXT_PUBLIC_</code> is essential for avoiding such issues when using Cloudinary in both server-side and client-side code.</p>
<blockquote>
<p>Note: If you don't use the NEXT_PUBLIC_ you will still be able to get the values ​​on the API route in next js. but according to my research and experience, Next Cloudinary expects the env variable to be with that prefix. So, even if you get the value on the console, still it won't work.</p>
</blockquote>
<h3 id="heading-resources">Resources</h3>
<ul>
<li><p><a target="_blank" href="https://next.cloudinary.dev/">https://next.cloudinary.dev/</a></p>
</li>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/69743178/how-to-fix-cloudinary-error-must-supply-api-key">https://stackoverflow.com/questions/69743178/how-to-fix-cloudinary-error-must-supply-api-key</a></p>
</li>
<li><p><a target="_blank" href="https://community.cloudinary.com/discussion/742/missing-dependency-signed-upload-requires-an-api-key">https://community.cloudinary.com/discussion/742/missing-dependency-signed-upload-requires-an-api-key</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[fatal: not possible to fast-forward, aborting Error solution]]></title><description><![CDATA[As a developer, we often encounter error messages that can be perplexing. One such common Git error is "fatal: not possible to fast-forward, aborting." In this article, we will dive into this error and try to understand what this error is all about, ...]]></description><link>https://robiul.dev/fatal-not-possible-to-fast-forward-aborting-error-solution</link><guid isPermaLink="true">https://robiul.dev/fatal-not-possible-to-fast-forward-aborting-error-solution</guid><category><![CDATA[Git]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Mon, 29 Apr 2024 07:48:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714376416779/5a823fe1-71d2-41ae-8fab-f688521610f8.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As a developer, we often encounter error messages that can be perplexing. One such common Git error is "fatal: not possible to fast-forward, aborting." In this article, we will dive into this error and try to understand what this error is all about, the concept of fast-forward merges, why this error occurs, and discuss effective solutions to this error.</p>
<h2 id="heading-understand-the-error-message">Understand the error message</h2>
<p>It is important to understand the error message Before discussing the reason and solution of the error. Understanding the error message can make our work much easier.</p>
<p>let's break down the error message word by word to understand its components:</p>
<p>The first word of the error message is "fatal". In the Git error message the word "fatal" basically means that the current operation cannot be completed, and you need to take corrective actions to resolve the issue.</p>
<p>"not possible to fast-forward" This segment explains the nature of the error. The message indicates that, under the current conditions, a <a target="_blank" href="https://blog.mergify.com/what-is-a-git-merge-fast-forward/">fast-forward</a> merge is not possible.</p>
<p>At last The term "aborting" indicates that Git is canceling the ongoing operation. In the context of this error, Git cannot proceed with the intended merge operation due to the inability to perform a fast-forward merge.</p>
<p>Now if we put it all together, the error message is saying that an issue has been encountered during an attempted merge operation. The desired fast-forward merge is not possible, and Git is aborting the operation.</p>
<p>In real life scenario, this is a common Git error, which usually pops up when you do a Git pull from a remote branch.</p>
<blockquote>
<p>Note: A "fast-forward" merge in Git is a type of merge that occurs when the target branch (the branch being merged into) has not diverged from the source branch (the branch being merged) since the last commit and can be directly updated with the new commits from another branch.</p>
<p>By default git always try to perform fast-forward merge if the feature branch contains a sequence of commits that can be “joined” to the current main branch, then Git will “fast-forward” those commits into main, instead of merge.</p>
<p>A fast-forward merge is recommended to be used for complex conflicts. Instead, you should use other ways to merge them.</p>
</blockquote>
<h2 id="heading-the-reason-for-fast-forward-is-not-possible">The reason for fast-forward is not possible</h2>
<p>If there are Divergent Histories or Diverging branches then the fast-forward commit is not possible.</p>
<p>In the context of Git, divergent changes refer to alterations made independently on both the branch being merged (feature_branch) and the target branch (main).</p>
<p>For example: Let's imagine the situation where someone adds a commit to the remote branch and at the same time you add a commit to the local branch.</p>
<p>Now when you run git pull in this situation. Git will try to fast-forward those commits but it won't be able to do that and will run a 'fatal: not possible to fast-forward, aborting' error. Because there is an extra commit on the local branch that doesn’t exist on the remote branch.</p>
<p>In short, When two branches have separate commit histories that don't form a linear sequence, Git cannot perform a fast-forward merge.</p>
<h2 id="heading-possible-fixes-for-the-error">Possible Fixes for the error</h2>
<p>There is no magic fix for the "fatal: Not possible to fast-forward, aborting" error. Your approach depends on what you're aiming for.</p>
<p>Here are some common options:</p>
<h3 id="heading-changing-the-default-settings">Changing the default settings</h3>
<p>One simple way we can apply to solve error is changing the default behavior of git prevent fast-forward merges and always create a new merge commit, even in cases where a fast-forward is possible.</p>
<p>To inspect the configuration and determine whether the pull.ff setting is configured to only, developers can use the following commands: Check pull.ff Setting:</p>
<pre><code class="lang-bash">git config pull.ff
</code></pre>
<blockquote>
<p>If you don't get any output after running this command, it typically indicates that the pull.ff configuration setting is not defined in any of the configuration files. Git will then fall back to its default behavior for handling merges when pulling changes.</p>
</blockquote>
<p>To change the pull.ff (git pull regarding fast-forward merges) configuration, you can use the following commands:</p>
<p>Remove Default Setting:</p>
<pre><code class="lang-bash">git config --<span class="hljs-built_in">unset</span> pull.ff
</code></pre>
<p>Set pull.ff to Another Value (e.g., true for <a target="_blank" href="https://git-scm.com/docs/git-rebase">rebase</a>):</p>
<pre><code class="lang-bash">git config pull.ff <span class="hljs-literal">true</span>
</code></pre>
<p>Adjusting the configuration might be necessary based on the project's requirements or the preferred merging strategy. If a project involves workflows where non-fast-forward merges are acceptable or necessary, developers might choose to configure pull.ff differently.</p>
<h3 id="heading-making-commit-manually-rebasemerge">Making commit manually (rebase/merge)</h3>
<p><a target="_blank" href="https://www.w3schools.com/git/git_branch_merge.asp?remote=github">Merge</a> commits are a tremendously useful tool in Git, but they can also add a layer of complexity. That is why it is better to create a merge commit manually without depending on Git to automatically do it for you by changing the default settings.</p>
<p>let's see an example situation and how to solve it.</p>
<p>For example: You're working on a feature branch called feature/new-feature where you've made several commits to implement a new feature. Meanwhile, the main branch has also progressed with new commits from other team members. Now you decide to integrate the changes from the main branch into your <code>feature/new-feature</code> branch to ensure your feature is up-to-date with the latest changes. You run <code>git pull origin main</code> while on the <code>feature/new-feature</code> branch to pull changes from the main branch. but you got the error <code>fatal: Not possible to fast-forward, aborting</code></p>
<p>We can solve this issue in two ways. Let's see both of them:</p>
<ol>
<li><p>Rebase Your Commits:</p>
<p> Rebasing is an important Git topic that deserves an entire article of its own. In short, It essentially rewrites the commit history by placing your changes on top of the latest changes from another branch. This helps to create a linear project history and can facilitate smoother integration of changes from different branches.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714376448169/2fb2fb21-0574-4df7-b940-e4771fc5ae9d.webp" alt="git rebase" class="image--center mx-auto" /></p>
<p> If you want to maintain a clean and linear history without unnecessary merge commits, rebasing is a good choice.</p>
<p> To solve the issue using rebase, first of all, Determine which branch you want to merge your changes into. This is typically the branch you want to update with your changes, such as the main.</p>
<p> Use the git rebase command to reapply your local commits onto the target branch. Here's how you can do it:</p>
<pre><code class="lang-bash"> git checkout feature/new-feature git rebase main
</code></pre>
<p> This command sequence switches to your feature branch (<code>feature/new-feature</code>) and then release your commits onto the <code>main</code> branch. If there are conflicts between your changes and the changes on the target branch (<code>main</code>), Git will pause the rebase process and prompt you to resolve these conflicts manually. You'll need to edit the conflicted files, stage the changes, and continue the rebase process until all conflicts are resolved.</p>
<p> Once all conflicts are resolved, you can continue the rebase process by using the following command:</p>
<pre><code class="lang-bash"> git rebase --<span class="hljs-built_in">continue</span>
</code></pre>
<p> This command tells Git to continue applying the remaining commits in the rebase operation.</p>
<p> Finally, push the rebased changes to the remote repository if applicable, using git push. Since you've rewritten history with the rebased commits, you may need to force-push if you've already pushed your feature branch to the remote repository:</p>
<pre><code class="lang-bash"> git push origin feature/new-feature --force
</code></pre>
<p> However, force-pushing can be risky, especially if others are also working on the same branch. If someone else has pulled the branch before you force-push, their local copy of the branch will become out of sync with the remote repository, leading to potential confusion and conflicts.</p>
</li>
<li><p>Perform a Regular Merge:</p>
<p> Regular merging creates a merge commit that explicitly shows the merge point and preserves the individual commit history of both branches.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1714376491456/60f3a7cd-4c6c-4917-97ee-a033bedb7f30.webp" alt="git merge" class="image--center mx-auto" /></p>
<p> If maintaining the independence of branches and clearly documenting points of divergence and integration is important, regular merging is a better choice.</p>
<p> Switch to the target branch you want to merge into Using git checkout or git switch</p>
<pre><code class="lang-bash"> git checkout feature/new-feature
</code></pre>
<p> Use git merge to merge the source branch into the target branch. Git will create a merge commit to reconcile the changes.</p>
<pre><code class="lang-bash"> git merge source_branch
</code></pre>
<p> If Git encounters conflicts during the merge, you'll need to resolve them manually.</p>
<p> After resolving conflicts, commit the changes.</p>
<pre><code class="lang-bash"> git commit -m <span class="hljs-string">"Merge branch 'source_branch' into 'target_branch'"</span>
</code></pre>
<p> If you're working with a remote repository, don't forget to push the changes.</p>
<pre><code class="lang-bash"> git push origin target_branch
</code></pre>
<p> these should solve the error.</p>
<blockquote>
<p>When faced with the "fatal: not possible to fast-forward, aborting" error in Git, developers need to explore the commit history and identify the divergence between their current branch and the target branch.</p>
<p>To understand the divergence, utilize the following command to view the commit history of both your current branch and the target branch:</p>
<pre><code class="lang-bash">git <span class="hljs-built_in">log</span> --graph --oneline HEAD &lt;some/branch&gt;
</code></pre>
<p>This command provides a graphical representation of the commit history, highlighting any divergent changes between the two branches.</p>
</blockquote>
</li>
</ol>
<h2 id="heading-resources">Resources</h2>
<ul>
<li><p><a target="_blank" href="https://www.atlassian.com/git/tutorials/using-branches/git-merge">Git merge</a></p>
</li>
<li><p><a target="_blank" href="https://linuxpip.org/fix-fatal-not-possible-to-fast-forward-aborting-in-git">How I fixed “fatal: Not possible to fast-forward, aborting”</a></p>
</li>
<li><p><a target="_blank" href="https://salferrarello.com/git-warning-pulling-without-specifying-how-to-reconcile-divergent-branches-is-discouraged/">Git warning: Pulling without specifying how to reconcile divergent branches is discouraged</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Cannot redeclare block-scoped variable in TypeScript [Fixed]]]></title><description><![CDATA[In TypeScript, developers often run into the "Cannot redeclare block-scoped variable" error. This issue arises primarily from two reasons:

Variable Redeclaration in the Same Block Scope: When you attempt to declare a variable with the same name agai...]]></description><link>https://robiul.dev/cannot-redeclare-block-scoped-variable-in-typescript-fixed</link><guid isPermaLink="true">https://robiul.dev/cannot-redeclare-block-scoped-variable-in-typescript-fixed</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[error handling]]></category><category><![CDATA[error]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Sat, 02 Dec 2023 14:40:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1701462077875/edc24eaf-2ef6-4ed3-b33f-ab15d254a02f.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In TypeScript, developers often run into the "Cannot redeclare block-scoped variable" error. This issue arises primarily from two reasons:</p>
<ol>
<li><p><strong>Variable Redeclaration in the Same Block Scope:</strong> When you attempt to declare a <a target="_blank" href="https://robiul.dev/javascript-variables-beginner-thinking">variable</a> with the same name again within the same block scope.</p>
</li>
<li><p><strong>Conflict with TypeScript Global Typings:</strong> When your chosen variable names clash with TypeScript's global typings.</p>
</li>
</ol>
<p>This article will delve into both of these reasons, providing detailed explanations and offering solutions to address this common TypeScript issue.</p>
<h2 id="heading-variable-redeclaration-in-the-same-block-scope"><strong>Variable Redeclaration in the Same Block Scope</strong></h2>
<p>When you have two variables with the same name within the same scope, it triggers the "Cannot redeclare block-scoped variable" error. This happens because, during declaration, a variable's value is stored in memory. If you try to declare another variable with the same name in the same scope, it attempts to save it in the same memory location, leading to an error.</p>
<p>Here's an illustrative example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> myVar = <span class="hljs-string">"Hello"</span>;  

<span class="hljs-keyword">let</span> myVar = <span class="hljs-string">"World"</span>; <span class="hljs-comment">// Error: Cannot redeclare block-scoped variable 'myVar'.   </span>

<span class="hljs-built_in">console</span>.log(myVar);
</code></pre>
<p>In this example, the error occurs when attempting to redeclare <code>myVar</code> because <code>let</code> variables have <a target="_blank" href="https://www.geeksforgeeks.org/javascript-es2015-block-scoping/">block-level scope</a>. The inner <code>myVar</code> is perceived as a redeclaration within the same block, leading to the error.</p>
<h3 id="heading-solution-1-update-the-existing-variable-without-re-declaring-it">Solution 1: Update the existing variable without re-declaring it</h3>
<p>To avoid this error, a straightforward solution is to update the existing variable rather than declaring it anew.</p>
<p>If you're looking to assign a new value to the variable, the proper approach involves initially declaring it with <a target="_blank" href="https://www.w3schools.com/js/js_let.asp"><code>let</code></a> and subsequently changing its value without redeclaring.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> myVar = <span class="hljs-string">"Hello"</span>;  

myVar = <span class="hljs-string">"World"</span>; 

<span class="hljs-built_in">console</span>.log(myVar); <span class="hljs-comment">// 👉️ "World"</span>
</code></pre>
<p>Unlike <a target="_blank" href="https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/"><code>const</code></a> and <code>let</code>, variables declared with <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var"><code>var</code></a> can be redeclared.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">var</span> myVar = <span class="hljs-string">"Hello"</span>;  

<span class="hljs-keyword">var</span> myVar = <span class="hljs-string">"World"</span>;

<span class="hljs-built_in">console</span>.log(myVar); <span class="hljs-comment">// 👉️ World</span>
</code></pre>
<p>However, note that the <code>var</code> keyword behaves less intuitively and is generally advised against.</p>
<h3 id="heading-solution-2-use-different-variable-names">Solution 2: Use Different Variable Names</h3>
<p>Another effective strategy to circumvent this error is to employ unique names for different variables.</p>
<p>Consider the following TypeScript snippet as an example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"Hello"</span>;

<span class="hljs-keyword">let</span> newGreeting = <span class="hljs-string">"World"</span>; <span class="hljs-comment">// Introduce a distinct variable name.</span>

<span class="hljs-built_in">console</span>.log(greeting); <span class="hljs-comment">// This is perfectly acceptable.</span>
<span class="hljs-built_in">console</span>.log(newGreeting); <span class="hljs-comment">// This is perfectly acceptable.</span>
</code></pre>
<p>By selecting different names for variables within the same block, you not only mitigate the error but also enhance the readability of your code. This practice aligns with best coding practices and facilitates collaboration among developers.</p>
<p>Remember, clear and unique variable names are not just about solving errors; they significantly contribute to the overall robustness and comprehensibility of your codebase.</p>
<h3 id="heading-solution-3-change-the-variables-scope">Solution 3: Change the variable's scope</h3>
<p>If you prefer maintaining identical names for variables, an alternative is to modify the scope of one of the variables. By declaring a variable with the same name in a nested block, you establish a clear distinction between the variable in the outer scope and the one in the inner scope.</p>
<p>Let's illustrate this using TypeScript:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"Hello"</span>;
<span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
   <span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"World"</span>;    
    <span class="hljs-built_in">console</span>.log(greeting); <span class="hljs-comment">// World </span>
}  
<span class="hljs-built_in">console</span>.log(greeting); <span class="hljs-comment">// Hello</span>
</code></pre>
<p>In this scenario, the two <code>greeting</code> variables coexist harmoniously due to their existence in different scopes. The initial <code>greeting</code> variable resides within the <a target="_blank" href="https://web.dev/articles/global-and-local-scope#:~:text=Variables%20with%20module%20scope%20are,needs%20to%20access%20the%20variable.">module's scope,</a> while the subsequent one finds its scope within the block.</p>
<p>Crucially, this scope-adjusting approach isn't confined to <a target="_blank" href="https://www.w3schools.com/js/js_if_else.asp"><code>if</code></a> blocks; it can be applied to any nested block delineated by curly braces (<code>{</code> and <code>}</code>). The syntax involving curly braces allows for the creation of distinct blocks.</p>
<p>Here is the same example, without the <code>if</code> statement.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"Hello"</span>;
{
   <span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"World"</span>;    
    <span class="hljs-built_in">console</span>.log(greeting); <span class="hljs-comment">// World </span>
}  
<span class="hljs-built_in">console</span>.log(greeting); <span class="hljs-comment">// Hello</span>
</code></pre>
<p>However, having variables with the same name in different scopes might confuse those reading your code. As a best practice, it's advisable to steer clear of such naming conflicts.</p>
<blockquote>
<p>Note: Using the <code>var</code> keyword for this approach would modify the value of the outer variable. This exemplifies one of the many reasons why the usage of <code>var</code> is discouraged.</p>
</blockquote>
<h2 id="heading-conflict-with-typescript-global-typings"><strong>Conflict with TypeScript Global Typings</strong></h2>
<p>If you're encountering the "Cannot redeclare block-scoped variable" error, but you're certain there's no duplicate variable with the same name. likely, you've inadvertently attempted to modify the <a target="_blank" href="https://www.w3schools.com/js/js_scope.asp">global scope</a>.</p>
<p>Let's unravel this scenario through an illustration:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> name = <span class="hljs-string">"Robiul"</span>;
<span class="hljs-comment">// Cannot redeclare block-scoped variable 'name'.</span>
</code></pre>
<p>Wait a minute! There's just one variable named <code>name</code> in our file. What's causing the hiccup?</p>
<p>When TypeScript encounters a file devoid of import or export declarations, it categorizes it as a script rather than a module. It makes its contents available in the global scope and to other modules.</p>
<p>Therefore, when an attempt is made to declare a variable with a name already in use, TypeScript raises an error.</p>
<p>Here's a practical example showcasing how this error manifests:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// ⛔️ Error: Cannot redeclare block-scoped variable 'name'.ts(2451)</span>
<span class="hljs-comment">// lib.dom.d.ts(17330, 15): 'name' was also declared here.</span>
<span class="hljs-keyword">const</span> name = <span class="hljs-string">"Robiul Hasan"</span>;
</code></pre>
<p>In this instance, the <code>name</code> variable is declared somewhere in the typings for the DOM library, leading to a clash between the global type definition and the local variable declaration.</p>
<h3 id="heading-solution-1-convert-your-file-to-an-es-module">Solution 1: Convert your file to an ES module</h3>
<p>To fix the error, convert your file to an <a target="_blank" href="https://www.knowledgehut.com/blog/web-development/commonjs-vs-es-modules">ES module</a>, like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"Hello"</span>;

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

<span class="hljs-keyword">export</span> {};
</code></pre>
<p>By introducing this export statement, you've effectively signaled TypeScript to treat the file as a module, eliminating the error stemming from the clash between global scope and local variable declarations.</p>
<blockquote>
<p>Note: If you are working in a project where each file is treated as a module rather than a script, you can adjust your TypeScript configuration to force module detection in your <code>tsconfig.json</code>.</p>
<p>Enabling <code>moduleDetection</code> with the value <code>force</code> instructs TypeScript to treat every file as a module, irrespective of whether it contains imports or exports.</p>
<p>Here's an example configuration snippet for your <code>tsconfig.json</code>:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"compilerOptions"</span>: {
    <span class="hljs-attr">"moduleDetection"</span>: <span class="hljs-string">"force"</span>
  }
}
</code></pre>
</blockquote>
<h3 id="heading-solution-2-use-an-immediately-invoked-function-expressioniife">Solution 2: Use an immediately invoked function expression(IIFE)</h3>
<p>Another effective solution is employing an Immediately Invoked Function Expression (<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE">IIFE</a>). This technique involves encapsulating the code segment containing the variable within a function that executes as soon as it's defined.</p>
<p>Here's a practical illustration:</p>
<pre><code class="lang-javascript">(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// ✅ works as expected</span>
  <span class="hljs-keyword">let</span> greeting = <span class="hljs-string">"Hello"</span>;
  <span class="hljs-built_in">console</span>.log(greeting); <span class="hljs-comment">// Hello //</span>
})();
</code></pre>
<p>In this setup, the IIFE executes immediately upon script execution, ensuring the inner variable doesn't conflict with the global scope, providing a straightforward yet powerful resolution. This approach enhances code organization and maintains variable isolation.</p>
<h2 id="heading-resources">Resources</h2>
<ul>
<li><p><a target="_blank" href="https://bobbyhadz.com/blog/typescript-cannot-redeclare-block-scoped-variable"><strong>Cannot redeclare block-scoped variable in TypeScript [Fixed]</strong></a></p>
</li>
<li><p><a target="_blank" href="https://www.totaltypescript.com/cannot-redeclare-block-scoped-variable"><strong>Explained: Cannot redeclare block-scoped variable</strong></a></p>
</li>
<li><p><a target="_blank" href="https://www.codingbeautydev.com/blog/typescript-cannot-redeclare-block-scoped-variable"><strong>How to Fix the "Cannot redeclare block-scoped variable" Error in TypeScript</strong></a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Unsaved Changes Alert and Unsubmitted Data Preservation on Page Exit in React App]]></title><description><![CDATA[Hello fellow developers,
Today, we're delving into a fascinating topic that you may have encountered while using Facebook. You might have noticed a popup while crafting a post - Changes you made may not be saved - when attempting to leave the page mi...]]></description><link>https://robiul.dev/unsaved-changes-alert-and-unsubmitted-data-preservation-on-page-exit-in-react-app</link><guid isPermaLink="true">https://robiul.dev/unsaved-changes-alert-and-unsubmitted-data-preservation-on-page-exit-in-react-app</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Sun, 26 Nov 2023 02:00:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1700668889704/07984cf9-8ec7-463a-af67-5079f2736e17.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello fellow developers,</p>
<p>Today, we're delving into a fascinating topic that you may have encountered while using Facebook. You might have noticed a popup while crafting a post - <code>Changes you made may not be saved</code> - when attempting to leave the page midway through your creative process. It's a feature that has caught our attention, and today, I'll show you how to implement this in your React project using React Router Dom V6.</p>
<p>Now, you might be thinking, "Isn't this simple to implement using the browser's <a target="_blank" href="https://www.javascripttutorial.net/javascript-dom/javascript-beforeunload-event/#:~:text=Introduction%20to%20JavaScript%20beforeunload%20event&amp;text=If%20a%20webpage%20has%20a,you%20to%20the%20new%20page."><code>beforeUnload</code></a> event?" Well, the answer is a bit more complex. While it's indeed straightforward for multi-page applications, it's a different story when it comes to single-page applications. The <code>beforeUnload</code> event behaves seamlessly on the home page but doesn't play as nicely on other pages.</p>
<p>Additionally, React Router Dom v5 provides a few methods, such as <a target="_blank" href="https://v5.reactrouter.com/core/api/Prompt"><code>Prompt</code></a> and <code>unsafe_navigationcontext</code>, for implementing this feature. However, these approaches are not applicable in the latest version of <a target="_blank" href="https://reactrouter.com/en/main/start/overview">React Router Dom(v6)</a>. In this version, there's no direct, out-of-the-box solution for our task.</p>
<p>My journey with this feature began when I encountered these very challenges. I decided to dig deeper, and it took me more than one week to delve into the depths of research. What I found not only solved the problem but also expanded my understanding of React and React Router Dom.</p>
<p>So, let's dive into this journey together.</p>
<h2 id="heading-what-is-this-article-all-about">What is this article all about?</h2>
<p>This article is not like the so-called tutorial on the internet also this article is not similar to my other articles where I try to share my knowledge on different programming topics with you guys.</p>
<p>In this article I will go one step further I will cover the topic but in a storic way.</p>
<p>Basically, In this article, I am going to share my experience of doing research on this in-depth and what I have learned. it's like a demonstration of my journey of finding the best way to implement the feature.</p>
<p>I will take you through the whole journey how it began, how I got the minimal solution, What were its pros and cons, how I found better solutions, and lastly how I ended up my the journey by finding the solution that I was looking for.</p>
<p>Also, I will try to explain to you some tricky parts of the code so that you can understand what's going on and why things are going this way.</p>
<p>Since it's an article, I will try to bind myself just inside react and react-router dom without talking about multiple things in the same place. So that it feels much more relevant to you but at the same time I will try to cover all the things as much as possible to give you a taste of my one week journey.</p>
<p>So, be patient and read the whole article I believe you will learn lots of new things from this article.</p>
<p>But those who are in a hurry or only interested in the ultimate way to implement the feature can read the portion directly going to that part. Because I will cover three ways of making this feature and the first two ways are not recommended to use in your code.</p>
<p>Actually, these may work for you but when you have the better solution then why would take the least?</p>
<p>That's why you are most welcome to read only the ultimate solution from <a class="post-section-overview" href="#heading-using-unstableuseblocker-from-react-router-dom"><code>Using unstable_useBlocker from React Router Dom</code></a> section skipping other portions.</p>
<p>Too much talk, now let's get started.</p>
<h2 id="heading-what-do-we-intend-to-make">What do we intend to make?</h2>
<p>First let's have a look at what exactly we are going to make, because, before starting the actual implementation we must have a proper idea of what we intend to make.</p>
<p>So, let's see a demonstration of the project we are going to make.</p>
<p>We will make a simple react app which will have simple and minimal two pages. The first one will be our home page and the second one will be a subroute or subpage name profile page. All these two pages will have a nav section on top of these pages and a form section at the center of these pages.</p>
<p>Here are the visualizations of these two pages.</p>
<p>Home page:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697013753141/059528d3-a267-4b24-9744-6b8ff8b71dc1.png" alt="home page" class="image--center mx-auto" /></p>
<p>Profile page:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697903279917/f3f4bf2c-cb15-42b5-b637-85c1062ec782.png" alt="profile page" class="image--center mx-auto" /></p>
<p>Now on these pages when we enter something on the form input and if we try to leave the page we will get a prompt like this one:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697905114797/7118ad2c-8b19-434a-ab5b-f372ca9c24d2.png" alt="unsaved changes alert" class="image--center mx-auto" /></p>
<p>This prompt will be a little different for the profile page. But the main thing to consider is we will get a prompt like this instead of directly leaving the page. and if we select the cancel button this will keep us on this page and if we select the leave button this will leave the page.</p>
<p>Also when we get back to the page our typed data should be here as we had left it. For our scenario on the image on the top we are leaving the page with the value <code>4</code> for the first input field and when we get back to this page again this <code>4</code> should be here in the same input field.</p>
<p>We will build this functionality on both pages in our application because as I already mentioned the home route and other routes don't work in the same way in react router dom.</p>
<p>Here is the live link to this project:</p>
<p>link: <a target="_blank" href="https://prevent-unsaved-changes-page-leave.vercel.app/">https://prevent-unsaved-changes-page-leave.vercel.app/</a></p>
<h2 id="heading-starter-code-to-start-implementation">Starter code to start implementation</h2>
<p>To start with this article you will have to get the starter setup of the project that we are going to make. I have hosted all code inside this <a target="_blank" href="https://github.com/robiulhr/prevent-unsaved-changes-page-leave/">repo</a>.</p>
<p>Just clone the repo running this command on your terminal</p>
<pre><code class="lang-bash">git <span class="hljs-built_in">clone</span> https://github.com/robiulhr/prevent-unsaved-changes-page-leave.git
</code></pre>
<p>then open the project on the terminal and change the directory to <code>starter_code</code> directory</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> ./starter_code
</code></pre>
<p>and then install all dependencies of the project running this command:</p>
<pre><code class="lang-bash">npm install
</code></pre>
<p>inside the <code>starter_code</code> the folder structure will look like this after running the <code>npm install</code></p>
<pre><code class="lang-plaintext">├── node_modules
├── src
   ├── component
   |  └── Form.jsx
   |  └── Nav.jsx
   ├── pages
   |  └── Home.jsx
   |  └── Profile.jsx
   ├── reducer
   |  └── formReducer.jsx
   ├── main.jsx
├── .gitignore
├── index.html
├── package-lock.json
├── package.json
├── README.md
├── style.css
├── vite.config.js
</code></pre>
<p>If everything is alright then start the project by running this command:</p>
<pre><code class="lang-bash">npm run dev
</code></pre>
<p>That's it you are ready to go with the rest article.</p>
<h2 id="heading-beforeunload-event-to-prevent-page-leave-from-home-page"><code>beforeunload</code> event to prevent page leave from Home page</h2>
<p>If you search on the internet about the ways of preventing page leave the way you will find most of the answers is by using <code>beforeunload</code>. This is the easiest and most widely used way of preventing page leave on a website.</p>
<p>So, let's try to implement this in our project.</p>
<p>replace the whole code of <code>Home.jsx</code> the file with this code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Home.jsx</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">"../../style.css"</span>;
<span class="hljs-keyword">import</span> Nav <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/Nav"</span>;
<span class="hljs-keyword">import</span> Form <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/Form"</span>;
<span class="hljs-keyword">import</span> { useEffect, useState, useReducer, useCallback } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> formReducer <span class="hljs-keyword">from</span> <span class="hljs-string">"../reducer/formReducer"</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Home</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [dirty, setDirty] = useState(<span class="hljs-literal">false</span>);
  <span class="hljs-keyword">const</span> [formData, dispatch] = useReducer(formReducer, {
    <span class="hljs-attr">name</span>: <span class="hljs-string">""</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">""</span>,
  });
  <span class="hljs-keyword">const</span> beforeunloadHandler = useCallback(
    <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
      <span class="hljs-keyword">if</span> (dirty) {
        e.preventDefault();
        e.returnValue = <span class="hljs-string">""</span>;
      }
    },
    [dirty]
  );

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">"beforeunload"</span>, beforeunloadHandler);
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">window</span>.removeEventListener(<span class="hljs-string">"beforeunload"</span>, beforeunloadHandler);
    };
  }, [beforeunloadHandler]);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Nav</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome to Home Page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Form</span> <span class="hljs-attr">formData</span>=<span class="hljs-string">{formData}</span> <span class="hljs-attr">setDirty</span>=<span class="hljs-string">{setDirty}</span> <span class="hljs-attr">dispatch</span>=<span class="hljs-string">{dispatch}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Home;
</code></pre>
<p>And the whole code of <code>Form.jsx</code> file with this code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Form</span> (<span class="hljs-params">{setDirty,formData, dispatch}</span>) </span>{
 <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">nameChangeHandler</span>(<span class="hljs-params">e</span>) </span>{
    dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">"change_name"</span>, <span class="hljs-attr">name</span>: e.target.value });
    setDirty(<span class="hljs-literal">true</span>)
  }
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">emailChangeHandler</span>(<span class="hljs-params">e</span>) </span>{
    dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">"change_email"</span>, <span class="hljs-attr">email</span>: e.target.value });
    setDirty(<span class="hljs-literal">true</span>)    
  }

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">'form-wrapper'</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">div</span>&gt;</span>
             <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{nameChangeHandler}</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{formData.name}</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"name"</span> /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{emailChangeHandler}</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{formData.email}</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"email"</span> <span class="hljs-attr">placeholder</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">'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">div</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">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  )
}
</code></pre>
<p>What are we doing here is that we have defined a state using the <code>useState</code> hook and we named it <code>dirty</code>. Then we are passing the <code>setter function</code> or <code>state updater function</code> <code>setDirty</code> to the form component. Depending on the <code>dirty</code> state value <code>true</code> or <code>false</code> we are adding the <code>beforeunload</code> event to the home page inside the <code>useEffect</code> hook which will run every time the <code>dirty</code> state gets updated.</p>
<p>Inside the Form page, we receive the <code>setDirty</code> function, after that, we use this function inside the <code>nameChangeHandler</code> and <code>emailChangeHandler</code> function so that it's the value of <code>dirty</code> state gets <code>true</code> when users write something on the form input fields.</p>
<p>Now run the project and write something on the home page from inputs.</p>
<p>then try to leave the page using the browser back button</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697988827913/09e5a0fe-af05-47d8-8fa9-1ea93599d39e.png" alt="browser's back button" class="image--center mx-auto" /></p>
<p>or manually typing on the URL bar</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697989008616/859bb73c-bd5d-49d9-ac8c-38970f689878.png" alt="browser's url bar" class="image--center mx-auto" /></p>
<p>you won't be able to leave the page instead you will get a popup like this.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697905114797/7118ad2c-8b19-434a-ab5b-f372ca9c24d2.png" alt="unsaved changes alert" class="image--center mx-auto" /></p>
<p>Even if you want to close the tab by clicking on the cross button</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697989446375/98f8d342-26f7-4d47-820f-f156369ebf39.png" alt="browser's tab cross button" class="image--center mx-auto" /></p>
<p>you won't be able to do that too.</p>
<p>Also if you want to reload the page you will get a similar kind of error.</p>
<p>So, at this point, we have been able to make the feature workable at some point. we haven't yet thought of links on the page which are in the nav section. Because at this point our app can't prevent page leave for clicking on these links.</p>
<p>We will work with these things in future sections but now our concern is whatever we have achieved at this point these should work on every page of our application.</p>
<p>So, let's check it for other routes of this application. In our case which is the Profile page.</p>
<h2 id="heading-beforeunload-event-to-prevent-page-leave-from-subroutes"><code>beforeunload</code> event to prevent page leave from subroutes</h2>
<p>Now, to implement the same feature replace the existing code of the <code>Profile.jsx</code> page inside the pages directory with the code below:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Profile.jsx</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">"../../style.css"</span>;
<span class="hljs-keyword">import</span> Nav <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/Nav"</span>;
<span class="hljs-keyword">import</span> Form <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/Form"</span>;
<span class="hljs-keyword">import</span> { useCallback, useEffect, useState, useReducer } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> formReducer <span class="hljs-keyword">from</span> <span class="hljs-string">"../reducer/formReducer"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Profile</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [dirty, setDirty] = useState(<span class="hljs-literal">false</span>);
  <span class="hljs-keyword">const</span> [formData, dispatch] = useReducer(formReducer, {
    <span class="hljs-attr">name</span>: <span class="hljs-string">""</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">""</span>,
  });
  <span class="hljs-keyword">const</span> beforeunloadHandler = useCallback(
    <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
      <span class="hljs-keyword">if</span> (dirty) {
        e.preventDefault();
        e.returnValue = <span class="hljs-string">""</span>;
      }
    },
    [dirty]
  );

  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">"beforeunload"</span>, beforeunloadHandler);
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
      <span class="hljs-built_in">window</span>.removeEventListener(<span class="hljs-string">"beforeunload"</span>, beforeunloadHandler);
    };
  }, [beforeunloadHandler]);

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Nav</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome to Profile Page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Form</span> <span class="hljs-attr">setDirty</span>=<span class="hljs-string">{setDirty}</span> <span class="hljs-attr">formData</span>=<span class="hljs-string">{formData}</span> <span class="hljs-attr">dispatch</span>=<span class="hljs-string">{dispatch}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Profile;
</code></pre>
<p>Now run the application and you will see it's working as same as the home page.</p>
<p>But the problem is if we try to use the browser back button to navigate away, it won't work for the profile page as it does for the home page.</p>
<p>Not only that even if you navigate to the profile page from the home page and then come back to the home page using the navigation link which is on the nav bar instead of using the browser back button. And then try out the feature on the home page. You will face the same problem on the home page too.</p>
<p>And from here problems start...</p>
<p>Now the question begins that it was working fine for the home page when we entered the home page directly on an empty tab but why it's not working now and also why it's not working on the profile page or more specifically on subpages?</p>
<h2 id="heading-why-beforeunload-doesnt-work-properly-on-subpages">Why <code>beforeunload</code> doesn't work properly on subpages?</h2>
<p>To answer this question first we have to understand how the web page navigation works how it differs in single-page applications also how <code>beforeunload</code> event fits on both multipage and single-page applications.</p>
<p>Let's start with very basic</p>
<p>When we browse the internet you type a URL or click a link, and a new web page loads in your browser. But what's happening behind the scenes?</p>
<p>When you enter a website, your web browser creates a record of this action in its <code>history</code>. This history is like an itinerary of your online journey. The initial entry into a website becomes the starting point in your browsing history. At this point, browser history doesn't have any previous record since you have started with a fresh empty tab.</p>
<p>Now, as you navigate through the website, each page or state you visit is added to your browser's history.</p>
<p>For every new page, a new entry is pushed into the browser's history. This entry contains information about the URL or location of the page you're visiting.</p>
<p>The <code>Back</code> and <code>Forward</code> buttons in your browser allow you to move between pages. Clicking <code>Back</code> retrieves the previous entry from the history and loads that page. <code>Forward</code> takes you to the next entry, effectively reversing the <code>Back</code> action.</p>
<p>Think of your browser's history as a stack or list of pages. Each new page visited is added to the top of the stack.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700668955969/034e264f-253d-4202-9a21-1c8594005528.webp" alt="browser's history stack" class="image--center mx-auto" /></p>
<p>Clicking <code>Back</code> pops the top page off the stack, loading the previous one.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700668985289/78d334b2-ce0b-4389-8eaf-4b3980e1bfb3.webp" alt="clicking back button browser's history stack" class="image--center mx-auto" /></p>
<p><code>Forward</code> takes you forward in the stack.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700669001897/24d8cb49-14f3-41ae-9d40-9c9bd451a652.webp" alt="clicking forward button browser's history stack" class="image--center mx-auto" /></p>
<blockquote>
<p>Note: Browser's history mechanism doesn't necessarily use a stack data structure in a straightforward sense, but its behavior is conceptually similar to a stack.</p>
</blockquote>
<p>Now let's understand what is the role of <code>beforeunload</code> event on this journey.</p>
<p><code>beforeunload</code> event fires when the page gets unloaded. as we can feel this thing with the name of this event. it's a pretty self-explanatory name <code>beforeunload</code></p>
<p>The <code>beforeunload</code> event plays a vital role in this navigation process.</p>
<p>In the multipage application, every time a user tries to navigate to another page server renders a new page and since the browser renders a new page it's obvious it has unloaded the existing page and here the <code>beforeunload</code> event gets executed. that's why when users attempt to leave a page close a tab or navigate away from a page, the browser triggers the <code>beforeunload</code> event.</p>
<p>On the other hand single page application works that way in that it gets loaded when we first time visit the website and it gets unloaded when we leave the application. between these whenever we change routes browser does not unload anything. it's just making some API requests to get data and applying JavaScript to show this data. no new page is getting loaded. Since changing the route is not unloading anything that's why <code>beforeunload</code> event is not firing. That's the reason inside single page application <code>beforeunload</code> event doesn't work except on the home page.</p>
<p>And same thing happens for the home page if we are not in the first history state that means if we visit another page and come back to the home page by navigating from another page and trying to back to the previous page in that case the <code>beforeunload</code> event won't fire anymore.</p>
<p>In this scenario, our browser's history has some previous page to navigate and that's why it's not leaving the website or unloading anything here it's just navigating us to its previous route.</p>
<p>In a short word, the <code>beforeunload</code> event only fires when any page is getting unloaded. since when we first time visiting a website and then try to go back we are unloading the page here. this thing will work the same way even if we visit the profile directly from an empty tab instead of navigating from other pages to it. On the other hand, the home page <code>beforeunload</code> event won't fire if we navigate to it from another page instead of directly entering the home page in a new tab.</p>
<p>I believe you are now clear about why <code>beforeunload</code> event doesn't work for other routes or sub-pages</p>
<p>To make the explanation more realistic and put some weight on my words let's have a look at how Facebook handles this issue. That will make us more clear on that.</p>
<h2 id="heading-how-does-facebook-prevent-users-from-leaving-the-page">How does Facebook prevent users from leaving the page?</h2>
<p>Let's visit Facebook's home page and try to see a demonstration of the feature that we are working on.</p>
<p>Create a new empty tab on your browser and visit Facebook typing <a target="_blank" href="https://facebook.com/">facebook.com</a> on the URL bar.</p>
<p>Make sure you are logged in and navigating to the home page <a target="_blank" href="https://www.facebook.com/">https://www.facebook.com/</a></p>
<p>now click on the post creation section</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698045777161/ee3614dc-d0f9-4149-9e7a-72c410c0a64e.png" alt="facebook create post section" class="image--center mx-auto" /></p>
<p>A popup will open to create a post. Write something random on the popup.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698045878001/b069a529-97b7-4e88-94a5-dc878160e237.png" alt="facebook create post popup" class="image--center mx-auto" /></p>
<p>Now click on the browser back button without clicking anywhere else.</p>
<p>you will get an alert like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698046120636/a38948b1-8bf0-46ca-960a-e68e13bccad8.png" alt="unsaved changes alert on facebook" class="image--center mx-auto" /></p>
<p>Now go to your profile page clicking on the profile button left side of the page.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698046284304/6f9c5dd4-f819-49ff-a3c1-d1249663d95d.png" alt="profile link on facebook" class="image--center mx-auto" /></p>
<p>And inside the profile page do the same as we did on the home page.</p>
<p>Here we will get an alert that looks like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698046418300/975c1b17-c758-43a2-aa1a-f1204cc85886.png" alt="custom page leave alert on facebook" class="image--center mx-auto" /></p>
<p>Did you notice that Facebook uses different alert popups to handle the same feature for different pages?</p>
<p>It's not like they intentionally doing this. Actually, they are using two different ways to handle these scenarios and that is why the alert popup is different. In the first scenario, they are using the <code>beforeunload</code> event and that's why the alert is the browser's default popup.</p>
<p>On the other hand in the second scenario, they are using a different approach and used their custom popup to show the alert and we will discuss this in brief in upcoming sections.</p>
<p>Also now if you come back to the home page of Facebook from the profile page by clicking the link instead of the browser back button and try the same thing that we tried before on the home page. You will see the custom alert of Facebook instead of the default alert we had seen before. Feel free to experiment with this too.</p>
<p>And I believe that makes my point clear that <code>beforeunload</code> event doesn't work the same way in other routes of single page application as it works for the home page.</p>
<p>now you may be thinking if that's the case how we can make this feature for other routes?</p>
<p>To do that there are a few ways. We will see them.</p>
<h2 id="heading-using-the-popstate-event">using the <code>popstate</code> event</h2>
<p>The first approach we will use is using the <a target="_blank" href="https://www.w3schools.com/jsref/obj_popstateevent.asp"><code>popstate</code></a> event.</p>
<p>This procedure involves several modifications and additions to our project's code. Please remain patient and carefully follow the provided instructions. This will solve all problems and also will implement the Unsubmitted Data Preservation using the browser's <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage"><code>localStorage</code></a>.</p>
<p>Upon completion, you'll witness the enchantment.</p>
<ol>
<li><p>Set up the starter code again. Follow the instructions from <a class="post-section-overview" href="#heading-starter-code-to-start-implementation"><code>Starter code to start implementation</code></a> section</p>
</li>
<li><p>Create a directory named <code>hooks</code> for <a target="_blank" href="https://react.dev/learn/reusing-logic-with-custom-hooks">custom hooks</a> inside the <code>src</code> directory. Then inside this <code>hooks</code> directory create a file named <code>usePrompt.jsx</code></p>
<p> Paste this code below to the <code>usePrompt.jsx</code> file:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { useEffect, useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
 <span class="hljs-keyword">import</span> { PopstateContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"../context/PopstateContext"</span>;

 <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">usePrompt</span>(<span class="hljs-params">dirty, popStateHandler</span>) </span>{
   <span class="hljs-keyword">let</span> prevPopStateHandler = useContext(PopstateContext);
   useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">if</span> (dirty) {
       prevPopStateHandler.current &amp;&amp; <span class="hljs-built_in">window</span>.removeEventListener(<span class="hljs-string">"popstate"</span>, prevPopStateHandler.current);
       prevPopStateHandler.current = popStateHandler;
       <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">"popstate"</span>, popStateHandler, <span class="hljs-literal">false</span>);
     }
   }, [dirty]);
 }

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> usePrompt;
</code></pre>
<p> This <code>usePrompt</code> hook is designed to manage the event listeners related to the <code>popstate</code> event, which is triggered when the user navigates through the browser history. It does this based on the condition of whether there are unsaved changes (<code>dirty</code>).</p>
</li>
<li><p>Now Create a new file inside the <code>component</code> directory named <code>FormPrompt.jsx</code> and paste this code inside the file:</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// FormPrompt.jsx</span>
 <span class="hljs-keyword">import</span> { useCallback, useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
 <span class="hljs-keyword">import</span> { useNavigate, useBeforeUnload, useLocation } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;
 <span class="hljs-keyword">import</span> usePrompt <span class="hljs-keyword">from</span> <span class="hljs-string">"../hooks/usePrompt"</span>;
 <span class="hljs-keyword">import</span> { PopstateContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"../context/PopstateContext"</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">FormPrompt</span>(<span class="hljs-params">{ dirty, formData }</span>) </span>{
   <span class="hljs-keyword">let</span> prevPopStateHandler = useContext(PopstateContext);
   <span class="hljs-keyword">const</span> location = useLocation();
   <span class="hljs-keyword">const</span> navigate = useNavigate();
   <span class="hljs-keyword">const</span> currentRoute = <span class="hljs-built_in">window</span>.location.pathname;
   <span class="hljs-keyword">const</span> popStateHandler = useCallback(
     <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
       <span class="hljs-comment">// The popstate event is fired each time when the current history entry changes.</span>
       <span class="hljs-keyword">const</span> confirmValue = confirm(<span class="hljs-string">"You pressed a Back button! Are you sure?!"</span>);
       <span class="hljs-keyword">if</span> (confirmValue) {
         prevPopStateHandler.current &amp;&amp; <span class="hljs-built_in">window</span>.removeEventListener(<span class="hljs-string">"popstate"</span>, prevPopStateHandler.current);
         prevPopStateHandler.current = <span class="hljs-literal">null</span>;
         <span class="hljs-built_in">localStorage</span>.setItem(location.pathname, <span class="hljs-built_in">JSON</span>.stringify(formData));
         <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
       } <span class="hljs-keyword">else</span> {
         <span class="hljs-comment">// Stay on the current page.</span>
         navigate(currentRoute);
         <span class="hljs-keyword">if</span> (prevPopStateHandler.current) {
           <span class="hljs-built_in">window</span>.removeEventListener(<span class="hljs-string">"popstate"</span>, prevPopStateHandler.current);
           <span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">"popstate"</span>, prevPopStateHandler.current, <span class="hljs-literal">false</span>);
         }
         <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
       }
     },
     [prevPopStateHandler.current]
   );
   usePrompt(dirty, popStateHandler);
   useBeforeUnload(
     useCallback(
       <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
         <span class="hljs-keyword">if</span> (dirty) {
           event.preventDefault();
           event.returnValue = <span class="hljs-string">""</span>;
         }
       },
       [dirty]
     ),
     { <span class="hljs-attr">capture</span>: <span class="hljs-literal">true</span> }
   );
   <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
 }
</code></pre>
<p> This code defines a <a target="_blank" href="https://react.dev/learn/your-first-component">React component</a> (<code>FormPrompt</code>) that uses hooks from React Router and custom hooks (<code>useBeforeUnload</code>, <code>usePrompt</code>). The component manages browser history events, prompts the user before leaving the page with unsaved changes, and handles form data persistence.</p>
</li>
<li><p>Create another file within the <code>component</code> directory named <code>CustomLink.jsx</code>.</p>
<p> Paste the following code into it:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
 <span class="hljs-keyword">import</span> { Link, useLocation, useNavigate } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;
 <span class="hljs-keyword">import</span> { PopstateContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"../context/PopstateContext"</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">CustomLink</span>(<span class="hljs-params">{ children, ...props }</span>) </span>{
   <span class="hljs-keyword">const</span> { <span class="hljs-attr">onClick</span>: passedClickHandler, <span class="hljs-attr">to</span>: path, formData, ...slicedProps } = props;
   <span class="hljs-keyword">const</span> navigate = useNavigate();
   <span class="hljs-keyword">const</span> prevPopStateHandler = useContext(PopstateContext);
   <span class="hljs-keyword">const</span> location = useLocation();
   <span class="hljs-keyword">return</span> (
     <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Link</span>
       <span class="hljs-attr">onClick</span>=<span class="hljs-string">{(e)</span> =&gt;</span> {
         e.preventDefault();
         if (prevPopStateHandler.current) {
           let navigateTo;
           navigateTo = prevPopStateHandler.current();
           if (navigateTo) {
             navigate(path);
             prevPopStateHandler.current = null;
             localStorage.setItem(location.pathname, JSON.stringify(formData));
           }
         } else {
           navigate(path);
         }
         passedClickHandler?.(e);
       }}
       {...slicedProps}
     &gt;
       {children}
     <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span></span>
   );
 }
</code></pre>
<p> This code establishes a custom link (<code>CustomLink</code>) component similar to React Router DOM's <code>Link</code> component. This custom link is necessary because the React Router DOM's <code>Link</code> component doesn't provide a direct means to manage the <code>popstate</code> event. Since a custom <code>popstate</code> event is in use, this custom link is created to manually trigger the event when a user clicks on a navigation link.</p>
</li>
<li><p>To apply this <code>CustomLink</code> to our project we need to modify the Nav bar's code.</p>
<p> replace the code of <code>Nav.jsx</code> with this code below:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> CustomLink <span class="hljs-keyword">from</span> <span class="hljs-string">"./CustomLink"</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">Nav</span>(<span class="hljs-params">{formData}</span>) </span>{
   <span class="hljs-keyword">return</span> (
     <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">CustomLink</span> <span class="hljs-attr">formData</span>=<span class="hljs-string">{formData}</span> <span class="hljs-attr">to</span>=<span class="hljs-string">{</span>"/"}&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">CustomLink</span>&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">CustomLink</span> <span class="hljs-attr">formData</span>=<span class="hljs-string">{formData}</span> <span class="hljs-attr">to</span>=<span class="hljs-string">{</span>"/<span class="hljs-attr">profile</span>"}&gt;</span>Profile<span class="hljs-tag">&lt;/<span class="hljs-name">CustomLink</span>&gt;</span>
     <span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span></span>
   );
 }
</code></pre>
</li>
<li><p>Create another directory named <code>context</code> within the <code>src</code> directory, and within it, generate a file named <code>PopstateContext.jsx</code>. Copy and paste the ensuing code into <code>PopstateContext.jsx</code>:</p>
<p> paste this code inside the <code>PopstateContext.jsx</code> file:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { createContext, useRef } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> PopstateContext = createContext(<span class="hljs-literal">null</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">PopstateProvider</span> (<span class="hljs-params">{ children }</span>) </span>{
   <span class="hljs-keyword">const</span> prevPopStateHandler = useRef(<span class="hljs-literal">null</span>)
   <span class="hljs-keyword">return</span> (
     <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">PopstateContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{prevPopStateHandler}</span>&gt;</span>
       {children}
     <span class="hljs-tag">&lt;/<span class="hljs-name">PopstateContext.Provider</span>&gt;</span></span>
   )
 }
</code></pre>
<p> This code initiates a <a target="_blank" href="https://www.freecodecamp.org/news/context-api-in-react/">context</a> to store the <code>popstate</code> event reference, making it globally accessible throughout the application. This is vital for dynamically managing the addition and removal of the <code>popstate</code> event across the entire project as per specific requirements.</p>
</li>
<li><p>To add this context to the app replace the <code>main.jsx</code> file</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/client"</span>;
 <span class="hljs-keyword">import</span> Home <span class="hljs-keyword">from</span> <span class="hljs-string">"./pages/Home"</span>;
 <span class="hljs-keyword">import</span> Profile <span class="hljs-keyword">from</span> <span class="hljs-string">"./pages/Profile.jsx"</span>;
 <span class="hljs-keyword">import</span> FormContextProvider <span class="hljs-keyword">from</span> <span class="hljs-string">"./context/PopstateContext"</span>;

 <span class="hljs-keyword">import</span> { createBrowserRouter, RouterProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;
 <span class="hljs-keyword">const</span> router = createBrowserRouter([
   {
     <span class="hljs-attr">path</span>: <span class="hljs-string">"/"</span>,
     <span class="hljs-attr">element</span>: <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Home</span> /&gt;</span></span>,
   },
   {
     <span class="hljs-attr">path</span>: <span class="hljs-string">"/profile"</span>,
     <span class="hljs-attr">element</span>: <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Profile</span> /&gt;</span></span>,
   },
 ]);

 ReactDOM.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>)).render(
   <span class="hljs-comment">// &lt;React.StrictMode&gt;</span>
   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">FormContextProvider</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">RouterProvider</span> <span class="hljs-attr">router</span>=<span class="hljs-string">{router}</span> /&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">FormContextProvider</span>&gt;</span></span>
   <span class="hljs-comment">// &lt;/React.StrictMode&gt;</span>
 );
</code></pre>
</li>
<li><p>Create another custom hook inside the <code>hooks</code> directory named <code>useFormData.jsx</code></p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { useEffect, useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
 <span class="hljs-keyword">import</span> { useLocation } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;
 <span class="hljs-keyword">import</span> { PopstateContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"../context/PopstateContext"</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">useFormData</span>(<span class="hljs-params">formData, setDirty, dispatch</span>) </span>{
   <span class="hljs-keyword">const</span> prevPopStateHandler = useContext(PopstateContext);
   <span class="hljs-keyword">const</span> location = useLocation();
   <span class="hljs-comment">// restore the saved data from local storage</span>
   useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">const</span> prevData = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">localStorage</span>.getItem(location.pathname));
     <span class="hljs-keyword">if</span> (prevData) {
       dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">"restore"</span>, <span class="hljs-attr">data</span>: prevData });
       <span class="hljs-built_in">localStorage</span>.removeItem(location.pathname);
     }
   }, []);

   <span class="hljs-comment">// mark the form as dirty if there is form value otherwise mark as not dirty</span>
   useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">if</span> (formData.name === <span class="hljs-string">""</span> &amp;&amp; formData.email === <span class="hljs-string">""</span>) {
       setDirty(<span class="hljs-literal">false</span>);
       prevPopStateHandler.current &amp;&amp; <span class="hljs-built_in">window</span>.removeEventListener(<span class="hljs-string">"popstate"</span>, prevPopStateHandler.current);
       prevPopStateHandler.current = <span class="hljs-literal">null</span>;
     } <span class="hljs-keyword">else</span> setDirty(<span class="hljs-literal">true</span>);
   }, [formData]);
 }
</code></pre>
<p> This hook manages the form data within <code>localStorage</code> when the user visits the page, and it also handles the <code>popstate</code> event based on changes in <code>formData</code>.</p>
</li>
</ol>
<p>Now if we add this <code>FormPrompt</code> component and the <code>useFormData</code> hook inside the project's pages these will solve all the issues that we were facing.</p>
<p>Let's try it now on the profile page:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useReducer, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"../../style.css"</span>;
<span class="hljs-keyword">import</span> Nav <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/Nav"</span>;
<span class="hljs-keyword">import</span> Form <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/Form"</span>;
<span class="hljs-keyword">import</span> FormPrompt <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/FormPrompt"</span>;
<span class="hljs-keyword">import</span> formReducer <span class="hljs-keyword">from</span> <span class="hljs-string">"../reducer/formReducer"</span>;
<span class="hljs-keyword">import</span> useFormData <span class="hljs-keyword">from</span> <span class="hljs-string">"../hooks/useFormData"</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Profile</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [dirty, setDirty] = useState(<span class="hljs-literal">false</span>);
  <span class="hljs-keyword">const</span> [formData, dispatch] = useReducer(formReducer, {
    <span class="hljs-attr">name</span>: <span class="hljs-string">""</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">""</span>,
  });
  useFormData(formData, setDirty, dispatch);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">FormPrompt</span> <span class="hljs-attr">dirty</span>=<span class="hljs-string">{dirty}</span> <span class="hljs-attr">formData</span>=<span class="hljs-string">{formData}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Nav</span> <span class="hljs-attr">formData</span>=<span class="hljs-string">{formData}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome to Profile Page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Form</span> <span class="hljs-attr">formData</span>=<span class="hljs-string">{formData}</span> <span class="hljs-attr">dispatch</span>=<span class="hljs-string">{dispatch}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Profile;
</code></pre>
<p>Now run the app and check the feature. This code will do the same for the rest things but we won't see the issues that we were encountering before and preserve the data on <code>localStorage</code>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698037470569/d87df622-fcb8-447e-a9f3-f35cd632192b.png" alt="unsaved changes alert " class="image--center mx-auto" /></p>
<p>Now let's apply the same for the Home page. replace the <code>Home.jsx</code> file code with this code below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { useReducer, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">"../../style.css"</span>;
<span class="hljs-keyword">import</span> Nav <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/Nav"</span>;
<span class="hljs-keyword">import</span> Form <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/Form"</span>;
<span class="hljs-keyword">import</span> FormPrompt <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/FormPrompt"</span>;
<span class="hljs-keyword">import</span> formReducer <span class="hljs-keyword">from</span> <span class="hljs-string">"../reducer/formReducer"</span>;
<span class="hljs-keyword">import</span> useFormData <span class="hljs-keyword">from</span> <span class="hljs-string">"../hooks/useFormData"</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Home</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [dirty, setDirty] = useState(<span class="hljs-literal">false</span>);
  <span class="hljs-keyword">const</span> [formData, dispatch] = useReducer(formReducer, {
    <span class="hljs-attr">name</span>: <span class="hljs-string">""</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">""</span>,
  });
  useFormData(formData, setDirty, dispatch);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">FormPrompt</span> <span class="hljs-attr">dirty</span>=<span class="hljs-string">{dirty}</span> <span class="hljs-attr">formData</span>=<span class="hljs-string">{formData}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Nav</span> <span class="hljs-attr">formData</span>=<span class="hljs-string">{formData}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome to Home Page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Form</span> <span class="hljs-attr">formData</span>=<span class="hljs-string">{formData}</span> <span class="hljs-attr">dispatch</span>=<span class="hljs-string">{dispatch}</span> /&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Home;
</code></pre>
<p>Now run the application again, now both the home and profile pages should solve the issues and also preserve the data on <code>localStorage</code></p>
<h2 id="heading-using-the-history-npm-package">using the history npm package</h2>
<p>In the previous section, we have seen how can we make the feature workable for all situations using <code>popstate</code> event But there is another way that we can use without using <code>popstate</code> event.</p>
<p>Here we will use a npm package name <a target="_blank" href="https://www.npmjs.com/package/history"><code>history</code></a> this is a very popular and widely used package and even React router dom also use this package behind the scene. So, you can imagine how popular and authentic this package is.</p>
<p>And the interesting thing is we don't need to start from the beginning to do that. whatever code we have written so far few of them are still relevant also the folder structure will be totally the same. We just need to make some changes to a few files.</p>
<ol>
<li><p>First of all, let's install the package in our code:</p>
<pre><code class="lang-bash"> npm install <span class="hljs-built_in">history</span>
</code></pre>
</li>
<li><p>Now replace the <code>usePromp.jsx</code> file code with this code:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { useEffect, useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
 <span class="hljs-keyword">import</span> { NavigationRef } <span class="hljs-keyword">from</span> <span class="hljs-string">"../context/NavigationRefContext"</span>;
 <span class="hljs-keyword">import</span> { createBrowserHistory } <span class="hljs-keyword">from</span> <span class="hljs-string">"history"</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">usePrompt</span>(<span class="hljs-params">dirty,formData, locationChangeHandler</span>) </span>{
   <span class="hljs-keyword">let</span> { unblockNavigationRef, blockHandlerRef } = useContext(NavigationRef);
   <span class="hljs-keyword">const</span> history = createBrowserHistory();
   useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">if</span> (dirty) {
       <span class="hljs-keyword">if</span> (unblockNavigationRef.current) unblockNavigationRef.current();
       unblockNavigationRef.current = history.listen(locationChangeHandler);
       blockHandlerRef.current = locationChangeHandler;
     }
   }, [dirty, formData]);
 }
</code></pre>
</li>
<li><p>Then replace the <code>useFormData.jsx</code> file code:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
 <span class="hljs-keyword">import</span> { useLocation } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</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">useFormData</span>(<span class="hljs-params">formData, setDirty, dispatch</span>) </span>{
   <span class="hljs-keyword">const</span> location = useLocation();
   <span class="hljs-comment">// restore the saved data from local storage</span>
   useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">const</span> prevData = <span class="hljs-built_in">localStorage</span>.getItem(location.pathname);
     <span class="hljs-keyword">if</span> (prevData &amp;&amp; prevData !== <span class="hljs-string">"undefined"</span>) {
       <span class="hljs-keyword">const</span> parsedData = <span class="hljs-built_in">JSON</span>.parse(prevData);
       dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">"restore"</span>, <span class="hljs-attr">data</span>: parsedData });
       <span class="hljs-built_in">localStorage</span>.removeItem(location.pathname);
     }
   }, []);

   <span class="hljs-comment">// mark the form as dirty if there is form value otherwise mark as not dirty</span>
   useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">if</span> (formData.name !== <span class="hljs-string">""</span> || formData.email !== <span class="hljs-string">""</span>) {
       setDirty(<span class="hljs-literal">true</span>);
     }
   }, [formData]);
 }
</code></pre>
</li>
<li><p>Then replace the <code>FormPrompt.jsx</code> file code with this code:</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// FormPrompt.jsx</span>
 <span class="hljs-keyword">import</span> { useCallback, useContext, useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
 <span class="hljs-keyword">import</span> { useNavigate, useBeforeUnload, useLocation } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;
 <span class="hljs-keyword">import</span> usePrompt <span class="hljs-keyword">from</span> <span class="hljs-string">"../hooks/usePrompt"</span>;
 <span class="hljs-keyword">import</span> { NavigationRef } <span class="hljs-keyword">from</span> <span class="hljs-string">"../context/NavigationRefContext"</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">FormPrompt</span>(<span class="hljs-params">{ dirty, formData }</span>) </span>{
   <span class="hljs-keyword">let</span> { unblockNavigationRef, blockHandlerRef } = useContext(NavigationRef);
   <span class="hljs-keyword">const</span> location = useLocation();
   <span class="hljs-keyword">const</span> navigate = useNavigate();
   <span class="hljs-keyword">const</span> currentRoute = location.pathname;
   <span class="hljs-keyword">const</span> locationChangeHandler = useCallback(
     <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">transition</span>) </span>{
       <span class="hljs-keyword">if</span> (transition.action === <span class="hljs-string">"POP"</span>) {
         <span class="hljs-keyword">const</span> confirmValue = confirm(<span class="hljs-string">"are you sure?"</span>);
         <span class="hljs-keyword">if</span> (confirmValue) {
           unblockNavigationRef.current?.();
           unblockNavigationRef.current = <span class="hljs-literal">null</span>;
           blockHandlerRef.current = <span class="hljs-literal">null</span>;
           <span class="hljs-built_in">localStorage</span>.setItem(currentRoute, <span class="hljs-built_in">JSON</span>.stringify(formData));
           <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
         } <span class="hljs-keyword">else</span> {
           <span class="hljs-built_in">localStorage</span>.setItem(currentRoute, <span class="hljs-built_in">JSON</span>.stringify(formData));
           navigate(currentRoute);
           <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
         }
       }
     },
     [formData, unblockNavigationRef.current, blockHandlerRef.current]
   );

   usePrompt(dirty, formData, locationChangeHandler);
   useBeforeUnload(
     useCallback(
       <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
         <span class="hljs-keyword">if</span> (dirty) {
           event.preventDefault();
           event.returnValue = <span class="hljs-string">""</span>;
         }
       },
       [dirty]
     ),
     { <span class="hljs-attr">capture</span>: <span class="hljs-literal">true</span> }
   );
   <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
 }
</code></pre>
</li>
<li><p>Replace the <code>CustomLink.jsx</code> file code:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { useContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
 <span class="hljs-keyword">import</span> { Link, useLocation, useNavigate } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;
 <span class="hljs-keyword">import</span> { NavigationRef } <span class="hljs-keyword">from</span> <span class="hljs-string">"../context/NavigationRefContext"</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">CustomLink</span>(<span class="hljs-params">{ children, ...props }</span>) </span>{
   <span class="hljs-keyword">const</span> { <span class="hljs-attr">onClick</span>: passedClickHandler, <span class="hljs-attr">to</span>: path, formData, ...slicedProps } = props;
   <span class="hljs-keyword">const</span> navigate = useNavigate();
   <span class="hljs-keyword">const</span> { unblockNavigationRef, blockHandlerRef } = useContext(NavigationRef);
   <span class="hljs-keyword">const</span> location = useLocation();
   <span class="hljs-keyword">return</span> (
     <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Link</span>
       <span class="hljs-attr">onClick</span>=<span class="hljs-string">{(e)</span> =&gt;</span> {
         e.preventDefault();
         if (unblockNavigationRef.current &amp;&amp; blockHandlerRef.current) {
           const confirmed = confirm("are you sure?");
           if (confirmed) {
             navigate(path);
             unblockNavigationRef.current();
             unblockNavigationRef.current = null;
             blockHandlerRef.current = null;
             localStorage.setItem(location.pathname, JSON.stringify(formData));
           }
         } else {
           navigate(path);
         }
         passedClickHandler?.(e);
       }}
       {...slicedProps}
     &gt;
       {children}
     <span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span></span>
   );
 }
</code></pre>
</li>
<li><p>Inside the <code>context</code> folder rename the <code>PopstateContext.jsx</code> file to <code>NavigationRefContext.jsx</code> and replace the code inside it:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { createContext, useRef } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> NavigationRef = createContext(<span class="hljs-literal">null</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">NavigationRefProvider</span> (<span class="hljs-params">{ children }</span>) </span>{
   <span class="hljs-keyword">const</span> unblockNavigationRef = useRef(<span class="hljs-literal">null</span>)
   <span class="hljs-keyword">const</span> blockHandlerRef = useRef(<span class="hljs-literal">null</span>)
   <span class="hljs-keyword">return</span> (
     <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">NavigationRef.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{{unblockNavigationRef,blockHandlerRef}}</span>&gt;</span>
       {children}
     <span class="hljs-tag">&lt;/<span class="hljs-name">NavigationRef.Provider</span>&gt;</span></span>
   )
 }
</code></pre>
</li>
<li><p>Inside the <code>main.jsx</code> file, update the context file path</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">// remove this line</span>
 <span class="hljs-keyword">import</span> FormContextProvider <span class="hljs-keyword">from</span> <span class="hljs-string">"./context/PopstateContext"</span>;

 <span class="hljs-comment">// add this line</span>
 <span class="hljs-keyword">import</span> FormContextProvider <span class="hljs-keyword">from</span> <span class="hljs-string">"./context/NavigationRefContext.jsx"</span>;
</code></pre>
</li>
</ol>
<p>We don't need to do anything new for the pages the setup we did before is still applicable.</p>
<p>Now run the application and you will see that your application is working as it was before.</p>
<blockquote>
<p>Note: These two ways work well but these are not good enough to rely on also there are situations where they may won't work properly so I don't recommend using these on your project.</p>
<p>But you can explore these ways just for fun and enrich your knowledge.</p>
</blockquote>
<h2 id="heading-using-unstableuseblocker-from-react-router-dom">Using <code>unstable_useBlocker</code> from React Router Dom</h2>
<p>Now the way I am going to discuss is the ultimate solution that I have found to make this feature in a much easier way.</p>
<blockquote>
<p>Note: The solution I am talking about is not authorized by the authority or not recommended by the industry standard but it can make the work done properly.</p>
<p>Also, this <code>unstable_useBlocker</code> is not documented in the documentation but it exists on the react router dom <a target="_blank" href="https://github.com/remix-run/react-router/blob/react-router-dom%406.15.0/packages/react-router-dom/index.tsx#L1460">source code</a>.</p>
</blockquote>
<p>To apply this way we need to start from the beginning which means from the starter code I have provided. Because this way is much easier to implement in comparison to the other two ways we have discussed before. Much code is irrelevant now.</p>
<p>so it's better to start from the beginning. Also, this will help to follow the section even if are just reading this section instead of reading the whole article.</p>
<ol>
<li><p>Set up the starter code again. Follow the instructions from <a class="post-section-overview" href="#heading-starter-code-to-start-implementation"><code>Starter code to start implementation</code></a> section</p>
</li>
<li><p>Create a directory named <code>hooks</code> for custom hooks inside the <code>src</code> directory. Then inside this <code>hooks</code> directory create a file named <code>usePrompt.jsx</code></p>
<p> Paste this code below to the <code>usePrompt.jsx</code> file:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { useEffect, useRef } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
 <span class="hljs-keyword">import</span> { unstable_useBlocker <span class="hljs-keyword">as</span> useBlocker } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;

 <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">usePrompt</span>(<span class="hljs-params">onLocationChange, hasUnsavedChanges</span>) </span>{
   <span class="hljs-keyword">const</span> blocker = useBlocker(hasUnsavedChanges ? onLocationChange : <span class="hljs-literal">false</span>);
   <span class="hljs-keyword">const</span> prevState = useRef(blocker.state);

   useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">if</span> (blocker.state === <span class="hljs-string">"blocked"</span>) {
       blocker.reset();
     }
     prevState.current = blocker.state;
   }, [blocker]);
 }
 <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> usePrompt;
</code></pre>
<p> This <code>usePrompt</code> hook is designed to manage the blocking behavior during navigation changes based on whether there are unsaved changes in the application. This hook plays a similar role as the <code>usePrompt</code> hooks we used in the previous two ways but it uses the <code>unstable_useBlocker</code> instead of <code>popstate</code> event or <code>history</code> npm package.</p>
</li>
<li><p>Now Create a new file inside the <code>component</code> directory named <code>FormPrompt.jsx</code> and paste this code inside the file:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { useCallback } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
 <span class="hljs-keyword">import</span> { useBeforeUnload, useLocation } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</span>;
 <span class="hljs-keyword">import</span> usePrompt <span class="hljs-keyword">from</span> <span class="hljs-string">"../hooks/usePrompt"</span>;

 <span class="hljs-keyword">const</span> stepLinks = [<span class="hljs-string">"/"</span>, <span class="hljs-string">"/profile"</span>];
 <span class="hljs-keyword">const</span> FormPrompt = <span class="hljs-function">(<span class="hljs-params">{ dirty, formData }</span>) =&gt;</span> {
   <span class="hljs-keyword">const</span> location = useLocation();
   <span class="hljs-keyword">const</span> onLocationChange = useCallback(
     <span class="hljs-function">(<span class="hljs-params">{ nextLocation }</span>) =&gt;</span> {
       <span class="hljs-keyword">let</span> confirmValue = <span class="hljs-literal">false</span>;
       <span class="hljs-keyword">if</span> (stepLinks.includes(nextLocation.pathname) &amp;&amp; dirty) {
         confirmValue = !<span class="hljs-built_in">window</span>.confirm(<span class="hljs-string">"You have unsaved changes, are you sure you want to leave?"</span>);
       }
       <span class="hljs-keyword">if</span> (!confirmValue) <span class="hljs-built_in">localStorage</span>.setItem(location.pathname, <span class="hljs-built_in">JSON</span>.stringify(formData));
       <span class="hljs-keyword">return</span> confirmValue;
     },
     [dirty, formData]
   );

   usePrompt(onLocationChange, dirty);
   useBeforeUnload(
     useCallback(
       <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
         <span class="hljs-keyword">if</span> (dirty) {
           event.preventDefault();
           event.returnValue = <span class="hljs-string">""</span>;
         }
       },
       [dirty]
     ),
     { <span class="hljs-attr">capture</span>: <span class="hljs-literal">true</span> }
   );

   <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
 };

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> FormPrompt;
</code></pre>
<p> This <code>FormPrompt</code> component manages navigation prompts and handles unsaved changes during navigation events, offering a confirmation dialog to users.</p>
</li>
<li><p>Create another custom hook inside the hooks directory named <code>useFormData.jsx</code> and paste this code:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
 <span class="hljs-keyword">import</span> { useLocation } <span class="hljs-keyword">from</span> <span class="hljs-string">"react-router-dom"</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">useFormData</span>(<span class="hljs-params">formData, setDirty, dispatch</span>) </span>{
   <span class="hljs-keyword">const</span> location = useLocation();
   <span class="hljs-comment">// restore the saved data from local storage</span>
   useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">const</span> prevData = <span class="hljs-built_in">JSON</span>.parse(<span class="hljs-built_in">localStorage</span>.getItem(location.pathname));
     <span class="hljs-keyword">if</span> (prevData) {
       dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">"restore"</span>, <span class="hljs-attr">data</span>: prevData });
       <span class="hljs-built_in">localStorage</span>.removeItem(location.pathname);
     }
   }, []);

   <span class="hljs-comment">// mark the form as dirty if there is form value otherwise mark as not dirty</span>
   useEffect(<span class="hljs-function">() =&gt;</span> {
     <span class="hljs-keyword">if</span> (formData.name === <span class="hljs-string">""</span> &amp;&amp; formData.email === <span class="hljs-string">""</span>) {
       setDirty(<span class="hljs-literal">false</span>);
     } <span class="hljs-keyword">else</span> setDirty(<span class="hljs-literal">true</span>);
   }, [formData]);
 }
</code></pre>
<p> This <code>useFormData</code> hook manages the form data, restores it from localStorage when the user visits the page, and tracks changes to mark the form as dirty or not dirty accordingly.</p>
</li>
</ol>
<p>Now we are done with the feature implementation let's apply it to the project's pages.</p>
<ol>
<li><p>Replace the <code>Home.jsx</code> file's code:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { useReducer, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
 <span class="hljs-keyword">import</span> <span class="hljs-string">"../../style.css"</span>;
 <span class="hljs-keyword">import</span> Nav <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/Nav"</span>;
 <span class="hljs-keyword">import</span> Form <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/Form"</span>;
 <span class="hljs-keyword">import</span> FormPrompt <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/FormPrompt"</span>;
 <span class="hljs-keyword">import</span> useFormData <span class="hljs-keyword">from</span> <span class="hljs-string">"../hooks/useFormData"</span>;
 <span class="hljs-keyword">import</span> formReducer <span class="hljs-keyword">from</span> <span class="hljs-string">"../reducer/formReducer"</span>;
 <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Home</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">const</span> [dirty, setDirty] = useState(<span class="hljs-literal">false</span>);
   <span class="hljs-keyword">const</span> [formData, dispatch] = useReducer(formReducer, {
     <span class="hljs-attr">name</span>: <span class="hljs-string">""</span>,
     <span class="hljs-attr">email</span>: <span class="hljs-string">""</span>,
   });
   useFormData(formData, setDirty, dispatch);
   <span class="hljs-keyword">return</span> (
     <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">FormPrompt</span> <span class="hljs-attr">formData</span>=<span class="hljs-string">{formData}</span> <span class="hljs-attr">dirty</span>=<span class="hljs-string">{dirty}</span> /&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">Nav</span> /&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome to Home Page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">Form</span> <span class="hljs-attr">formData</span>=<span class="hljs-string">{formData}</span> <span class="hljs-attr">dispatch</span>=<span class="hljs-string">{dispatch}</span> /&gt;</span>
       <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
     <span class="hljs-tag">&lt;/&gt;</span></span>
   );
 }

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Home;
</code></pre>
</li>
<li><p>Replace the <code>Profile.jsx</code> file's code:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> { useReducer, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
 <span class="hljs-keyword">import</span> <span class="hljs-string">"../../style.css"</span>;
 <span class="hljs-keyword">import</span> Nav <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/Nav"</span>;
 <span class="hljs-keyword">import</span> Form <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/Form"</span>;
 <span class="hljs-keyword">import</span> FormPrompt <span class="hljs-keyword">from</span> <span class="hljs-string">"../component/FormPrompt"</span>;
 <span class="hljs-keyword">import</span> useFormData <span class="hljs-keyword">from</span> <span class="hljs-string">"../hooks/useFormData"</span>;
 <span class="hljs-keyword">import</span> formReducer <span class="hljs-keyword">from</span> <span class="hljs-string">"../reducer/formReducer"</span>;

 <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Profile</span>(<span class="hljs-params"></span>) </span>{
   <span class="hljs-keyword">const</span> [dirty, setDirty] = useState(<span class="hljs-literal">false</span>);
   <span class="hljs-keyword">const</span> [formData, dispatch] = useReducer(formReducer, {
     <span class="hljs-attr">name</span>: <span class="hljs-string">""</span>,
     <span class="hljs-attr">email</span>: <span class="hljs-string">""</span>,
   });
   useFormData(formData, setDirty, dispatch);
   <span class="hljs-keyword">return</span> (
     <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">FormPrompt</span> <span class="hljs-attr">formData</span>=<span class="hljs-string">{formData}</span> <span class="hljs-attr">dirty</span>=<span class="hljs-string">{dirty}</span> /&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">Nav</span> /&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">main</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome to Profile Page<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">Form</span> <span class="hljs-attr">formData</span>=<span class="hljs-string">{formData}</span> <span class="hljs-attr">dispatch</span>=<span class="hljs-string">{dispatch}</span> /&gt;</span>
       <span class="hljs-tag">&lt;/<span class="hljs-name">main</span>&gt;</span>
     <span class="hljs-tag">&lt;/&gt;</span></span>
   );
 }

 <span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Profile;
</code></pre>
</li>
</ol>
<p>Now run the application again and see the magic.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Alerts for Unsaved Changes and Unsubmitted Data Preservation are not commonly implemented features. You might not encounter many situations where you'll need to incorporate these into your application. but these are cool features to know as a developer.</p>
<p>I started playing around with these as an experiment, and it turned into a fun learning experience.</p>
<p>The motive behind sharing this article is to pass on the enthusiasm and knowledge I gathered while working on these unique features. I hope you had a similar experience. Feel free to express your thoughts in the comments, and if you have any questions, don't hesitate to ask.</p>
<p>All the code of this article you will find in this <a target="_blank" href="https://github.com/robiulhr/prevent-unsaved-changes-page-leave">GitHub repo</a></p>
<p>Happy coding :)</p>
<h2 id="heading-resources">Resources</h2>
<ul>
<li><p><a target="_blank" href="https://gist.github.com/chaance/2f3c14ec2351a175024f62fd6ba64aa6">Example implementation of <code>usePrompt</code> and React Router v5's <code>&lt;Prompt&gt;</code> with <code>unstable_useBlocker</code></a></p>
</li>
<li><p><a target="_blank" href="https://claritydev.net/blog/display-warning-for-unsaved-form-data-on-page-exit"><strong>Display Warning for Unsaved Form Data on Page Exit</strong></a></p>
</li>
<li><p><a target="_blank" href="https://subwaymatch.medium.com/disabling-back-button-in-react-with-react-router-v5-34bb316c99d7">Disabling back button in React with react-router v5</a></p>
</li>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/70573526/prevent-navigation-with-react-router-v6">Prevent navigation with React router v6</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Transform common web development project ideas into unique ones]]></title><description><![CDATA[Introduction
Hello developers, hope you're all doing great. I've noticed a common challenge among many aspiring developers – the quest for unique project ideas to apply their programming skills. Beginners often find themselves at a crossroads, having...]]></description><link>https://robiul.dev/transform-common-web-development-project-ideas-into-unique-ones</link><guid isPermaLink="true">https://robiul.dev/transform-common-web-development-project-ideas-into-unique-ones</guid><category><![CDATA[React]]></category><category><![CDATA[projects]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[backend]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Tue, 21 Nov 2023 02:00:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1700491029535/14fa5a0f-013a-4370-9d68-27bfb74f52c5.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello developers, hope you're all doing great. I've noticed a common challenge among many aspiring developers – the quest for unique project ideas to apply their programming skills. Beginners often find themselves at a crossroads, having learned the fundamental concepts and tools but struggling to find truly distinctive project ideas.</p>
<p>The internet is flooded with project ideas, but most of them are similar, done, and redone by countless developers. You search online, and every "best React.js project ideas" list gives you déjà vu.</p>
<p>It's like, "Come on, give me something different!"</p>
<p>Now, imagine this scenario: Hundreds of developers undertake the same project. How do you stand out? How do you showcase your unique abilities? How do you show that you've got that special sauce, that secret ingredient?</p>
<p>Well, it's not about reinventing the wheel every time. Sometimes, it's the little tweaks that turn something ordinary into something extraordinary. Not every project needs to be groundbreaking; sometimes, the magic is in the refinement and personal touch you bring to the table.</p>
<p>The trick is in taking a project and making it uniquely yours. You don't have to reinvent the wheel with every project. Sometimes, the real magic happens when you put your own spin on something familiar. it's about taking a common project and putting your own spin on it, making it uniquely yours.</p>
<p>Recruiters understand this reality. They don't expect every candidate to present an entirely unique project. What they look for is the ability to innovate, to turn something common into something special. Demonstrating your knack for improvement and creativity on a familiar project is equally valuable.</p>
<p>So, let's explore how you can transform a simple and ubiquitous project into something truly unique. And to keep it real, we're going to do this with a classic: the Tic Tac Toe game.</p>
<blockquote>
<p>Note: Before we dive in, I want to make something crystal clear. I'm not here to walk you through the code. What I am going to do is share some feature ideas that can turn a simple Tic Tac Toe into something totally unique. The goal is for you to take these ideas and apply them to other projects as well.<br />While my primary focus in this article is on frontend development, it's important to note that these techniques can be adapted for backend projects as well.</p>
</blockquote>
<h2 id="heading-basic-features">Basic features</h2>
<p>To make the article more interesting and inspiring I have already made a version of tic tac toe using react and react router dom.</p>
<p>let me spill the beans on the secret sauce that turned my Tic Tac Toe from ordinary to extraordinary.</p>
<ol>
<li><p><strong>A Game of Choices: More Tiles, More Fun!</strong></p>
<ul>
<li><p><strong>Feature Description:</strong> I added a feature that lets players pick how big they want their Tic Tac Toe playground to be. You know, Tic Tac Toe is usually on a 3x3 grid. Well, not anymore!<br />  Now, you can choose to play on a classic 3x3 board, spice things up with a 4x4 challenge, or go all-in for a brain-bending 5x5 experience. It's like choosing your adventure but in Tic Tac Toe land.<br />  More tiles, more fun – you're in control!</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700475554458/59f3efdb-6746-4b09-a236-01239fe01fde.png" alt class="image--center mx-auto" /></p>
</li>
<li><p><strong>What You'll Learn:</strong> By adding this feature, you'll learn how to organize your React app with reusable parts, making it easier to manage. You'll also get the hang of showing different things based on user choices, like changing the board size. It's like learning to adjust parts of your app depending on what the user picks or the app's current situation.</p>
</li>
</ul>
</li>
<li><p><strong>The 10-Second Countdown! Feature Description:</strong></p>
<ul>
<li><p><strong>Quick Decision Time:</strong> You're playing your move, but here's the catch – you only have 10 seconds! It's like a little race against the clock in your Tic Tac Toe adventure. Feel the excitement, make your move before the countdown hits zero, and all's good.<br />  But here's the twist – if you take too long, your move gets tossed into a random spot. It's like a speedy game of Tic Tac Toe with a time limit – can you beat the clock? 🕐💨</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700475589805/c0d49d2d-1a06-48df-b6b2-7837ba78b788.png" alt class="image--center mx-auto" /></p>
</li>
<li><p><strong>What You'll Learn:</strong> Adding this feature will teach you how to manage asynchronous operations. You'll be working with the <a target="_blank" href="https://robiul.dev/javascript-settimeout-method-all-you-need-to-know"><code>setTimeout</code></a> method, and it's crucial to handle it carefully to avoid memory leaks. This hands-on experience will enhance your grasp of <code>asynchronous code</code>, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Event_loop"><code>event loops</code></a>, <code>stacks</code>, and more.</p>
</li>
</ul>
</li>
<li><p><strong>Rewind and Replay! History Feature:</strong></p>
<ul>
<li><p><strong>Feature Description</strong>: With the History Feature, you can look back at every move you've made, go back to any point you want, and redo your moves. It's like having a magical time machine in your Tic Tac Toe game. But, a heads up – if you decide to change things up, anything after that point is wiped out. So, choose your moves wisely and have fun exploring your game journey!</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700475620993/dca3c281-025f-44a9-bbe4-7d087ebaa931.png" alt class="image--center mx-auto" /></p>
</li>
<li><p><strong>What You'll Learn:</strong> Implementing this feature provides hands-on experience with manipulating <a target="_blank" href="https://www.w3schools.com/js/js_arrays.asp">arrays</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">objects</a> more effectively. You'll dive into using advanced array and object methods, gaining valuable insights for real-world applications.</p>
</li>
</ul>
</li>
<li><p><strong>Prevent Page Leave: No Escape Until Victory!</strong></p>
<ul>
<li><p><strong>Feature Description:</strong> Here's the deal with Prevent Page Leave: Imagine you're in the middle of an epic game, and suddenly you think about leaving the page. Well, not so fast! This feature throws up a popup that says, "Hold up! Are you sure you want to leave this awesome game?" You've got two choices: finish the game like a champ or leave the page by selecting exit.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700475683796/d47241f8-41eb-4276-b2a9-4d964b310af4.png" alt class="image--center mx-auto" /></p>
</li>
<li><p><strong>What You'll Learn:</strong> This feature, though seemingly straightforward, is a unique and intriguing aspect of web development. While it may appear easy to implement, tackling it within a single-page application adds a layer of complexity. The process of implementing this feature provides an in-depth understanding of the nuances involved in single-page application development.</p>
</li>
</ul>
</li>
</ol>
<p>There are many small things on the project but I have highlighted only the most important and unique ones.</p>
<p>here are the project live links</p>
<ol>
<li><p>https://tic-tac-toe-virid-eight.vercel.app/</p>
</li>
<li><p>https://robiulhr.github.io/Tic-Tac-Toe/</p>
</li>
</ol>
<h2 id="heading-advanced-features">Advanced features</h2>
<p>There are so many features that can be implemented in this project let's have a look at them:</p>
<ol>
<li><p><strong>Sound Effects: Adding a Sonic Touch!</strong></p>
<ul>
<li><p><strong>Feature Description:</strong> Let's talk about adding some fun noises to your Tic Tac Toe game – we call these "Sound Effects". Imagine every time you put an X or an O on the board, there's a little sound. Win the game? Cue a victory cheer! It's all about making your game not just something you see but something you hear too.</p>
</li>
<li><p><strong>What You'll Learn:</strong> By adding this feature, you'll gain hands-on experience with the browser's <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API">audio API</a>, enhancing your skills in working with various <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction">built-in browser APIs</a>.</p>
</li>
</ul>
</li>
<li><p><strong>Interactive Animations: Bringing the Board to Life!</strong></p>
<ul>
<li><p><strong>Feature Description:</strong> Now, instead of just placing Xs and Os on the board like usual, think about making your Tic Tac Toe board a bit more lively. You can do it with something called "Interactive Animations."<br />  Here's a simple idea: When someone makes a move, instead of just putting their X or O on the board, you can make it do a little spin or a jump. It's all about adding a touch of fun to each move.<br />  There are easy-to-use tools and libraries out there that can help your game pieces come to life with just a few lines of code. It's like giving your game a playful vibe! 🕺💃✨</p>
</li>
<li><p><strong>What You'll Learn:</strong> By implementing interactive animations in your project, you'll gain hands-on experience with various tools and animation libraries. This endeavor will not only enhance your creativity but also encourage innovative thinking, forcing you to create visually appealing elements.</p>
</li>
</ul>
</li>
<li><p><strong>Different Types of Play: Mix It Up!</strong></p>
<ul>
<li><p><strong>Feature Description:</strong> Right now, your app is set up for two players on one device. But think about this – what if players could play in different ways:</p>
<ol>
<li><p><strong>Play Against the Computer Alone:</strong> Ever thought about challenging the computer all by yourself? It's like having your private game.</p>
</li>
<li><p><strong>Battle Friends Online:</strong> Now, imagine playing with friends online, no matter where they are. It's like having a game night without being in the same room.</p>
<p> So, your game isn't just for two players anymore. You can play solo against the computer or have a virtual match with friends. Cool, right?</p>
</li>
</ol>
</li>
<li><p><strong>What You'll Learn:</strong> This feature provides an opportunity to delve into real-time data and the application of tools like <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">web socket</a>, especially when implementing the functionality for playing with friends online. Additionally, you'll explore the intricacies of Tic Tac Toe algorithms as you implement AI for playing against the computer.<br />  Leveraging available npm packages will equip you with the necessary resources for feature implementation, enhancing your understanding of algorithms and how to integrate them seamlessly into your own projects.</p>
</li>
</ul>
</li>
<li><p><strong>User Authentication: Personalizing the Experience!</strong></p>
<ul>
<li><p><strong>Feature Description:</strong> Let's make your Tic Tac Toe game a bit more personal.</p>
<p>  Here's what User Authentication mean:</p>
<ul>
<li><p><strong>User Registration:</strong> Think of it like creating your own spot in the game. Pick a username and password to have your unique space.</p>
</li>
<li><p><strong>Login:</strong> Once you're registered, use your chosen details to enter the game. It's like unlocking the door to your special gaming area.</p>
</li>
</ul>
</li>
<li><p><strong>What You'll Learn:</strong> Incorporating authentication into the project provides you with the opportunity to engage in full-stack development. You'll dive into backend and database operations to implement the necessary APIs. Integrating these components with the front end offers valuable experience in creating a full-stack project.<br />  And here's the bonus: This feature opens up lots of possibilities. We can now keep track of users for a long time in our system, recognizing them each time they play. This gives us the power to add cool features like a point table and much more! This journey serves as a stepping stone for beginner programmers aspiring to become proficient full-stack developers.</p>
</li>
</ul>
</li>
<li><p><strong>Scoreboard Galore: Track and Brag!</strong></p>
<ul>
<li><p><strong>Feature Description:</strong> Let's step up our app game by introducing the Scorecard feature! let's add a Scoreboard! This Scoreboard will have:</p>
<ul>
<li><p>The number of wins users have notched up.</p>
</li>
<li><p>The count of losses the user bravely faced.</p>
</li>
<li><p>A record of all the matches the user played.</p>
</li>
<li><p>Track of who your opponent was in each match!</p>
</li>
</ul>
</li>
<li><p><strong>What You'll Learn:</strong> By incorporating this feature, you'll have the chance to apply your problem-solving skills to a real-life project. It goes beyond mere syntax memorization; it's a demonstration of your problem-solving abilities. Working with data structures like arrays, objects, and their associated methods, this feature explores the logical aspects, demanding thoughtful solutions. It serves as proof of your adeptness in overcoming challenges and implementing effective solutions.</p>
</li>
</ul>
</li>
<li><p><strong>Chat System: Connect Beyond the Board!</strong></p>
<ul>
<li><p><strong>Feature Description:</strong> Let's infuse a social touch into our app! Enhance its engagement and features by incorporating a chat system. This allows users to participate in live chats while fully immersed in the game.</p>
</li>
<li><p><strong>What You'll Learn:</strong> Implementing this feature isn't just about coding; it's a journey that enhances your development skills. You'll dive into real-time communication protocols, understand user experience nuances, and master the art of creating engaging in-app communities.<br />  The recruiter, upon seeing this, will be impressed not only by your technical prowess but also by your ability to create immersive and socially connected applications, showcasing a well-rounded skill set.</p>
</li>
</ul>
</li>
</ol>
<p>These features we've explored are merely the tip of the iceberg. The possibilities are boundless, transforming your Tic Tac Toe from a mere game into a complete experience. I didn't have the time to add these features myself, but you can explore them in your version. And hey, if you want to contribute to mine, you're more than welcome!</p>
<p>Check out the <a target="_blank" href="https://github.com/robiulhr/tic-tac-toe">source code</a> 🚀🎮✨</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>After exploring the insights in this article, I trust you've gained a clear understanding of how to transform an ordinary project into something truly unique. We used Tic Tac Toe as our canvas, but guess what? You can sprinkle these magic tricks on any project.</p>
<p>Remember, your coding journey is not just about syntax and frameworks; it's about injecting your creativity to make every project uniquely yours.</p>
<p>So, whether you're developing a game, a website, or a mobile app, seize the opportunity to innovate and leave your distinctive mark. Now, armed with these tricks, go ahead, infuse your projects with creativity, and watch them soar to new heights! 🚀💻✨</p>
]]></content:encoded></item><item><title><![CDATA[Deploy Vite React App on Both GitHub Pages and Vercel]]></title><description><![CDATA[Hey developers, hope you're doing great!
Have you ever wondered about deploying your React project on both GitHub Pages and Vercel simultaneously? Well, it's not just possible; it's super simple!
Now, you might be thinking, 'Why would I do that?'
Let...]]></description><link>https://robiul.dev/deploy-vite-react-app-on-both-github-pages-and-vercel</link><guid isPermaLink="true">https://robiul.dev/deploy-vite-react-app-on-both-github-pages-and-vercel</guid><category><![CDATA[React]]></category><category><![CDATA[vite]]></category><category><![CDATA[Vercel]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[github-actions]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Mon, 20 Nov 2023 07:42:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1700323955165/c6a12b37-7bbc-498d-9078-97180686e6b1.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey developers, hope you're doing great!</p>
<p>Have you ever wondered about deploying your React project on both GitHub Pages and Vercel simultaneously? Well, it's not just possible; it's super simple!</p>
<p>Now, you might be thinking, 'Why would I do that?'</p>
<p>Let's be real; in most cases, you won't deploy the same project on different servers. But, here's the twist. I've noticed something among beginner developers who showcase their practical projects on GitHub Pages or Vercel for their portfolio. Often, the shared link doesn't work smoothly, creating a not-so-great impression. Imagine having a backup deployment on another platform! It's a solution to avoid those awkward moments.</p>
<p>So, I'm here to guide you through deploying on both GitHub Pages and Vercel. It's not just a tech hack, it's an exploration! Join me, and let's dive in together.</p>
<p>Are you ready for the journey?</p>
<blockquote>
<p>Note: While there are multiple methods to create a React app, for the purpose of this guide, we'll be considering a React project using Vite, known for its speed and simplicity, which offers an efficient front-end build process. Although other approaches exist, we've chosen Vite for its ease of use. And for the routing, I am using react router dom.</p>
</blockquote>
<p>All the code for this article is available on this <a target="_blank" href="https://github.com/robiulhr/deploy_react_app_github_pages_vercel">GitHub repository</a>. Feel free to check it out for a better understanding. Additionally, it can be used as a convenient template for kickstarting your React projects with GitHub Pages and Vercel. Feel free to fork, and utilize the code to enhance your development workflow.</p>
<h2 id="heading-deploy-vite-react-app-to-github-pages">Deploy Vite React app to GitHub Pages</h2>
<ol>
<li><p>Begin by configuring the base URL in the vite.config.js file. This step is crucial because GitHub Pages uses a subdirectory-like URL structure for Project Pages. When hosted on GitHub Pages, a project is accessible at a link resembling <code>&lt;ROOT&gt;/project-name/</code>.  </p>
<p> Define the base URL to match the project name to avoid errors and ensure your project can locate its assets correctly.  </p>
<p> This is how the links should look like:</p>
<pre><code class="lang-markdown"> ❌ Bad 
 https://robiulhr.github.io/assets/favicon.17e50649.svg  
 ✅ Good 
 https://robiulhr.github.io/deploy<span class="hljs-emphasis">_react_</span>app<span class="hljs-emphasis">_github_</span>pages<span class="hljs-emphasis">_vercel/assets/favicon.17e50649.svg</span>
</code></pre>
<p> Update the vite.config.js file accordingly. Here project name is the name of our repository which means use the repo name as the base URL.</p>
<pre><code class="lang-javascript"> base: <span class="hljs-string">"/deploy_react_app_github_pages_vercel"</span>;
</code></pre>
<p> after adding the base URL the <code>vite.config.js</code> file will look like this:</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700319425456/2a16aeef-316a-458a-85ae-dac1cbadcb73.png" alt="set the base url of project in vite.config.js file" class="image--center mx-auto" /></p>
</li>
<li><p>Add a homepage field to your project’s package.json:</p>
<pre><code class="lang-json"> <span class="hljs-string">"homepage"</span>: <span class="hljs-string">"https://username.github.io/repo_name"</span>
</code></pre>
<p> Replace username with your GitHub username and repo_name with your repository’s name.</p>
</li>
<li><p>Install gh-pages in your project:</p>
<pre><code class="lang-bash"> npm install --save gh-pages
</code></pre>
<p> Modify your package.json scripts by adding these two scripts below:</p>
<pre><code class="lang-json"> <span class="hljs-string">"scripts"</span>: {    
    <span class="hljs-attr">"predeploy"</span>: <span class="hljs-string">"npm run build"</span>,    
    <span class="hljs-attr">"deploy"</span>: <span class="hljs-string">"gh-pages -d dist"</span>, 
  }
</code></pre>
<p> <code>predeploy</code> ensures the latest build is ready before deployment, and <code>deploy</code> triggers the deployment process.</p>
</li>
<li><p>Since we've included the base URL in the <code>vite.config.js</code> file as the repo name for deployment, we need to make adjustments in our React Router DOM setup. In your project's router setup, locate the part where you create the router using <code>createBrowserRouter</code>.</p>
<p> As the second parameter of the createBrowserRouter method, add the following code:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> router = createBrowserRouter(routes, { <span class="hljs-attr">basename</span>: <span class="hljs-keyword">import</span>.meta.env.BASE_URL });
</code></pre>
<p> This line ensures that React Router DOM correctly handles the new base URL configuration.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700319780447/a8f74d38-8f80-46c3-bc1c-588f9345576f.png" alt="add basename to the roact router dom" class="image--center mx-auto" /></p>
</li>
<li><p>Execute the following command to deploy your application:</p>
<pre><code class="lang-bash"> npm run deploy
</code></pre>
<p> This command creates a new branch named <code>gh-pages</code> in your GitHub repository.</p>
</li>
<li><p>Set the source branch to <code>gh-pages</code> in the GitHub Pages section of your repository’s settings.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700320110764/c97ec05e-3b9c-4657-a476-9708ae3c31b2.png" alt="gh pages branch" class="image--center mx-auto" /></p>
<p> Navigate to Settings &gt; Pages to find the link to your deployed site.</p>
</li>
</ol>
<h3 id="heading-automate-deployment-using-github-actions">Automate Deployment using GitHub Actions</h3>
<p>Manually deploying your project to GitHub Pages works, but wouldn't it be convenient if this process happened automatically with every push to the main branch?</p>
<p>GitHub Actions makes this automation easy. You can create workflows that specify the steps to build and deploy your React app whenever changes are pushed to the specified branch.</p>
<p>GitHub Actions work by defining workflows using YAML files in a <code>.github/workflows</code> directory in your repository. These workflows contain a set of jobs and steps that GitHub will run in response to events, such as pushes, pull requests, or manual triggers.</p>
<ol>
<li><p>In your project repository, create a new folder named <code>.github/workflows</code> if it doesn't exist. Inside the <code>workflows</code> folder, create a new file named <code>deploy.yml</code>. This file will define your GitHub Actions workflow.</p>
</li>
<li><p>Paste the following YAML content into <code>deploy.yml</code>:</p>
<pre><code class="lang-yaml"> <span class="hljs-attr">name:</span> <span class="hljs-string">Deploy</span>

 <span class="hljs-attr">on:</span>
   <span class="hljs-attr">push:</span>
     <span class="hljs-attr">branches:</span>
       <span class="hljs-bullet">-</span> <span class="hljs-string">main</span>

 <span class="hljs-attr">jobs:</span>
   <span class="hljs-attr">build:</span>
     <span class="hljs-attr">name:</span> <span class="hljs-string">Build</span>
     <span class="hljs-attr">runs-on:</span> <span class="hljs-string">ubuntu-latest</span>

     <span class="hljs-attr">strategy:</span>
       <span class="hljs-attr">matrix:</span>
         <span class="hljs-attr">node-version:</span> [<span class="hljs-number">16.</span><span class="hljs-string">x</span>] <span class="hljs-comment"># Specify the Node.js version you want to use</span>

     <span class="hljs-attr">steps:</span>
       <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Checkout</span> <span class="hljs-string">repo</span>
         <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/checkout@v2</span>

       <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Setup</span> <span class="hljs-string">Node</span>
         <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/setup-node@v3</span>
         <span class="hljs-attr">with:</span>
           <span class="hljs-attr">node-version:</span> <span class="hljs-string">${{</span> <span class="hljs-string">matrix.node-version</span> <span class="hljs-string">}}</span>

       <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Install</span> <span class="hljs-string">dependencies</span>
         <span class="hljs-attr">run:</span> <span class="hljs-string">npm</span> <span class="hljs-string">install</span>

       <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Build</span> <span class="hljs-string">project</span>
         <span class="hljs-attr">run:</span> <span class="hljs-string">npm</span> <span class="hljs-string">run</span> <span class="hljs-string">build</span>

       <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Upload</span> <span class="hljs-string">production-ready</span> <span class="hljs-string">build</span> <span class="hljs-string">files</span>
         <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/upload-artifact@v2</span>
         <span class="hljs-attr">with:</span>
           <span class="hljs-attr">name:</span> <span class="hljs-string">production-files</span>
           <span class="hljs-attr">path:</span> <span class="hljs-string">./dist</span>

   <span class="hljs-attr">deploy:</span>
     <span class="hljs-attr">name:</span> <span class="hljs-string">Deploy</span>
     <span class="hljs-attr">needs:</span> <span class="hljs-string">build</span>
     <span class="hljs-attr">runs-on:</span> <span class="hljs-string">ubuntu-latest</span>
     <span class="hljs-attr">if:</span> <span class="hljs-string">github.ref</span> <span class="hljs-string">==</span> <span class="hljs-string">'refs/heads/main'</span>

     <span class="hljs-attr">steps:</span>
       <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Download</span> <span class="hljs-string">artifact</span>
         <span class="hljs-attr">uses:</span> <span class="hljs-string">actions/download-artifact@v2</span>
         <span class="hljs-attr">with:</span>
           <span class="hljs-attr">name:</span> <span class="hljs-string">production-files</span>
           <span class="hljs-attr">path:</span> <span class="hljs-string">./dist</span>

       <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Deploy</span> <span class="hljs-string">to</span> <span class="hljs-string">GitHub</span> <span class="hljs-string">Pages</span>
         <span class="hljs-attr">uses:</span> <span class="hljs-string">peaceiris/actions-gh-pages@v3</span>
         <span class="hljs-attr">with:</span>
           <span class="hljs-attr">github_token:</span> <span class="hljs-string">${{</span> <span class="hljs-string">secrets.GITHUB_TOKEN</span> <span class="hljs-string">}}</span>
           <span class="hljs-attr">publish_dir:</span> <span class="hljs-string">./dist</span>
</code></pre>
<p> This workflow consists of two jobs: build and deploy.</p>
<p> The build job installs dependencies and builds the project, while the deploy job uses the action to deploy the contents of the <code>./dist</code> directory to GitHub Pages.</p>
</li>
<li><p>Commit the changes to your repository and push them to the main branch.</p>
<pre><code class="lang-bash"> git add .
 git commit -m <span class="hljs-string">"Add GitHub Actions workflow for automatic deployment"</span>
 git push origin main
</code></pre>
</li>
<li><p>After running all the commands above, we can see our directory files on GitHub.</p>
<p> In the repository, proceed to the <a target="_blank" href="https://github.com/robiulhr/deploy_react_app_github_pages_vercel/actions/">Actions</a> tab. Click on the recent workflow.</p>
<p> you might notice that it failed initially due to missing permissions.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700321425593/829dcca8-b35c-4073-9582-928c11c8ddf8.png" alt="github workflow failed error" class="image--center mx-auto" /></p>
<p> Since our action modifies the repository, it requires write permissions.</p>
<p> To resolve this, Navigate to Actions Settings, Select Read and Write permissions, and Hit Save.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700321516844/aab62ab1-ed37-40bf-9f0c-218f3cabd9ac.png" alt="setup workflow action on github" class="image--center mx-auto" /></p>
<p> Now, check the status of your workflows. Go to Actions, and verify if the workflows have been executed successfully. If not, click on the failed workflow name. Inside the page, on the top-right section, you'll find an option to re-run the job.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700321598814/4c7fe7d3-99bb-4d9d-9e4e-39b2f0a2ed4e.png" alt="rerun failed workflow" class="image--center mx-auto" /></p>
<p> A successfully executed workflow will appear like this:</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700321653489/0180b57f-fa2f-411d-86cd-37caf663a24d.png" alt="check the workflow have executed successfully" class="image--center mx-auto" /></p>
<p> Now, with every update to your project, GitHub Actions will automatically build and deploy your React project to GitHub Pages, keeping your live demo up to date.</p>
</li>
</ol>
<h2 id="heading-deploy-vite-react-app-on-vercel">Deploy Vite react app on Vercel</h2>
<ol>
<li><p>To deploy your Vite React app on Vercel, begin by creating a new account. You can easily log in using OAuth.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700321957547/f4396c85-ce6b-4de1-bfc3-3a40efae2792.png" alt="login vercel" class="image--center mx-auto" /></p>
<p> Once logged in successfully, you'll land on the Vercel dashboard.</p>
</li>
<li><p>Import the project from the Git repository. If it's your first time using Vercel, you'll be prompted to install it for GitHub. Click "Install Now For GitHub" and follow the instructions. Save the settings for GitHub.</p>
</li>
<li><p>Navigate back to the <a target="_blank" href="https://vercel.com/import/git">import Git</a> page, and you'll see that your GitHub is now connected. Click "Import Project from GitHub.".</p>
</li>
<li><p>If you haven't given permission for your GitHub repo click on the 'Adjust GitHub App Permissions' to provide the necessary permission. This will open a popup and from this popup select the repo you want to deploy to give the Repository access and click save.</p>
</li>
<li><p>Now you will see your selected project repo on the 'Import Git Repository' section.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700322186275/1af83556-bd07-4072-919b-4d053b5a279c.png" alt="import project vercel" class="image--center mx-auto" /></p>
<p> Click "Import" and you'll get a form to enter the project name, root directory, and Framework preset.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700322304011/b9436647-6af3-49a9-a5b5-a808351e1c09.png" alt="new project vercel" class="image--center mx-auto" /></p>
</li>
<li><p>Make sure the Framework preset is selected as <code>vite</code> and the root directory is set to <code>./</code>.</p>
</li>
<li><p>Add an environment variable with the key as <code>VITE_BASE_PATH</code> and the value as <code>/</code>.  </p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700322507376/c8213c37-92af-48c1-bd67-492e865da2f4.png" alt="add environment variable" class="image--center mx-auto" /></p>
<p> You can name it anything, but ensure it starts with <code>VITE_</code> the preset. Leave other settings as default and click "Deploy."</p>
</li>
</ol>
<p>Your React application will deploy within seconds, providing two to three preview links.</p>
<h3 id="heading-handle-base-url-dynamically">Handle Base URL Dynamically</h3>
<p>Even though we've completed the deployment process on Vercel, there's one more thing to address.</p>
<p>Since we've set the repository name as the basename in our <code>vite.config.js</code> file, we need to configure this dynamically. Otherwise, Vite will use the <code>/repo-name</code> URL instead of root URL <code>/</code>.</p>
<p>Inside the vite.config.js file, update the base URL with the following line:</p>
<pre><code class="lang-javascript">base: process.env.VITE_BASE_PATH || <span class="hljs-string">'/deploy_react_app_github_pages_vercel'</span>,
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1700322993345/0b7d49db-0525-4c01-ab04-1b147e842357.png" alt="dynamic base url inside vite.config.js file" class="image--center mx-auto" /></p>
<p>With these changes, you've dynamically configured the base URL for your Vite React app on Vercel.</p>
<h3 id="heading-solve-client-side-routing-issue-on-vercel">Solve Client Side Routing issue on Vercel</h3>
<p>After completing all the deployment steps, there's one more thing to address: making client-side routing work seamlessly on Vercel. Without this setup, if you navigate to a sub-route of your project and refresh the page, it won't work.</p>
<p>Let's fix this react router issue on Vercel by adding a configuration file.</p>
<ul>
<li>Add a file called <code>vercel.json</code> to the root directory of your project.</li>
</ul>
<ul>
<li><p>Insert the following code into the <code>vercel.json</code> file:</p>
<pre><code class="lang-json">  {
    <span class="hljs-attr">"rewrites"</span>: [
      {
        <span class="hljs-attr">"source"</span>: <span class="hljs-string">"/(.*)"</span>,
        <span class="hljs-attr">"destination"</span>: <span class="hljs-string">"/index.html"</span>
      }
    ]
  }
</code></pre>
</li>
</ul>
<p>This configuration ensures that all routes lead to index.html, enabling proper client-side routing.</p>
<blockquote>
<p>Note: As deployment processes on platforms like GitHub Pages and Vercel are subject to frequent updates, it's possible that the steps outlined here might differ when you execute them. If you encounter any difficulties deploying your project, kindly share the specific issues in the comments section.  </p>
<p>For the most current and detailed information, consult the official Vercel documentation for deploying Vite applications: <a target="_blank" href="https://vercel.com/docs/frameworks/vite">vite on vercel</a></p>
</blockquote>
<p>With this setup, every time you push code to your repository, your project will be automatically deployed on both GitHub Pages and Vercel, providing a seamless and reliable deployment experience.</p>
<h2 id="heading-resources">Resources</h2>
<ul>
<li><p><a target="_blank" href="https://blog.logrocket.com/8-ways-deploy-react-app-free">8 ways to deploy a React app for free</a></p>
</li>
<li><p><a target="_blank" href="https://www.educative.io/answers/deploying-vite-project-to-github-pages">Deploying Vite project to GitHub Pages</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/sitek94/vite-deploy-demo">Deploy Vite app to GitHub Pages using GitHub Actions</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[I Made a Custom Version of Express.js Framework: Cute Express]]></title><description><![CDATA[Introduction
Hello there, fellow JavaScript and node js learner! We all know that practice makes perfect, and what's better than a challenge to level up our skills? I found myself on a mission to discover a project that could take my JavaScript and n...]]></description><link>https://robiul.dev/i-made-a-custom-version-of-expressjs-framework-cute-express</link><guid isPermaLink="true">https://robiul.dev/i-made-a-custom-version-of-expressjs-framework-cute-express</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Express]]></category><category><![CDATA[backend]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Wed, 09 Aug 2023 01:30:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1691477948422/4ea39d46-66b3-4666-b25e-e0ad6a0da00f.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Hello there, fellow JavaScript and node js learner! We all know that practice makes perfect, and what's better than a challenge to level up our skills? I found myself on a mission to discover a project that could take my JavaScript and node js knowledge to the next level. Something interesting, effective, and practical, where I could put all my learning into action.</p>
<p>And guess what? I found it - Cute Express!</p>
<p>It's my very own version of the famous Express.js framework. I built it from the heart, driven by my passion for coding and inspired by the elegance of Express js.</p>
<p>In this article, I'm thrilled to show you the cool things I've created and that is Cute Express.</p>
<p>Let's dive in and explore its features and functionalities together!</p>
<h2 id="heading-what-is-cute-express">What is Cute Express?</h2>
<p>Cute Express is a lightweight and feature-rich web framework that covers almost all basic and a few advanced features of <a target="_blank" href="https://expressjs.com/">Express.js</a>. It's like having a smaller and cuter clone, or you could even consider it a pocket-sized version of Express.js.</p>
<p>However, let's be clear – Cute Express isn't trying to conquer the web development world and It's not intended for industry use or to replace anything. It's a fun project I crafted purely for practicing my JavaScript and <a target="_blank" href="https://nodejs.org/en">Node.js</a> skills.</p>
<p>Unlike serious industry tools, Cute Express is your coding companion for creative experimentation. It's my way of exploring the world of web frameworks while having a blast.</p>
<p>So, join me as we unravel the adorable charm and practicality of Cute Express<br />together!</p>
<h2 id="heading-features-of-cute-express">Features of Cute Express</h2>
<p>Now, let's talk about the real deal – the features of Cute Express that I've crafted with my own hands tailored to my coding style and preferences.</p>
<p>Cute Express is all about embracing the tried-and-true features of Express.js – no frills, no extra fuss.</p>
<p>From routing to handling different <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods">HTTP methods</a>, Cute Express is packed with functionalities that mirror those of actual express js. I wanted to challenge myself and see if I could recreate the Express.js magic in my unique way, sticking to its core functionalities.</p>
<p>Just like Express.js, Cute Express lets you define routes, handle middleware, and respond to various <a target="_blank" href="https://www.geeksforgeeks.org/different-kinds-of-http-requests/">HTTP requests</a>. It's all about creating a smooth and intuitive experience for developers, just on a smaller scale.</p>
<h2 id="heading-setting-up-a-basic-server-with-cute-express">Setting Up a Basic Server with Cute Express</h2>
<p>let's start our journey by setting up a basic server.</p>
<p>To begin, let's install Cute Express as a dependency:</p>
<pre><code class="lang-bash">npm install cute-express
</code></pre>
<p>Learn more about the installation process from <a target="_blank" href="https://robiulhr.github.io/cute-express/getting_started/hello_world.html">Installing Cute Express</a>.</p>
<p>Now, let's create a simple server using Cute Express:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> cuteExpress = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cute-express'</span>) 
<span class="hljs-keyword">const</span> app = cuteExpress() 
<span class="hljs-keyword">const</span> port = <span class="hljs-number">3000</span>  

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">'Welcome to Cute Express!'</span>);
})  

app.listen(port, <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Example app listening on port <span class="hljs-subst">${port}</span>`</span>)
})
</code></pre>
<p>Do you notice the resemblance? The process mirrors the simplicity of creating a server in Express.js. With just a few lines of code, we have a basic server that listens on port <code>3000</code>. As you visit <code>http://localhost:3000</code> in your browser, you'll be greeted with the message <code>Welcome to Cute Express!</code></p>
<h2 id="heading-routing-with-cute-express">Routing with Cute Express</h2>
<p>Ah, <a target="_blank" href="https://robiulhr.github.io/cute-express/guide/routing.html">routing</a> – the heart and soul of any web framework. Let's dive into the world of routing in Cute Express, where we'll navigate through URLs and create delightful paths for our users to follow.</p>
<p>In Cute Express, routing is a breeze, and it'll feel just like home if you've ever worked with Express.js. Defining routes is straightforward:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> cuteExpress = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cute-express'</span>); 
<span class="hljs-keyword">const</span> app = cuteExpress();  

<span class="hljs-comment">// Define routes </span>
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">'Welcome to Cute Express!'</span>); 
});  

app.get(<span class="hljs-string">'/about'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
   res.send(<span class="hljs-string">'Learn more about Cute Express.'</span>); 
});  

app.post(<span class="hljs-string">'/contact'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
   <span class="hljs-comment">// Handle contact form submission </span>
});  

<span class="hljs-comment">// Start the server </span>
app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server is running on port 3000'</span>); 
});
</code></pre>
<p>Notice the familiarity? We're defining routes using <a target="_blank" href="https://robiulhr.github.io/cute-express/api_reference/api_reference_1.x.html#app-get-path-callback-callback"><code>app.get()</code></a> and <a target="_blank" href="https://robiulhr.github.io/cute-express/api_reference/api_reference_1.x.html#app-post-path-callback-callback"><code>app.post()</code></a> – just like you would in Express.js. When a user visits <code>/about</code>, Cute Express will greet them with <code>Learn more about Cute Express.</code></p>
<p>But wait, there's more! Cute Express also supports dynamic routing with parameters:</p>
<pre><code class="lang-javascript">app.get(<span class="hljs-string">'/user/:id'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
   <span class="hljs-keyword">const</span> userId = req.params.id;
   res.send(<span class="hljs-string">`Hello, User <span class="hljs-subst">${userId}</span>!`</span>); 
});
</code></pre>
<p>When a user visits <code>/user/42</code>, Cute Express will warmly say, <code>Hello, User 42!</code> This flexible routing lets you create personalized experiences for your users.</p>
<p>And guess what? You can even use regular expressions as paths, giving you the flexibility to match complex patterns and create advanced routing logic.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Using regular expressions as paths </span>
app.get(<span class="hljs-regexp">/\/product\/(\d+)/</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> productUrl = req.url;
  res.send(<span class="hljs-string">`Product ID: <span class="hljs-subst">${productUrl.split(<span class="hljs-string">"/"</span>)[<span class="hljs-number">2</span>]}</span>`</span>);  
});
</code></pre>
<h2 id="heading-middleware-in-cute-express">Middleware in Cute Express</h2>
<p><a target="_blank" href="https://robiulhr.github.io/cute-express/guide/writing_middleware.html">Middleware</a> – the mystical bridge between requests and responses. Just like Express.js, Cute Express supports middleware functions that can handle a wide range of tasks, from logging to authentication.</p>
<p>Declaring middleware in Cute Express is a breeze. Simply use <a target="_blank" href="https://robiulhr.github.io/cute-express/api_reference/api_reference_1.x.html#app-use-path-callback-callback"><code>app.use()</code></a> and unleash the power:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> cuteExpress = <span class="hljs-built_in">require</span>(<span class="hljs-string">'cute-express'</span>);
<span class="hljs-keyword">const</span> app = cuteExpress();

<span class="hljs-comment">// A simple middleware</span>
app.use(<span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'A request is coming in...'</span>);
  next(); <span class="hljs-comment">// Don't forget to call next to continue the flow</span>
});

<span class="hljs-comment">// More middleware functions...</span>
</code></pre>
<p>See? You can log messages, check authentication, or perform various operations in middleware. Cute Express maintains the order, executing middleware functions in the sequence they're defined.</p>
<p>But let's raise the stakes! How about middleware for specific routes?</p>
<p>Just like Express.js, Cute Express infuses middleware functions directly into your route declarations, creating a symphony of power and flexibility. Behold, the elegance of middleware in action:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Middleware for a specific route </span>
app.get(<span class="hljs-string">'/profile'</span>, <span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Middleware for /profile activated.'</span>);
   next(); 
}, 
<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
   res.send(<span class="hljs-string">'Welcome to your profile!'</span>); 
});
</code></pre>
<p>In this scenario, the middleware only activates when users venture into the <code>/profile</code> route.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As you've seen, Cute Express has some fascinating features that I've introduced here. However, there's a lot more to uncover beyond what I've covered in this article.</p>
<p>To make sure you have an enjoyable experience and don't get overwhelmed, I've focused on showing you the basics.</p>
<p>But don't stop here!</p>
<p>Dive into Cute Express by exploring its <a target="_blank" href="https://robiulhr.github.io/cute-express/">documentation</a>. It's like a map that will guide you through all the exciting places within the framework.</p>
<p>If you ever have thoughts, ideas, or suggestions, I'd be thrilled to hear them. Your input could make Cute Express even better for everyone.</p>
<p>And guess what? If you're feeling brave and want to contribute to this project, you're invited! Whether you're a coding expert or just starting, your input is valuable.</p>
<p>So, go ahead and let your creativity flow. Cute Express is here to accompany you on your coding journey.</p>
<p>Have fun exploring, and happy coding!</p>
<ul>
<li><p><a target="_blank" href="https://github.com/robiulhr/cute-express">Source code</a></p>
</li>
<li><p><a target="_blank" href="https://www.npmjs.com/package/cute-express">npm package</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[What are Programming Paradigms? - Master all Popular Ones]]></title><description><![CDATA[Introduction
Have you ever found yourself wondering what people mean when they talk about 'object-oriented programming' or 'functional programming'? These terms can sound confusing and leave you scratching your head, unsure of their true meaning.
Wel...]]></description><link>https://robiul.dev/what-are-programming-paradigms-master-all-popular-ones</link><guid isPermaLink="true">https://robiul.dev/what-are-programming-paradigms-master-all-popular-ones</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[paradigm]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Sat, 15 Jul 2023 01:30:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1689412963316/226c5ebf-5ef9-4690-8635-8a23d99e0bb8.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Have you ever found yourself wondering what people mean when they talk about 'object-oriented programming' or 'functional programming'? These terms can sound confusing and leave you scratching your head, unsure of their true meaning.</p>
<p>Well, fret not! In this article, I am here to make things crystal clear. We'll dive into the world of programming paradigms and explain these concepts in plain and simple language. We'll explore popular paradigms like object-oriented programming and functional programming, breaking them down into easy-to-understand ideas.</p>
<p>By the end of this article, you'll have a clear understanding of these programming paradigms and be able to join the conversation with confidence. No more confusion or feeling left out when people mention these terms!</p>
<p>Whether you are a seasoned developer or just starting your programming journey, this exploration of programming paradigms will broaden your horizons and empower you to think creatively and tackle complex problems with confidence.</p>
<p>So, Let's jump right in and explore this exciting world together!</p>
<h2 id="heading-what-are-programming-paradigms">What are Programming Paradigms?</h2>
<p>Programming paradigms are different ways or approaches that programmers use to write code. Just like there are various ways to approach everyday tasks, such as cooking or building, there are different approaches to coding.</p>
<p>Think of programming paradigms as different sets of instructions or strategies that programmers follow to solve problems and build software. Each paradigm has its unique characteristics and principles that guide how code is organized and structured. These different approaches yield the same result but involve different ways of thinking and organizing the process.</p>
<p>To better understand this concept, let's consider the process of making a cup of coffee.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689310399872/001bbbc1-56ab-4e01-8fed-7c69c7a561fe.webp" alt="making a cup of coffee" class="image--center mx-auto" /></p>
<p>When making coffee, you can approach it in different ways, just like programming paradigms offer different approaches to coding. When making a cup of coffee, you can follow a set of step-by-step instructions, where each action is explicitly defined (imperative approach).</p>
<p>You measure the water, grind the coffee beans, heat the water to a specific temperature, pour the water over the coffee grounds, and finally, enjoy your cup of coffee.</p>
<p>Each action is explicitly defined, and you have full control over every step of the process.</p>
<p>On the other hand, Alternatively, you can describe the desired outcome without specifying each step (declarative approach).</p>
<p>You simply state that you want a cup of coffee. This approach focuses on the end result rather than the specific instructions. The coffee machine takes care of the process, determining the water temperature, grind size, and other details to achieve the desired outcome.</p>
<p>In this case, someone else, like the coffee machine, has already defined how the process of making coffee should be done. These different approaches yield the same result—a cup of coffee—but involve different ways of thinking and organizing the process.</p>
<p>In the declarative approach, the responsibility for executing the detailed steps lies with someone else or a pre-existing system.</p>
<p>Similarly, programming paradigms offer different ways to tackle coding challenges. Some paradigms focus on specifying explicit instructions (imperative), while others prioritize describing the desired outcome (declarative). Each paradigm offers its own benefits and considerations.</p>
<h2 id="heading-what-programming-paradigms-are-not">What Programming Paradigms are Not?</h2>
<p>Besides understanding what programming paradigms are, it is equally important to know what programming paradigms are not. This clarity is especially crucial for new programmers to avoid confusion and misconceptions.</p>
<p>This Understanding will help you approach the subject with a clearer perspective, appreciating the strengths and limitations of each paradigm.</p>
<p>Firstly, a programming paradigm is not a specific programming language or a strict set of rules. It's not a one-size-fits-all solution or a magic trick for solving every programming problem effortlessly.</p>
<p>Instead, think of programming paradigms as shared ways of thinking and organizing code. They're like guiding principles and ideas that programmers agree upon and follow.</p>
<p>Secondly, programming paradigms are not a strict progression or separate categories. They can coexist within a programming language or project. Developers often mix and match different paradigms based on their software's needs.</p>
<p>Programming languages are not always tied to a single paradigm. Some languages are designed for a particular paradigm, but many languages allow you to adapt your code to fit different paradigms.</p>
<p>It's important to understand that using a specific programming paradigm doesn't guarantee good or bad code. The quality of code depends on factors like the developer's skills, best practices, and coding standards, regardless of the paradigm used.</p>
<p>Remember, programming paradigms are flexible frameworks, not strict rules, allowing you to navigate the programming landscape and make informed decisions in your coding journey.</p>
<h2 id="heading-why-should-i-care">Why should I care?</h2>
<p>To answer this question in short, Programming paradigms are essential general knowledge for developers.</p>
<p>However, if we delve into a more detailed explanation, we discover that Exploring programming paradigms is not only interesting but also crucial for expanding your understanding of different approaches to programming. It goes beyond the usual tools and techniques, encouraging you to think creatively and explore new problem-solving strategies.</p>
<p>You've probably come across terms like object-oriented programming (OOP) or functional programming in the coding world. Having a basic understanding of programming paradigms helps you grasp these concepts and enhances your overall comprehension of programming.</p>
<p>Ever wondered why there are so many programming languages out there?</p>
<p>Understanding programming paradigms holds the key to unraveling this mystery.</p>
<p>Each paradigm represents a unique philosophy and set of principles that shape how developers think and solve problems.</p>
<p>For example, in OOP, developers focus on modeling real-world objects and their interactions. They use concepts like encapsulation, inheritance, and polymorphism to organize their code and promote code reuse.</p>
<p>Embracing OOP allows for a modular and intuitive approach to development, enabling developers to analyze problems based on objects and relationships. This flexibility in thinking and problem-solving is highly valuable in the dynamic field of software development.</p>
<p>Developers who embrace different paradigms become more adaptable and can tackle challenges from various perspectives. They have a wider range of tools at their disposal, allowing them to choose the most suitable paradigm for a specific task or even combine paradigms to create powerful solutions.</p>
<h2 id="heading-types-of-programming-paradigms">Types of Programming Paradigms</h2>
<p>While there are multiple programming paradigms, we can categorize them into two major groups:</p>
<ul>
<li><p><code>Imperative Paradigms</code>: Imperative paradigms focus on explicitly defining step-by-step instructions to manipulate the program state.</p>
</li>
<li><p><code>Declarative Paradigms</code>: Declarative paradigms focus on describing the desired outcome or result, rather than explicitly specifying the steps to achieve it.</p>
</li>
</ul>
<p>Almost all major programming paradigms have a main concept of either instructing the computer step-by-step or describing the desired outcome and they can be broadly categorized as either imperative or declarative.</p>
<p>However, every programming paradigm comes in different flavors, each with its own unique ideas, benefits, and challenges.</p>
<p>But in this article, we will mainly focus on understanding the imperative and declarative nature of programming paradigms to make it simple to understand.</p>
<h2 id="heading-understanding-the-major-programming-paradigms">Understanding the Major Programming Paradigms</h2>
<p>So far, we have discussed what programming paradigms are and why they matter.</p>
<p>Now let's explore a few of them...</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689312590220/62060f3c-7ce9-411f-9a2a-c4f81e6b7914.webp" alt="Understanding the Major Programming Paradigms" class="image--center mx-auto" /></p>
<blockquote>
<p>Note: Keep in mind that this list is not complete, as there are other programming paradigms beyond what we'll cover here. However, we will focus on the most popular and widely-used ones.</p>
</blockquote>
<h3 id="heading-imperative-programming-paradigm">Imperative Programming Paradigm</h3>
<p>Imperative programming serves as the foundation for many programming paradigms. It consists of sets of detailed instructions that are given to the computer to execute in a given order.</p>
<p>It's called "imperative" because as programmers, we dictate exactly what the computer has to do in a very specific way.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689324925903/74ee75b5-d00b-4f4c-979c-394fad10c3dd.webp" alt="Imperative Programming Paradigm" class="image--center mx-auto" /></p>
<p>Imperative programming focuses on explicitly defining step-by-step instructions to manipulate the program state. Programs are composed of a sequence of statements that change the variable's values and control flow. Imperative programming provides a basic structure for other paradigms to build upon.</p>
<p>Let's consider the following coding problem to understand more:</p>
<p><code>Problem</code>: Given an <a target="_blank" href="https://www.w3schools.com/js/js_arrays.asp">array</a> of integers, find the average of these numbers.</p>
<p>We can solve this problem using different programming paradigms, such as imperative, procedural, object-oriented, functional, and declarative programming.</p>
<p>In imperative programming, we would iterate over the array, keeping track of the sum and count of the numbers encountered. We can use a <a target="_blank" href="https://robiul.dev/javascript-loop-best-practices-for-optimal-performance">loop</a> and an accumulator variable to update the sum.</p>
<p>Here's an example solution in JavaScript:</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-number">50</span>];
<span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
<span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>;

<span class="hljs-comment">// Iterate through each element in the numbers array</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; numbers.length; i++) {
  <span class="hljs-comment">// Accumulate the sum of the numbers</span>
  sum += numbers[i];
  <span class="hljs-comment">// Increment the count of elements</span>
  count++;
}

<span class="hljs-comment">// Calculate the average by dividing the sum by the count</span>
<span class="hljs-keyword">const</span> average = sum / count;

<span class="hljs-comment">// Output the calculated average</span>
<span class="hljs-built_in">console</span>.log(average);
</code></pre>
<p>Here we define the necessary <a target="_blank" href="https://robiul.dev/javascript-variables-beginner-thinking">variables</a>, sum, and count, and initialize them both to <code>0</code>. We then proceed with a loop that iterates through each element in the numbers array.</p>
<p>Inside the loop, we accumulate the sum of the numbers by adding each element to the sum variable, and simultaneously increment the count variable to keep track of the number of elements encountered.</p>
<p>Once the loop completes, we calculate the average by dividing the accumulated sum by the count of elements. The result is stored in the average variable.</p>
<p>Finally, we output the calculated average to the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/console">console</a> using <code>console.log(average)</code>.</p>
<p>In this imperative solution, we're focusing on describing "how" to perform tasks providing detailed and specific instructions to the program. We are We explicitly iterate through each element in the array, accumulate the sum, and keep track of the count.</p>
<p>Imperative programming languages, such as <a target="_blank" href="https://en.wikipedia.org/wiki/C_(programming_language)">C</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Pascal_(programming_language)">Pascal</a>, or <a target="_blank" href="https://en.wikipedia.org/wiki/Python_(programming_language)">Python</a>, follow a step-by-step approach to execute code. Developers provide explicit instructions to the computer, specifying exactly how to perform each task. This level of control and specificity allows for fine-grained manipulation of program state and enables precise control over program flow.</p>
<p>Imperative programming is particularly useful in scenarios where detailed control is required, such as low-level programming, <a target="_blank" href="https://www.geeksforgeeks.org/introduction-to-algorithms/">algorithm</a> implementation, or situations where efficiency is a primary concern.</p>
<p>However, it can sometimes result in verbose and complex code, especially for large-scale applications. Therefore, it is important to strike a balance between explicit instructions and code readability when employing imperative programming.</p>
<h3 id="heading-procedural-programming-paradigm">Procedural Programming Paradigm</h3>
<p>Procedural programming is a programming paradigm that focuses on breaking down a program into a set of procedures or <a target="_blank" href="https://www.w3schools.com/js/js_functions.asp">functions</a>. It emphasizes dividing the program into smaller, manageable chunks of code that can be executed in a specific order.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689325168165/a8c80187-ba7a-4e2d-810b-a2c63ee438e1.webp" alt="Procedural Programming Paradigm" class="image--center mx-auto" /></p>
<p>It is closely related to imperative programming and can be considered a subset of it. Procedural programming extends imperative programming by introducing the concept of functions or procedures. It still shares the fundamental idea of providing step-by-step instructions to the computer, specifying the precise sequence of actions to be performed.</p>
<p>One of the key advantages of procedural programming is its emphasis on code modularity and reusability. By breaking the program into separate procedures or functions, developers can create reusable blocks of code that can be called from different parts of the program.</p>
<p>This promotes code organization, simplifies maintenance, and reduces code duplication. Procedures encapsulate a set of instructions, making the code more manageable and easier to understand.</p>
<p>Procedural programming provides a structured approach to program design and works well for problems that can be divided into logical, sequential steps. It allows developers to focus on specific tasks or subroutines, making it easier to reason about and debug the code.</p>
<p>Here's an example that demonstrates procedural programming using the previous problem of calculating the average of a list of numbers:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateAverage</span>(<span class="hljs-params">numbers</span>) </span>{
  <span class="hljs-keyword">const</span> sum = sumNumbers(numbers);
  <span class="hljs-keyword">const</span> count = numbers.length;
  <span class="hljs-keyword">const</span> average = sum / count;
  <span class="hljs-keyword">return</span> average;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumNumbers</span>(<span class="hljs-params">numbers</span>) </span>{
  <span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; numbers.length; i++) {
    sum += numbers[i];
  }
  <span class="hljs-keyword">return</span> sum;
}

<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> result = calculateAverage(numbers);
<span class="hljs-built_in">console</span>.log(result);
</code></pre>
<p>In this example, we define the <code>calculateAverage</code> function that takes an array of numbers as input. Instead of calculating the sum and count within the <code>calculateAverage</code> function as we did in the imperative paradigm, we introduce a separate function <code>sumNumbers</code> that calculates the sum of the numbers.</p>
<p>The <code>calculateAverage</code> function calls the <code>sumNumbers</code> function to obtain the <code>sum</code>, calculates the <code>count</code> using the length of the numbers array, and then calculates the average by dividing the sum by the count.</p>
<p>By breaking down the problem into reusable functions, procedural programming promotes code modularity and reusability. Each function has a specific responsibility, making the code easier to understand and maintain.</p>
<p>Procedural programming is commonly used in languages like C, Pascal, and <a target="_blank" href="https://en.wikipedia.org/wiki/Fortran">Fortran</a>.</p>
<p>However, many modern languages, including Python and JavaScript, also support procedural programming alongside other paradigms, allowing developers to choose the most appropriate approach for their projects.</p>
<h3 id="heading-object-oriented-programming-paradigm">Object-Oriented Programming Paradigm</h3>
<p>One of the most popular and widely used programming paradigms is object-oriented programming (OOP). It focuses on representing real-world entities as objects and organizing code around these objects.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689326050987/709fef45-f2b8-4410-b3fc-11890a70d43a.webp" alt="Object-Oriented Programming Paradigm" class="image--center mx-auto" /></p>
<p>It provides a way to structure programs by grouping related data and behavior into objects, which are instances of classes. Object-oriented programming builds upon the foundations of imperative and procedural programming.</p>
<p>It takes the concept of breaking down a program into smaller, reusable parts (functions or procedures) and extends it to objects, which encapsulate both data and behavior.</p>
<p>Objects in OOP act as self-contained entities that can communicate and interact with each other through well-defined interfaces. This enhances code organization and promotes reusability, allowing for more modular and maintainable codebases.</p>
<p>In the object-oriented paradigm, objects are the fundamental building blocks. An object encapsulates data (known as attributes or properties) and behaviors (known as methods) that operate on that data. Objects interact with each other through method invocations and can communicate by sending messages.</p>
<p>OOP introduces the concept of classes, which are blueprints for creating objects. A class defines the structure and behavior of objects, including their attributes and methods. Objects are instances of classes, meaning they are created based on the class definition.</p>
<blockquote>
<p>Note: There are multiple types of OOP paradigms such as <a target="_blank" href="https://en.wikipedia.org/wiki/Prototype-based_programming">Prototype-based</a>, and <a target="_blank" href="https://en.wikipedia.org/wiki/Class-based_programming">class-based</a>.</p>
</blockquote>
<p>Key concepts in Object-Oriented Programming include:</p>
<ul>
<li><p><code>Encapsulation</code>: Encapsulation is like putting related things together in a box. It keeps some information private and provides a way to interact with it through a public interface.</p>
</li>
<li><p><code>Inheritance</code>: Inheritance is like passing down traits from parents to children. It allows new classes to inherit properties and behaviors from existing classes.</p>
</li>
<li><p><code>Polymorphism</code>: Polymorphism is like using the same word to mean different things in different contexts. It allows objects of different types to be treated as if they were the same type.</p>
</li>
<li><p><code>Abstraction</code>: Abstraction is like simplifying something complex. It focuses on the important parts while hiding unnecessary details.</p>
</li>
</ul>
<p>Here's an example that demonstrates the Object-Oriented Programming Paradigm using the previous problem of calculating the average of a list of numbers:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AverageCalculator</span> </span>{
   <span class="hljs-keyword">constructor</span>(numbers) {
     <span class="hljs-built_in">this</span>.numbers = numbers;
   }
    calculateAverage() {
     <span class="hljs-keyword">const</span> sum = <span class="hljs-built_in">this</span>.sumNumbers();
     <span class="hljs-keyword">const</span> count = <span class="hljs-built_in">this</span>.numbers.length;
     <span class="hljs-keyword">const</span> average = sum / count;
     <span class="hljs-keyword">return</span> average;
   }
    sumNumbers() {
     <span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
     <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.numbers.length; i++) {
       sum += <span class="hljs-built_in">this</span>.numbers[i];
     }
     <span class="hljs-keyword">return</span> sum;
   }
 }

 <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> calculator = <span class="hljs-keyword">new</span> AverageCalculator(numbers);
 <span class="hljs-keyword">const</span> result = calculator.calculateAverage();
 <span class="hljs-built_in">console</span>.log(result);
</code></pre>
<p>In this Object-Oriented Programming example, we define a class <code>AverageCalculator</code> that represents a calculator object for calculating the average of a list of numbers. The class has a <code>constructor</code> that takes an array of numbers as input and assigns it to the <code>numbers</code> property.</p>
<p>It also defines two methods: <code>calculateAverage()</code> to calculate the average and <code>sumNumbers()</code> to calculate the sum of the numbers. We create an instance of the <code>AverageCalculator</code> class by passing the numbers array to the constructor.</p>
<p>Then, we call the <code>calculateAverage()</code> method on the instance to obtain the average.</p>
<p>Finally, we log the result to the console. In this OOP approach, we encapsulate the data (the numbers array) and the behavior (the calculation methods) within the <code>AverageCalculator</code> class.</p>
<p>By creating an instance of the class, we can perform average calculations on different sets of numbers, promoting reusability and modularity.</p>
<p>Object-Oriented Programming provides a modular and extensible approach to software development. It allows for the creation of reusable code components, enhances code organization, and facilitates the modeling of complex systems.</p>
<p>OOP is widely used in languages such as <a target="_blank" href="https://en.wikipedia.org/wiki/Java_(programming_language)">Java</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/C%2B%2B">C++</a>, and <a target="_blank" href="https://en.wikipedia.org/wiki/Python_(programming_language)">Python</a> to build robust and scalable applications.</p>
<h3 id="heading-declarative-programming-paradigm">Declarative Programming Paradigm</h3>
<p>Declarative programming is a programming paradigm that focuses on expressing the desired outcome or result, rather than specifying the exact steps to achieve it. It's all about hiding away complexity and bringing programming languages closer to human language and thinking.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689326392725/cbbbf765-fdef-401a-9bcf-d2255228feda.webp" alt="Declarative Programming Paradigm" class="image--center mx-auto" /></p>
<p>It contrasts with imperative programming, where the programmer provides instructions on how to execute a task. In declarative programming, the emphasis is on what needs to be achieved, leaving the implementation details to the underlying system or framework.</p>
<p>This paradigm utilizes declarations, constraints, and high-level abstractions to describe the problem domain and define the desired behavior. It encompasses various sub-paradigms such as functional programming, logic programming, and database <a target="_blank" href="https://en.wikipedia.org/wiki/Query_language#:~:text=A%20query%20language%2C%20also%20known,Structured%20Query%20Language%20(SQL).">query languages</a>, each with its unique characteristics.</p>
<p>Key features of declarative programming include its focus on specifying the desired result, expressing constraints and relationships, employing high-level abstractions, promoting code reusability, and emphasizing data transformations over direct state manipulation.</p>
<p>Let's take the example of calculating the average of a list of numbers to demonstrate the declarative programming paradigm:</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-number">50</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-keyword">const</span> average = sum / numbers.length;

<span class="hljs-built_in">console</span>.log(average);
</code></pre>
<p>In this example, we use the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce">reduce</a> method, a <a target="_blank" href="https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/#:~:text=A%20higher%20order%20function%20is%20a%20function%20that%20takes%20one,functions%20like%20map%20and%20reduce.">higher-order function</a> in JavaScript, to declaratively calculate the sum of the numbers in the array. We provide a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">callback function</a> that defines the accumulation logic. The reduce method iterates over each element of the array, updating the accumulator by adding the current element's value.</p>
<p>Finally, we divide the sum by the length of the array to calculate the average.</p>
<p>See that with the reduce function, we're not explicitly telling the computer to iterate over the array. We just say what we want ("reduce") and update the accumulator by adding the current element's value.</p>
<p>By utilizing <a target="_blank" href="https://www.freecodecamp.org/news/higher-order-functions-in-javascript-explained/#:~:text=A%20higher%20order%20function%20is%20a%20function%20that%20takes%20one,functions%20like%20map%20and%20reduce.">higher-order functions</a> and method chaining, this declarative programming approach allows us to express complex computations concisely. The focus is on describing the desired result (the sum and average calculation) rather than specifying the step-by-step procedure.</p>
<p>One of the advantages of declarative programming is its ability to improve code clarity, reusability, and maintainability. By separating the problem description from the implementation details, declarative programming enhances code readability and reduces the likelihood of introducing bugs.</p>
<p>It enables programmers to express computations as a composition of functions and transformations, promoting code organization and comprehension.</p>
<blockquote>
<p>Note: It's important to note that while declarative programming hides away the complexity of implementation details, the computer still processes the information using imperative code.</p>
</blockquote>
<h3 id="heading-functional-programming-paradigm">Functional Programming Paradigm</h3>
<p>Functional programming is another widely used programming paradigm, closely related to declarative programming and often considered a subset of it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689326637970/347b723e-42d4-482b-ad0b-711a745bfe03.webp" alt="Functional Programming Paradigm" class="image--center mx-auto" /></p>
<p>Functional programming treats functions as <a target="_blank" href="https://www.javascripttutorial.net/javascript-functions-are-first-class-citizens/#:~:text=Summary-,Functions%20are%20first%2Dclass%20citizens%20in%20JavaScript.,and%20store%20them%20in%20variables.">first-class citizens</a>, enabling them to be assigned to <a target="_blank" href="https://robiul.dev/javascript-variables-beginner-thinking">variables</a>, passed as arguments, and returned from other functions. This paradigm focuses on immutability, <a target="_blank" href="https://www.freecodecamp.org/news/what-is-a-pure-function-in-javascript-acb887375dfe/">pure functions</a>, and higher-order functions.</p>
<p>Pure functions are fundamental in functional programming. They solely depend on their inputs to produce results and have no side effects. Regardless of the context, a pure function will always produce the same output for the same input. This enhances code reliability and predictability.</p>
<p>Functional programming languages like <a target="_blank" href="https://en.wikipedia.org/wiki/Haskell">Haskell</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/Lisp_(programming_language)">Lisp</a>, and JavaScript (with libraries like <a target="_blank" href="https://legacy.reactjs.org/">React</a>) promote the use of functions as first-class citizens and encourage a declarative and concise coding style. The paradigm discourages mutable state and data modification, promoting code reliability and predictability.</p>
<p>Functional programming emphasizes higher-order functions, which provide flexibility and enable <a target="_blank" href="https://www.freecodecamp.org/news/function-composition-in-javascript/">function composition</a> and reusability. By emphasizing modularity and avoiding side effects, functional programming makes it easier to identify and separate responsibilities within the codebase, improving code maintainability.</p>
<p>Taking the example of calculating the average of an array, we can demonstrate the functional programming approach:</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-number">50</span>];

<span class="hljs-comment">// Function to calculate the average </span>
<span class="hljs-keyword">const</span> calculateAverage = <span class="hljs-function">(<span class="hljs-params">arr</span>) =&gt;</span> {
   <span class="hljs-keyword">const</span> sum = arr.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-keyword">const</span> count = arr.length;
   <span class="hljs-keyword">return</span> sum / count;
};

<span class="hljs-comment">// Calculate the average using the functional approach </span>
<span class="hljs-keyword">const</span> average = calculateAverage(numbers);
<span class="hljs-built_in">console</span>.log(average)
</code></pre>
<p>In this functional programming example, code is almost the same as the declarative paradigm, but we wrap our iteration within a function called <code>calculateAverage</code>. It uses the reduce method to calculate the sum of the numbers in the array and then divides it by the length of the array to obtain the average.</p>
<p>The <code>calculateAverage</code> function is a pure function as it solely depends on its input and produces a predictable output without modifying any external state. This promotes code reusability, modularity, and easier testing.</p>
<p>By encapsulating the logic within the <code>calculateAverage</code> function, we ensure that it doesn't modify anything outside its scope. It processes its information within the function and doesn't have any side effects on the surrounding code.</p>
<p>Functional programming encourages writing programs primarily using functions. By promoting code modularity, immutability, and the absence of side effects, functional programming enhances code reliability and maintainability.</p>
<h2 id="heading-importance-of-choosing-the-right-paradigm">Importance of Choosing the Right Paradigm</h2>
<p>Choosing the right programming paradigm can seem pointless to beginners at times.</p>
<p>After all, most paradigms can work fine for many scenarios, and getting the work done is the primary objective. However, selecting the appropriate paradigm involves considering various factors beyond immediate functionality.</p>
<p>Paradigms have a significant impact on code management, project extensibility, code performance, and other aspects of software development. Merely achieving the desired outcome is not enough reason to choose a paradigm. It's crucial to evaluate how well the paradigm aligns with the project requirements and long-term goals.</p>
<p>A well-suited paradigm can improve code organization, maintainability, and readability. It can provide the necessary structure for future scalability and ease of maintenance.</p>
<p>Additionally, certain paradigms may optimize code performance, making it more efficient and resource-friendly.</p>
<p>Therefore, it's essential to weigh the pros and cons of different paradigms and assess their compatibility with the project's specific needs. It's not just about making the work done; it's about selecting the paradigm that can best address the broader aspects of software development and contribute to the success of the project.</p>
<h2 id="heading-how-to-choose-the-right-paradigm">How to Choose the Right Paradigm</h2>
<p>After knowing the importance of choosing the right paradigm, you may wonder how to choose the right paradigm for your project or development needs.</p>
<p>It is essential to acknowledge that selecting the appropriate paradigm is a complex task that requires a strong understanding of programming principles and substantial experience working with different paradigms.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689328590379/a50378b1-a82c-4a7b-b4a8-0ca36145d88e.webp" alt="How to Choose the Right Paradigm" class="image--center mx-auto" /></p>
<p>However, to gain a basic understanding, let's explore some key points that should be considered when choosing the right programming paradigm:</p>
<ul>
<li><p><code>Nature of the Problem</code>: Consider the nature of the problem you are trying to solve. Some paradigms align naturally with specific types of problems. For example, functional programming is well-suited for complex mathematical calculations or data transformations.</p>
</li>
<li><p><code>Project Requirements</code>: Evaluate the specific requirements of your project. Each paradigm offers different strengths. If code organization, modularity, and reuse are important, an object-oriented paradigm might be a good fit.</p>
</li>
<li><p><code>Team Expertise</code>: Take into account the expertise and experience of your development team. If they are skilled in a particular paradigm, leveraging their expertise can lead to greater efficiency. However, exploring new paradigms can also enhance their problem-solving abilities and broaden their skill set.</p>
</li>
<li><p><code>Available Resources</code>: Consider the availability of tools, libraries, and frameworks that support the paradigm you are considering. Some paradigms have extensive ecosystems and resources that can facilitate development.</p>
</li>
<li><p><code>Compatibility and Integration</code>: Think about how well a particular paradigm integrates with your existing codebase or external systems. Maintaining consistency can be beneficial, but choosing a paradigm that aligns well with external systems can simplify integration efforts.</p>
</li>
<li><p><code>Hybrid Approaches</code>: Remember that you are not limited to a single paradigm. Many programming languages support multiple paradigms and allow hybrid approaches. You can combine paradigms to leverage their strengths in different aspects of your project.</p>
</li>
</ul>
<p>Ultimately, the choice of programming paradigm should be based on careful consideration of project requirements, problem domain, team expertise, and available resources. Evaluate the strengths and limitations of each paradigm and determine how well they align with your specific needs.</p>
<h2 id="heading-misconceptions-about-programming-paradigms">Misconceptions about Programming Paradigms</h2>
<p>At this point in the article, we have covered all the major programming paradigms and Choosing the right paradigm.</p>
<p>Now, let's address Two common misconceptions that often arise in discussions about programming paradigms.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689327709153/367f0b5d-57e1-4f85-83b4-394f7be2a17f.webp" alt="Misconceptions about Programming Paradigms" class="image--center mx-auto" /></p>
<h3 id="heading-misconception-1-one-paradigm-is-superior-to-others">Misconception 1: "One Paradigm is Superior to Others"</h3>
<p>It's important to note that no single programming paradigm is inherently superior to others. Each paradigm has its strengths and weaknesses, and its effectiveness depends on the context in which they are applied.</p>
<p>The choice of a programming paradigm should be based on the specific requirements of the project, the problem domain, team expertise, and available resources. A paradigm that works well for one project may not be the best fit for another.</p>
<p>Instead of viewing paradigms as competitors, it's more productive to see them as tools in a developer's toolkit. Each paradigm provides unique approaches and techniques that can be utilized to solve different types of problems efficiently.</p>
<p>Furthermore, many modern programming languages support multiple paradigms, allowing developers to mix and match approaches as needed. Hybrid approaches that combine paradigms can often lead to more flexible and robust solutions.</p>
<p>The key is to have a broad understanding of different paradigms and their underlying principles. This knowledge empowers developers to make informed decisions and choose the most appropriate paradigm for a given situation.</p>
<p>Remember, the goal of programming is to solve problems effectively and efficiently. By embracing the diversity of programming paradigms and understanding their strengths, developers can unlock their full potential and create innovative and high-quality software solutions.</p>
<h3 id="heading-misconception-2-one-paradigm-to-rule-them-all">Misconception 2: "One Paradigm to Rule Them All"</h3>
<p>The funniest misconception about programming paradigms is the belief in "One Paradigm to Rule Them All". It's like thinking there's a magical programming approach that can solve every problem and is superior to all others. Imagine if there were a legendary programming paradigm that had all the answers, like a superhero of programming.</p>
<p>This misconception humorously suggests that this mythical paradigm would be incredibly powerful, efficient, and adaptable, capable of tackling any software challenge effortlessly.</p>
<p>But here's the reality: programming paradigms are diverse and designed for different purposes. Each paradigm has its own strengths and limitations, and no single paradigm can be the best for every situation. It's like saying there's one perfect tool that can fix any problem, from fixing a leaky faucet to building a skyscraper!</p>
<p>In the real world of software development, projects have unique requirements and demands. That's why developers need to understand the various paradigms and choose the most suitable one for each situation. It's about using the right tool for the right job, rather than searching for a mythical all-in-one solution.</p>
<p>So, while the idea of a "One Paradigm to Rule Them All" is humorous, it reminds us that programming is diverse and exciting, with a range of paradigms to explore and combine. Embracing this diversity allows developers to adapt their approaches, solve problems creatively, and build robust and innovative software.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Programming paradigms play a crucial role in shaping how developers approach problem-solving and code organization. Each paradigm offers its own unique characteristics and approaches, providing developers with diverse tools to tackle different types of problems effectively.</p>
<p>Whether it's imperative, object-oriented, functional, or a combination of paradigms, selecting the right approach can greatly influence the quality and success of a software project.</p>
<p>Keep exploring these paradigms, experimenting with their principles, and expanding your programming toolkit. With a solid understanding of different paradigms, you'll be well-equipped to approach diverse programming challenges with confidence and creativity.</p>
<p>Happy Coding :)</p>
<h2 id="heading-resources"><strong>Resources</strong></h2>
<ul>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-programming-paradigms/">https://www.freecodecamp.org/news/an-introduction-to-programming-paradigms/</a></p>
</li>
<li><p><a target="_blank" href="https://en.wikipedia.org/wiki/Programming_paradigm">https://en.wikipedia.org/wiki/Programming_paradigm</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[What is Node.js Exactly? - Real World Example]]></title><description><![CDATA[Introduction
Welcome to this article where we will Find out What is Node.js Exactly and will explore the world of Node.js. We often associate JavaScript with making websites interactive and dynamic,
but did you know that it was mainly confined to web...]]></description><link>https://robiul.dev/what-is-nodejs-exactly-real-world-example</link><guid isPermaLink="true">https://robiul.dev/what-is-nodejs-exactly-real-world-example</guid><category><![CDATA[Node.js]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Wed, 21 Jun 2023 01:10:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1689247843161/d6347e3b-c5a3-402e-9e6d-4812ef4c5514.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Welcome to this article where we will Find out What is <a target="_blank" href="https://nodejs.org/en/docs">Node.js</a> Exactly and will explore the world of Node.js. We often associate JavaScript with making websites interactive and dynamic,</p>
<p>but did you know that it was mainly confined to web browsers?</p>
<p>That's where Node.js comes in. It's like a magical tool that frees JavaScript from its browser boundaries and unlocks its true potential.</p>
<p>In this article, we will take a closer look at how Node.js empowers JavaScript to operate outside the browser and create powerful web applications. we'll explore the features and benefits of Node.js in more detail.</p>
<p>But don't worry, I won't get too technical. My goal is to explain everything in simple terms and use real-life analogies so that everyone, even if you're new to programming, can understand what Node.js is all about and why it's so prevalent in web development.</p>
<p>So, let's dive in and discover the exciting world of Node.js together!</p>
<h2 id="heading-what-is-nodejs-exactly">What is Node.js exactly?</h2>
<p>You may have come across the definition of Node.js as a JavaScript runtime that runs JavaScript outside the browser. However, this definition can be confusing at first.</p>
<p>Let's break it down into simpler terms.</p>
<p>Think of Node.js as a tool or platform that allows JavaScript to be executed beyond the confines of a web browser. It provides JavaScript with the capability to run on servers, computers, or devices.</p>
<p>In other words, Node.js expands the scope of JavaScript, enabling it to be used for server-side development and other applications outside the browser environment.</p>
<p>Node.js is like breaking the boundaries that restricted JavaScript to a limited area and unleashing its true potential. JavaScript was originally confined to running inside web browsers, limiting its capabilities to enhancing website interactivity.</p>
<p>But with the introduction of Node.js, JavaScript can now operate outside of those boundaries and perform tasks beyond the <a target="_blank" href="https://javascript.info/browser-environment">browser environment</a>.</p>
<p>Let's Understand this using a Real life example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689247879076/5d93a4a7-aa1e-4ad7-9ea5-64710585699d.webp" alt="What is Node js? - Restaurant Analogy" class="image--center mx-auto" /></p>
<p>Imagine you're a chef working in a small restaurant. Your main job is to prepare delicious dishes for the customers.</p>
<p>However, you're only allowed to work within the confines of the restaurant's kitchen, using the ingredients and tools available inside. This limits your ability to source new ingredients from different places or collaborate with other talented chefs.</p>
<p>Now, imagine if someone came along and removed those limitations. Suddenly, you have the freedom to step outside the restaurant, explore different markets to find unique ingredients and connect with other chefs to exchange ideas and techniques.</p>
<p>This newfound freedom allows you to unleash your full potential and create extraordinary culinary experiences.</p>
<p>In this analogy, the restaurant represents the web browser, and you, the chef, represent JavaScript. Introducing Node.js is like stepping out of the restaurant, breaking free from the limitations, and expanding the possibilities of what JavaScript can do.</p>
<p>Node.js has set JavaScript free from the confines of the browser, breaking it out of its cage and unleashing its power for <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/First_steps/Introduction">server-side development</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689247934965/82ae9c6b-f23a-4924-b1c8-568762171e21.webp" alt="Node.js has set JavaScript free from the confines of the browser, breaking it out of its cage and unleashing its power for server-side development." class="image--center mx-auto" /></p>
<p>It empowers developers to use JavaScript not just in the browser, but also on servers, enabling them to build powerful web applications, real-time chat apps, data-intensive systems, and more.</p>
<p>Node.js opens up a whole new world of opportunities for JavaScript, making it a versatile and powerful language that can be used across different domains. It revolutionizes web development by providing a platform where JavaScript can flourish beyond the browser and fulfill its true potential.</p>
<h2 id="heading-how-does-nodejs-work">How Does Node.js Work?</h2>
<p>To understand how Node.js works, let's continue with our restaurant analogy. Now that you, as the chef, have stepped outside the restaurant and embraced the newfound freedom, let's see how you can make the most of it.</p>
<p>In the traditional cooking process, you would follow a sequential approach. You would prepare one dish at a time, waiting for each dish to cook before moving on to the next. This sequential process can be time-consuming and inefficient, especially if you have multiple dishes to prepare.</p>
<p>But with Node.js, things work differently. As the liberated chef, you can now multitask and work on multiple dishes simultaneously. You can start preparing one dish while another is already cooking, and perhaps brainstorm new recipes for future creations.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689247976981/9dad1951-5113-40e2-980e-ebc808407987.webp" alt="Node can multitask and work on multiple work simultaneously" class="image--center mx-auto" /></p>
<p>You are no longer bound by a strict sequence; instead, you can efficiently manage your time and resources to accomplish more.</p>
<p>Similarly, Node.js operates on a non-blocking, event-driven model. It can handle multiple tasks <a target="_blank" href="https://hackernoon.com/how-does-nodejs-achieve-concurrency">concurrently</a> without getting stuck waiting for one task to complete before moving on to the next.</p>
<p>This non-blocking nature allows Node.js to make the most of available resources and deliver high performance.</p>
<p>In technical terms, Node.js uses an <a target="_blank" href="https://www.freecodecamp.org/news/nodejs-eventloop-tutorial/">event loop</a>, which is like a central dispatcher that listens for events and triggers corresponding actions. It allows Node.js to efficiently handle multiple requests and perform tasks asynchronously.</p>
<p>This means that Node.js can start processing a request, such as fetching data from a database or making an <a target="_blank" href="https://en.wikipedia.org/wiki/API">API</a> call, and while waiting for the response, it can handle other requests, ensuring that the server remains responsive and productive.</p>
<p>It can handle a large number of concurrent connections and perform data-intensive operations without compromising performance.</p>
<h2 id="heading-key-features-of-nodejs">Key Features of Node.js</h2>
<p>Node.js comes with a set of powerful features that make it a popular choice for building web applications.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689248011533/e2b3ba0b-61ea-427c-b16d-2e8e6dc137a6.webp" alt="Key Features of Node.js" class="image--center mx-auto" /></p>
<p>These unique features make Node.js a powerful and popular choice for building scalable, high-performance web applications. By leveraging these capabilities, developers can create efficient, real-time, and data-intensive applications that meet the demands of modern web development.</p>
<p>Let's explore some of its key features:</p>
<h3 id="heading-asynchronous-and-non-blocking">Asynchronous and Non-Blocking</h3>
<p>Node.js follows an <a target="_blank" href="https://www.techtarget.com/searchnetworking/definition/asynchronous#:~:text=In%20general%2C%20asynchronous%20%2D%2D%20pronounced,are%20not%20coordinated%20in%20time.">asynchronous</a> and non-blocking programming model. This means it can handle multiple tasks simultaneously without waiting for each task to complete before moving on to the next one.</p>
<p>It's like a multitasking magician that can juggle multiple requests and operations efficiently. Let's switch gears to our restaurant analogy.</p>
<p>As we discussed before, in a traditional synchronous model, the chef would have to wait for each dish to finish cooking before starting the next one.</p>
<p>It's like a chef working alone in the kitchen, carefully monitoring each dish as it cooks, and only moving on to the next one once the previous dish is done.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687237676327/952f9cd2-1a09-4ab5-8548-3b861848193f.webp" alt="synchronous model, the chef would have to wait for each dish to finish cooking before starting the next one" class="image--center mx-auto" /></p>
<p>But with Node.js, it's like having a highly skilled chef who can multitask effortlessly.</p>
<p>Imagine the chef utilizing specialized tools and equipment that handle time-consuming tasks like cooking the food.</p>
<p>While the food is simmering on the stove or baking in the oven, the chef can efficiently work on preparing other dishes simultaneously.</p>
<p>This parallel processing capability of Node.js frees the chef from the constraints of waiting for each dish to finish cooking before starting the next one.</p>
<p>It's like having an assistant chef or an automated cooking system that takes care of the time-consuming tasks, allowing the chef to focus on other aspects of food preparation.</p>
<p>The analogy of a chef using tools or automated systems to handle time-consuming tasks in the kitchen represents how Node.js leverages <a target="_blank" href="https://www.codecentric.de/wissens-hub/blog/explain-non-blocking-i-o-like-im-five">non-blocking I/O</a> and event-driven architecture to maximize efficiency in web development.</p>
<p>By efficiently managing resources and handling multiple tasks concurrently, Node.js enables faster and more responsive applications, enhancing the overall user experience.</p>
<h3 id="heading-event-driven-architecture">Event Driven Architecture</h3>
<p>Node.js utilizes an event-driven architecture, which means it listens for events and responds to them asynchronously. <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events">Events</a> can be triggered by various actions, such as user interactions, <a target="_blank" href="https://javascript.info/network">network requests</a>, or <a target="_blank" href="https://nodejs.org/api/fs.html">file system operations</a>.</p>
<p>When an event occurs, Node.js responds by executing the associated <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">callback function</a>, allowing the application to continue handling other tasks in the meantime.</p>
<p>In Restaurant Analogy, It's like running a bustling restaurant with a highly skilled chef and a set of specialized tools and equipment.</p>
<p>In this scenario, Node.js acts as the chef, utilizing specialized tools and equipment that handle time-consuming tasks like cooking food. These tools not only assist in the cooking process but also have the ability to notify the chef when a specific task is completed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687239913537/cce86520-e734-4d90-aa0d-fe162a10da2e.webp" alt="Using Robot to Monitor Cooking" class="image--center mx-auto" /></p>
<p>Just like the chef relies on these tools, Node.js leverages an event loop that acts as the notification system. When Node.js initiates a task, it registers an event and continues to process other tasks without waiting.</p>
<p>Meanwhile, the event loop keeps an eye on these tasks and alerts Node.js when a specific task is finished, just like the specialized tools notify the chef.</p>
<p>This event-driven approach of Node.js allows it to efficiently handle numerous requests and operations simultaneously, similar to how the chef can multitask with the help of specialized tools. It frees Node.js from the constraints of waiting for each task to finish before moving on to the next one, resulting in faster response times and improved performance.</p>
<h3 id="heading-single-threaded-event-loop">Single-Threaded Event Loop</h3>
<p>In the world of web development, Node.js stands out with its single-threaded event loop architecture. This unique approach allows Node.js to handle concurrent requests efficiently, providing excellent performance and scalability.</p>
<p>Let's delve into this architecture using our restaurant analogy.</p>
<p>Imagine your restaurant has a talented and efficient chef who can effortlessly manage multiple orders. Instead of hiring additional chefs for each order, your chef excels at prioritizing tasks, delegating responsibilities, and ensuring the smooth progress of each order.</p>
<p>Similarly, Node.js maximizes resource utilization by efficiently handling multiple requests within a single thread.</p>
<p>Node.js's single-threaded event loop architecture eliminates the need for spawning multiple threads for each request, reducing memory consumption and eliminating the overhead of context switching.</p>
<p>It's like having your chef expertly juggling different orders in the kitchen, without the need for additional chefs.</p>
<p>Remember we discussed the event loop notifying when a specific task gets finished in a previous section?</p>
<p>Now, let's explore how this process happens.</p>
<p>When a request or operation is initiated, it is placed in a task queue, waiting to be processed. The event loop continuously checks this task queue and retrieves tasks one by one for execution.</p>
<p>As the event loop retrieves a task from the queue, it executes the associated callback function, which may involve performing I/O operations, accessing databases, or processing data. While waiting for these operations to complete, the event loop doesn't block and continues to check for new tasks in the queue.</p>
<p>Once an asynchronous operation is finished, the associated callback function is placed in the event loop's <a target="_blank" href="https://blog.logrocket.com/a-deep-dive-into-queues-in-node-js/">callback queue</a>. In the next iteration of the event loop, these callback functions are retrieved from the callback queue and executed.</p>
<p>This mechanism ensures that tasks are executed in the order they were added to the queue, maintaining the integrity of the application's logic.</p>
<p>This event-driven approach not only allows Node.js to efficiently manage concurrent tasks but also provides a way for the event loop to notify when a specific task finishes. When a callback function is placed in the callback queue, the event loop detects its presence and initiates its execution.</p>
<p>It's like your chef receiving a notification when a specific dish finishes cooking, prompting them to proceed with the next steps of food preparation.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687242230249/07aecfd3-7210-49cf-b8bc-dd02f0aa0c4b.webp" alt="Notification of Cooking finish" class="image--center mx-auto" /></p>
<p>By utilizing this architecture, Node.js optimizes performance and ensures responsiveness. The event loop, like your chef's management skills, efficiently schedules considering priority and executes tasks, allowing Node.js to handle a large number of concurrent requests seamlessly.</p>
<h3 id="heading-cross-platform-compatibility">Cross Platform Compatibility</h3>
<p>Node.js is built to run on multiple platforms, ensuring compatibility across different <a target="_blank" href="https://en.wikipedia.org/wiki/Operating_system">operating systems</a> such as <a target="_blank" href="https://en.wikipedia.org/wiki/Microsoft_Windows">Windows</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/MacOS">macOS</a>, and <a target="_blank" href="https://en.wikipedia.org/wiki/Linux">Linux</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687270513205/f99e2af1-f2e0-48e4-971c-04c72a1696ac.webp" alt="Node js has Cross Platform Compatibility" class="image--center mx-auto" /></p>
<p>This cross-platform support enables developers to create applications that can seamlessly run on various environments.</p>
<p>Imagine having a versatile restaurant that can cater to customers from different locations and backgrounds. Regardless of whether your customers prefer different cuisines or have diverse dietary preferences, your restaurant is adaptable and capable of meeting their needs.</p>
<p>Similarly, Node.js's cross-platform compatibility allows developers to reach a wider audience and ensure their applications can be deployed and used across different operating systems.</p>
<p>Node.js's ability to run consistently across platforms simplifies development, deployment, and maintenance efforts, as developers can focus on building the application logic without worrying about the underlying operating system.</p>
<p>It provides a unified environment for developers to create robust and reliable applications that can be deployed seamlessly on various platforms.</p>
<p>With Node.js's cross-platform compatibility, developers can leverage its power and flexibility to build applications that can reach users across different devices and operating systems, expanding their potential user base and enhancing the accessibility of their software solutions.</p>
<h3 id="heading-extensive-module-library-npm">Extensive Module Library (<code>npm</code>)</h3>
<p>Node.js comes with a powerful module library called <a target="_blank" href="https://www.npmjs.com/"><code>npm</code></a> (Node Package Manager), offering a vast collection of pre-built modules and packages.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687270566717/d437df89-0c23-4d02-98e1-f43d21e1dab1.webp" alt="Extensive Module Library (npm)" class="image--center mx-auto" /></p>
<p>These modules cover a wide range of functionalities and can be seamlessly integrated into Node.js applications, saving developers valuable time and effort.</p>
<p>Imagine having a comprehensive recipe book in your restaurant kitchen, filled with a diverse selection of recipes for various specialties and techniques. This recipe book serves as a valuable resource, allowing you to enhance your culinary creations and experiment with new flavors.</p>
<p>In a similar manner, the npm module library empowers developers by providing a rich repository of ready-to-use modules that can be incorporated into their Node.js applications.</p>
<p>With npm, developers can easily search for and install modules tailored to their specific needs, whether it's for database connectivity, web frameworks, authentication, data processing, or any other functionality required for their application.</p>
<p>These modules have been developed and shared by a thriving community of developers, ensuring their reliability and usefulness.</p>
<p>By leveraging the npm module library, developers can significantly expedite the development process, as they don't have to reinvent the wheel for every functionality they require. They can rely on the existing modules, benefiting from the expertise and contributions of the wider Node.js community.</p>
<p>Furthermore, npm provides version management, allowing developers to easily update or switch between different module versions to meet the evolving needs of their applications. This ensures compatibility and provides a streamlined workflow for maintaining and managing dependencies.</p>
<h2 id="heading-benefits-of-nodejs">Benefits of Node.js</h2>
<p>Node.js offers several compelling benefits that make it a preferred choice for web development.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1689248065982/98e31862-11cd-4608-8c91-21074464d502.webp" alt="Benefits of Node.js" class="image--center mx-auto" /></p>
<p>Let's explore some of the key Benefits of using Node.js:</p>
<h3 id="heading-improved-efficiency-and-leverage-javascript-expertise">Improved Efficiency and leverage JavaScript expertise</h3>
<p>Node.js offers enhanced development efficiency and leverages JavaScript expertise. It streamlines the development process by enabling developers to utilize JavaScript on both the client and server sides of a web application.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687270656258/39c1192d-829a-4ef1-9083-c540c9111e84.webp" alt="Improved Efficiency and leverage JavaScript expertise" class="image--center mx-auto" /></p>
<p>This unified language approach eliminates the need to switch between different programming languages or frameworks, improving overall efficiency.</p>
<p>Just like a versatile set of tools in a restaurant kitchen that can handle various cooking techniques, Node.js empowers developers to work more efficiently and effectively.</p>
<p>By leveraging the same JavaScript language for both client-side and server-side development tasks, Node.js simplifies the development process. Developers can write code using JavaScript for the front-end user interface and back-end server logic, leveraging their existing JavaScript skills.</p>
<p>This unified approach reduces the learning curve and allows developers to reuse code, shared <a target="_blank" href="https://en.wikipedia.org/wiki/List_of_JavaScript_libraries">libraries</a>, and their JavaScript knowledge across the entire application.</p>
<p>With Node.js, developers seamlessly transition between client-side and server-side programming, accessing a consistent set of tools, libraries, and <a target="_blank" href="https://en.wikipedia.org/wiki/Comparison_of_JavaScript-based_web_frameworks">frameworks</a>. This eliminates the need to learn a new language or framework for server-side development, saving time and effort.</p>
<p>It's like having an experienced chef in a restaurant who is already familiar with the tools and techniques, making the introduction of new dishes or menu expansion easier and more efficient.</p>
<p>Furthermore, The ability to leverage existing JavaScript skills and reuse code not only reduces the learning curve but also increases productivity. Developers can quickly build upon their existing knowledge and focus on learning the specific features and capabilities of Node.js.</p>
<p>It's similar to experienced chefs who can adapt to new recipes and techniques effortlessly, allowing the introduction of a wider variety of delicious dishes to customers.</p>
<p>With Node.js and its compatibility with JavaScript, developers can leverage their existing skills and knowledge to build efficient and scalable server-side applications.</p>
<p>This combination of enhanced development efficiency and JavaScript expertise empowers developers to streamline the development process, deliver high-quality web applications, and create exceptional digital experiences for users.</p>
<h3 id="heading-node-js-provides-enhanced-performance">Node js Provides Enhanced Performance</h3>
<p>Node.js is renowned for its exceptional performance and scalability. Its event-driven, non-blocking I/O model enables it to handle numerous concurrent connections efficiently, minimizing resource wastage.</p>
<p>This results in accelerated response times, enhanced throughput, and superior overall performance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687270715493/14395fa2-4b3b-4989-a5f8-93924c049137.webp" alt class="image--center mx-auto" /></p>
<p>Imagine having an efficient system in your restaurant that can handle a large number of customers swiftly and seamlessly. Every order is processed promptly, ensuring that all customers receive their meals without enduring lengthy waiting times.</p>
<p>This efficiency optimizes customer satisfaction and allows your restaurant to serve a greater volume of patrons. Similarly, Node.js excels at managing multiple concurrent connections without blocking or slowing down the application. Its event-driven architecture listens for events and responds to them asynchronously.</p>
<p>This means that while one connection is waiting for a response, Node.js can swiftly move on to handle other incoming requests. It's like having a team of highly skilled and dedicated staff members in your restaurant who work diligently to fulfill customer orders without any delays.</p>
<p>By efficiently handling concurrent connections and events, Node.js maximizes resource utilization and ensures that your application remains highly responsive.</p>
<p>This is especially crucial in scenarios where real-time interactions or data-intensive operations are involved.</p>
<p>Node.js's performance capabilities make it an ideal choice for building scalable applications that can effortlessly handle a large number of users or process significant amounts of data.</p>
<h3 id="heading-real-time-applications">Real Time Applications</h3>
<p>Node.js is exceptionally well-suited for developing real-time applications, ranging from interactive menus to collaborative order tracking systems. Its event-driven architecture and built-in support for <a target="_blank" href="https://ably.com/blog/web-app-websockets-nodejs">WebSockets</a> facilitate seamless communication and instantaneous updates between clients and servers.</p>
<p>Imagine a system in your restaurant where customers can place their orders and receive live updates as their orders are prepared and served. Node.js enables a similar experience in the digital realm.</p>
<p>It's like having a dynamic platform in your restaurant where customers can interact with your staff, provide instructions, and receive real-time updates on their orders.</p>
<p>With Node.js, you can establish persistent connections between clients and servers, enabling bidirectional communication. This means that data can be sent and received instantly, allowing for real-time collaboration and interaction.</p>
<p>It's like having a dedicated communication channel between your restaurant and your customers, ensuring a smooth and interactive dining experience.</p>
<p>The event-driven nature of Node.js plays a crucial role in enabling real-time functionality. When a client initiates an action, such as placing an order or requesting a menu update, Node.js responds promptly by triggering the appropriate event and delivering the corresponding updates to all relevant clients.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687270869212/6aa4dca8-d3e9-437a-9d3c-182025ffa115.webp" alt="Real Time Applications" class="image--center mx-auto" /></p>
<p>It's like having an attentive team in your restaurant who immediately responds to customer requests and ensures that everyone stays informed about the progress of their orders.</p>
<p>Additionally, Node.js provides native support for WebSockets, a communication protocol that enables persistent, full-duplex communication between clients and servers over a single connection.</p>
<p>This allows for efficient and low-latency data transmission, facilitating real-time updates without the need for frequent refreshing. It's like having a streamlined and efficient order management system in your restaurant that keeps customers updated in real time.</p>
<p>Whether you're building a reservation system where customers can book tables and receive instant confirmations or a collaborative tool where multiple users can contribute to a shared menu in real time, Node.js empowers you to create highly interactive and responsive experiences.</p>
<p>It's like having a cutting-edge digital infrastructure in your restaurant that enables seamless communication and collaboration among customers and staff.</p>
<h3 id="heading-node-js-provides-scalability">Node js Provides Scalability</h3>
<p>Node.js's ability to handle a large number of concurrent connections makes it highly <a target="_blank" href="https://www.freecodecamp.org/news/scaling-node-js-applications-8492bd8afadc/">scalable</a>. It excels at efficiently managing resources and leveraging asynchronous operations, allowing it to handle increased workloads without compromising performance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687270919825/00beb4fc-b665-4e33-bc7f-e62bcb7bf2a7.webp" alt="Node js Provides Scalability" class="image--center mx-auto" /></p>
<p>Imagine a bustling restaurant during peak hours, where numerous customers place their orders simultaneously. Node.js enables similar scalability in the digital realm.</p>
<p>It's like having a flexible and expandable system in your restaurant that can seamlessly accommodate a growing number of customers and ensure that everyone is served promptly.</p>
<p>The non-blocking, event-driven architecture of Node.js is One of the key strengths which we discussed earlier section.</p>
<p>With this architecture, Node.js can effectively manage a large number of concurrent connections. It avoids the bottleneck of traditional blocking I/O, where each operation would need to wait for the previous one to complete, by allowing operations to be executed concurrently and independently.</p>
<p>Node.js optimizes resource utilization by employing the single-threaded event loop architecture. Instead of spawning a new thread for each connection, it leverages a single thread to handle multiple connections, reducing memory consumption and eliminating the overhead of context switching.</p>
<p>The scalability of Node.js is also enhanced by its ecosystem of modules and tools specifically designed for building scalable applications. These modules provide features like <a target="_blank" href="https://nodejs.org/api/cluster.html">clustering</a>, <a target="_blank" href="https://javascript.plainenglish.io/building-a-load-balancer-using-node-js-express-a947b7d27a39">load balancing</a>, and <a target="_blank" href="https://temporal.io/blog/building-reliable-distributed-systems-in-node">distributed computing</a>, enabling you to scale your application across multiple processes or even multiple servers.</p>
<p>It's like having a network of interconnected restaurants that collaborate to meet the demands of a large number of customers.</p>
<p>Whether you're running a small restaurant with a few tables or a large establishment with high customer traffic, Node.js empowers you to scale your digital infrastructure to match the needs of your business.</p>
<p>It's like having a responsive and adaptable system in your restaurant that grows with your customer base and ensures a seamless dining experience for everyone.</p>
<h3 id="heading-node-js-has-active-and-supportive-community">Node js has Active and Supportive Community</h3>
<p>Node.js benefits from a vibrant and active community of developers who contribute to its growth and offer valuable resources, tutorials, and support.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1687270997822/75c2ba96-3202-41c9-b49d-5ddcda5b5a75.webp" alt="Node js has Active and Supportive Community" class="image--center mx-auto" /></p>
<p>This community acts as a valuable asset, providing a wealth of knowledge and expertise that makes it easier to learn and troubleshoot Node.js applications.</p>
<p>Imagine having a group of experienced chefs in your restaurant who are always there to offer guidance and share their expertise. They can help you improve your recipes, suggest new techniques, and troubleshoot any challenges you may encounter.</p>
<p>Similarly, the Node.js community serves as a supportive and knowledgeable group of individuals who are passionate about the technology and eager to help others succeed.</p>
<p>The Node.js community has created an extensive range of resources, including documentation, tutorials, forums, and online communities. These resources serve as a valuable knowledge base, helping developers learn Node.js and discover best practices.</p>
<p>It's like having access to a comprehensive library of cookbooks, recipe collections, and forums where you can exchange ideas with other chefs.</p>
<p>Furthermore, the community actively contributes to the development of Node.js by creating and maintaining open-source modules and libraries. These modules can be easily integrated into your projects, saving development time and effort.</p>
<p>It's like having a network of talented chefs who share their innovative recipes and techniques with you, allowing you to enhance your restaurant's offerings without starting from scratch.</p>
<p>The collaborative nature of the Node.js community also ensures that the technology stays up to date with the latest trends and developments. The community actively discusses new features, shares insights, and provides feedback, leading to continuous improvements in Node.js.</p>
<p>It's like being part of a culinary association or guild, where chefs come together to exchange ideas, learn from each other, and push the boundaries of their craft.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, Node.js is a game-changer in web development. It allows JavaScript to break free from web browsers and enables the creation of dynamic and interactive web applications.</p>
<p>Just like a restaurant empowers its chef with freedom, Node.js gives JavaScript more freedom to do things it couldn't do before. It simplifies development by using a single language, JavaScript, for both the client and server sides.</p>
<p>Node.js excels at handling multiple tasks simultaneously, making applications highly scalable. It also benefits from a vast library of pre-built modules, saving developers time and effort.</p>
<p>Node.js has revolutionized the way JavaScript operates, making the web more dynamic and flavorful. It's a popular choice for building modern web applications.</p>
<p>So, next time you dine at a restaurant, remember how Node.js has empowered JavaScript to venture beyond its traditional confines, making the web a more exciting place.</p>
]]></content:encoded></item><item><title><![CDATA[How to Split a Number into an Array in JavaScript]]></title><description><![CDATA[Introduction
There are scenarios where you might need to split a number into its digits and store them in an array When working with numbers in JavaScript. This can be useful for tasks such as performing mathematical operations on each digit or manip...]]></description><link>https://robiul.dev/how-to-split-a-number-into-an-array-in-javascript</link><guid isPermaLink="true">https://robiul.dev/how-to-split-a-number-into-an-array-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[tips and tricks]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Fri, 16 Jun 2023 04:40:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1686838271650/a0bb8c5d-48ba-47e2-98aa-bfc62432a2fa.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>There are scenarios where you might need to split a number into its digits and store them in an array When working with numbers in JavaScript. This can be useful for tasks such as performing mathematical operations on each digit or manipulating the digits individually.</p>
<p>In this article, we will delve into various techniques for splitting a number into an array of digits using JavaScript. We will not only cover the fundamental approaches but also address important considerations such as handling negative numbers and float numbers.</p>
<p>By the end of this article, you will gain a comprehensive understanding of how to extract and organize the digits of a number effectively. Whether you're working with integers or float numbers, this article will equip you with the necessary knowledge and techniques to accomplish the task efficiently.</p>
<p>So, Let's get started!</p>
<h2 id="heading-different-ways-to-split-numbers-into-arrays">Different Ways to split numbers into Arrays</h2>
<p>In the context of splitting numbers, there are two main approaches that we will explore in this article:</p>
<ul>
<li><p>Using string conversion</p>
</li>
<li><p>Using math operations.</p>
</li>
</ul>
<p>These approaches offer different ways to extract individual digits from a number and store them in an array.</p>
<p>By leveraging string conversion, we can convert the number into a string and iterate over its characters.</p>
<p>On the other hand, using math operations allows us to perform calculations to extract the digits.</p>
<p>Both approaches have their advantages and are suited for different scenarios.</p>
<p>Let's delve into each approach and explore its implementation in detail.</p>
<h2 id="heading-splitting-a-number-using-string-conversion">Splitting a Number Using String Conversion</h2>
<p>The most straightforward approach to splitting a number into an array is by converting it to a string and then iterating over each character to extract the digits.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686883927843/41a3924b-8c73-4610-b71c-135c7a12930c.webp" alt="Splitting a Number Using String Conversion" class="image--center mx-auto" /></p>
<p>This technique involves converting the number to a string representation using methods like <a target="_blank" href="https://www.w3schools.com/jsref/jsref_tostring_string.asp#:~:text=The%20toString()%20method%20is,it%20in%20your%20own%20code."><code>toString()</code></a> or the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/String"><code>String()</code></a> constructor. Once the number is converted to a string, we can access each character and extract the desired digits.</p>
<p>There are multiple techniques available to do that,</p>
<p>Let's explore some of these techniques to gain a better understanding of how to split a number into an array using string conversion.</p>
<h3 id="heading-split-number-using-for-loop">Split Number Using <code>for loop</code></h3>
<p>We can use a <a target="_blank" href="https://www.freecodecamp.org/news/javascript-for-loops/"><code>for loop</code></a> to iterate over each digit of the number and add it to an array after converting the number to a string.</p>
<p>Here's an example that demonstrates the usage of a for loop to split a number into an array:</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">splitNumberUsingForLoop</span>(<span class="hljs-params">number</span>) </span>{
   <span class="hljs-keyword">const</span> digits = [];
   <span class="hljs-keyword">const</span> numberString = number.toString(); <span class="hljs-comment">// Convert the number to a string</span>

   <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; numberString.length; i++) {
     <span class="hljs-keyword">const</span> digit = <span class="hljs-built_in">parseInt</span>(numberString[i]); <span class="hljs-comment">// Convert each character back to a number</span>
     digits.push(digit); <span class="hljs-comment">// Add the digit to the end of the array</span>
   }

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

 <span class="hljs-keyword">const</span> number = <span class="hljs-number">12345</span>;
 <span class="hljs-keyword">const</span> digits = splitNumberUsingForLoop(number);
 <span class="hljs-built_in">console</span>.log(digits); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
</code></pre>
<p>In the example above, we define a function called <code>splitNumberUsingForLoop</code> that takes a number as input. Inside the function, we initialize an empty array called digits to store the individual digits of the number. We convert the number to a string using the <code>toString()</code> method.</p>
<p>Next, we use a for loop to iterate over each character in the <code>numberString</code>. We convert each character back to a number using <a target="_blank" href="https://www.scaler.com/topics/parseint-in-javascript/"><code>parseInt()</code></a> and then push it to the digits array using the <a target="_blank" href="https://www.javascripttutorial.net/javascript-array-push/"><code>push()</code></a> method.</p>
<p>After the loop finishes, we return the digits array, which contains all the individual digits of the number.</p>
<p>Using a for loop gives us control over the iteration process and allows us to handle each digit individually. It provides flexibility in case we need to perform additional operations or validations during the iteration.</p>
<h3 id="heading-split-number-using-split-method">Split Number Using <code>split()</code> Method</h3>
<p>Another way to split a number into an array of digits in the string conversion approach is by using the <a target="_blank" href="https://www.javascripttutorial.net/javascript-string-split/"><code>split()</code></a> method after converting the number to a string.</p>
<p>Here's an example that demonstrates the usage of the split() method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> number = <span class="hljs-number">12345</span>;
<span class="hljs-keyword">const</span> numberString = number.toString(); <span class="hljs-comment">// Convert the number to a string</span>
<span class="hljs-keyword">const</span> digits = numberString.split(<span class="hljs-string">""</span>); <span class="hljs-comment">// Split the string into an array of individual characters</span>

<span class="hljs-built_in">console</span>.log(digits); <span class="hljs-comment">// ["1", "2", "3", "4", "5"]</span>
</code></pre>
<p>In the example above, we convert the number to a string using the <code>toString()</code> method. Then, we call the <code>split("")</code> method on the resulting string, passing an empty string as the separator. This splits the string into an array of individual characters, which represent the digits of the number.</p>
<p>By using the <code>split()</code> method, we can easily obtain an array of digits from a number. This approach is straightforward and can be useful when you specifically need the digit values as strings.</p>
<h3 id="heading-split-number-using-spread-operator">Split Number Using Spread Operator</h3>
<p>Another way to split a number into an array of digits is by using the <a target="_blank" href="https://medium.com/coding-at-dawn/how-to-use-the-spread-operator-in-javascript-b9e4a8b06fab">spread operator</a> after converting the number to a string. The spread operator allows us to spread the characters of a string into individual elements of an array.</p>
<p>Here's an example that demonstrates the usage of the spread operator:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> number = <span class="hljs-number">12345</span>;
<span class="hljs-keyword">const</span> numberString = number.toString(); <span class="hljs-comment">// Convert the number to a string</span>
<span class="hljs-keyword">const</span> digits = [...numberString]; <span class="hljs-comment">// Spread the characters of the string into an array</span>

<span class="hljs-built_in">console</span>.log(digits); <span class="hljs-comment">// ["1", "2", "3", "4", "5"]</span>
</code></pre>
<p>In the example above, we convert the number to a string using the <code>toString()</code> method. Then, by using the spread operator [<code>...</code>], we spread the characters of the string into individual elements of an array. This results in an array where each element represents a digit of the number.</p>
<p>Using the spread operator provides a concise and readable way to split a number into an array of digits. It is particularly useful when you need to work with the digit values as strings and want to avoid using the <code>split()</code> method.</p>
<h3 id="heading-split-number-using-reduce-or-map-method">Split Number Using <code>reduce()</code> or <code>map()</code> method</h3>
<p>As you can see When using the <code>.split()</code> method or spread operator to split a number into an array of digits, the resulting array will contain string values as the elements.</p>
<p>However, if you prefer the elements to be numbers instead of strings, you can combine this approach with the <a target="_blank" href="https://www.freecodecamp.org/news/reduce-f47a7da511a9/"><code>.reduce()</code></a> or <a target="_blank" href="https://www.freecodecamp.org/news/javascript-map-how-to-use-the-js-map-function-array-method/"><code>.map()</code></a> method.</p>
<p>Here's an example using the <code>.reduce()</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> number = <span class="hljs-number">12345</span>;
<span class="hljs-keyword">const</span> numberString = number.toString(); <span class="hljs-comment">// Convert the number to a string</span>
<span class="hljs-keyword">const</span> digits = numberString.split(<span class="hljs-string">''</span>).reduce(<span class="hljs-function">(<span class="hljs-params">acc, curr</span>) =&gt;</span> {
  acc.push(<span class="hljs-built_in">parseInt</span>(curr)); <span class="hljs-comment">// Convert each character back to a number</span>
  <span class="hljs-keyword">return</span> acc;
}, []);

<span class="hljs-built_in">console</span>.log(digits); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
</code></pre>
<p>In this example, we first convert the number to a string using the <code>.toString()</code> method. Then, we split the string into an array of individual characters using <code>.split('')</code>.</p>
<p>By applying the <code>.reduce()</code> method, we iterate over each character and use <code>parseInt()</code> to convert it back to a number. The resulting array contain the number values instead of strings.</p>
<p>Similarly, you can achieve the same result using the <code>.map()</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> number = <span class="hljs-number">12345</span>;
<span class="hljs-keyword">const</span> numberString = number.toString(); <span class="hljs-comment">// Convert the number to a string</span>
<span class="hljs-keyword">const</span> digits = [...numberString].map(<span class="hljs-function">(<span class="hljs-params">digit</span>) =&gt;</span> <span class="hljs-built_in">parseInt</span>(digit));

<span class="hljs-built_in">console</span>.log(digits); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
</code></pre>
<p>In this example, we convert the number to a string using the <code>.toString()</code> method. Then, by using the spread operator, we convert the string into an array of individual characters.</p>
<p>Finally, we apply the <code>.map()</code> method to iterate over each character and use <code>parseInt()</code> to convert it back to a number. The resulting array contains the number values extracted from the original number.</p>
<h3 id="heading-split-number-using-arrayfrom-method">Split Number Using Array.from() Method</h3>
<p>We can use <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from"><code>Array.from()</code></a> method to do that, This method creates a new array instance from an array-like or iterable object, allowing us to generate an array of digits from a number. To split a number using the <code>Array.from()</code> method, we pass the string as the first argument to <code>Array.from()</code> after converting the number to a string.</p>
<p>Additionally, we can provide a mapping function as the second argument to convert each character to a numeric digit.</p>
<p>Here's an example that demonstrates the usage of the <code>Array.from()</code> method:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> number = <span class="hljs-number">12345</span>;
<span class="hljs-keyword">const</span> numberString = number.toString(); <span class="hljs-comment">// Convert the number to a string</span>
<span class="hljs-keyword">const</span> digits = <span class="hljs-built_in">Array</span>.from(numberString, <span class="hljs-built_in">Number</span>); <span class="hljs-comment">// Create an array of digits</span>

<span class="hljs-built_in">console</span>.log(digits); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
</code></pre>
<p>In the example above, we convert the number to a string using the <code>toString()</code> method. Then, we pass the string and the Number function as arguments to <code>Array.from()</code>. The Number function is used as a mapping function to convert each character of the string to a numeric digit.</p>
<p>Using the <code>Array.from()</code> method provides a flexible approach to splitting a number into an array of digits. It allows us to customize the mapping function if needed and provides a clean and concise solution for the task.</p>
<h2 id="heading-splitting-a-number-using-math-operations">Splitting a Number Using Math Operations</h2>
<p>Another approach to splitting a number is by Using Math Operations which involves using mathematical operations such as modulus and division.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686883979391/233c88ea-f65b-4ef9-81e7-af1e2ebb1ecc.webp" alt="Splitting a Number Using Math Operations" class="image--center mx-auto" /></p>
<p>By leveraging the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder">Remainder or modulus operator</a> (<code>%</code>) and division, we can isolate each digit and add it to an array. This method is more suitable when you require precise numeric calculations along with digit extraction.</p>
<p>There are several ways to implement this approach.</p>
<p>Let's explore the most popular two of them:</p>
<h3 id="heading-split-number-using-while-loop">Split Number Using <code>while Loop</code></h3>
<p>One way to split a number using math operations is by utilizing a <a target="_blank" href="https://www.w3schools.com/js/js_loop_while.asp"><code>while loop</code></a>.</p>
<p>Here's an example implementation:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">splitNumberUsingWhileLoop</span>(<span class="hljs-params">number</span>) </span>{
  <span class="hljs-keyword">const</span> digits = [];
  <span class="hljs-keyword">let</span> tempNumber = number;

  <span class="hljs-keyword">while</span> (tempNumber &gt; <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">const</span> digit = tempNumber % <span class="hljs-number">10</span>;
    digits.unshift(digit);
    tempNumber = <span class="hljs-built_in">Math</span>.floor(tempNumber / <span class="hljs-number">10</span>);
  }

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

<span class="hljs-keyword">const</span> number = <span class="hljs-number">12345</span>;
<span class="hljs-keyword">const</span> digits = splitNumberUsingWhileLoop(number);
<span class="hljs-built_in">console</span>.log(digits); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
</code></pre>
<p>In this implementation, we start with an empty digits array. The <code>tempNumber</code> variable is initialized with the input number. The <code>while loop</code> runs as long as <code>tempNumber</code> is greater than <code>0</code>. In each iteration, we extract the last digit of tempNumber using the modulus operator (<code>%</code>) and add it to the beginning of the digits array using the <code>unshift()</code> method.</p>
<p>Then, we update <code>tempNumber</code> by dividing it by 10 and using <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor"><code>Math.floor()</code></a> to remove the last digit. This process continues until <code>tempNumber</code> becomes <code>0</code>, indicating that all digits have been extracted. Finally, we return the <code>digits</code> array.</p>
<h3 id="heading-split-number-using-recursion">Split Number Using Recursion</h3>
<p>Recursion is another way to split a number using math operations. It involves breaking down a number into its digits by utilizing a recursive function. Each recursive call processes a portion of the number, gradually extracting the digits until the base case is reached.</p>
<p>Here's an example implementation:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">splitNumberRecursive</span>(<span class="hljs-params">number</span>) </span>{
  <span class="hljs-keyword">if</span> (number &lt; <span class="hljs-number">10</span>) {
    <span class="hljs-keyword">return</span> [number]; <span class="hljs-comment">// Base case: return the single digit</span>
  }

  <span class="hljs-keyword">const</span> lastDigit = number % <span class="hljs-number">10</span>; <span class="hljs-comment">// Extract the last digit</span>
  <span class="hljs-keyword">const</span> remainingNumber = <span class="hljs-built_in">Math</span>.floor(number / <span class="hljs-number">10</span>); <span class="hljs-comment">// Remove the last digit</span>

  <span class="hljs-keyword">return</span> [...splitNumberRecursive(remainingNumber), lastDigit]; <span class="hljs-comment">// Concatenate the recursive result with the last digit</span>
}

<span class="hljs-keyword">const</span> number = <span class="hljs-number">12345</span>;
<span class="hljs-keyword">const</span> digits = splitNumberRecursive(number);
<span class="hljs-built_in">console</span>.log(digits); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>
</code></pre>
<p>In this recursive implementation, the function checks if the number is less than <code>10</code>, which indicates that we have reached the base case of a single digit. If the base case is met, the function returns an array containing that single digit.</p>
<p>Otherwise, it extracts the last digit using the modulus operator (<code>%</code>) and removes the last digit using division and <code>Math.floor()</code>. The function then recursively calls itself with the remaining number and concatenates the recursive result with the last digit.</p>
<h2 id="heading-handling-negative-numbers">Handling Negative Numbers</h2>
<p>So far we have discussed different approaches for splitting a number but Handling negative numbers when splitting them requires special attention to ensure accurate results. If we don't handle negative numbers separately, it can introduce complexity into our code.</p>
<p>Let's explore how we can handle negative numbers:</p>
<h3 id="heading-handling-negative-numbers-in-string-conversion">Handling Negative Numbers in String Conversion</h3>
<p>When using string conversion to split numbers, we can incorporate handling for negative numbers during the conversion process.</p>
<p>Here's the updated code that considers negative numbers in for loop approach that we talked about earlier:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">splitNumberUsingForLoop</span>(<span class="hljs-params">number</span>) </span>{
  <span class="hljs-keyword">const</span> digits = [];
  <span class="hljs-keyword">const</span> numberString = <span class="hljs-built_in">Math</span>.abs(number).toString(); <span class="hljs-comment">// Convert the absolute value of the number to a string</span>

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; numberString.length; i++) {
    <span class="hljs-keyword">const</span> digit = <span class="hljs-built_in">parseInt</span>(numberString[i]); <span class="hljs-comment">// Convert each character back to a number</span>
    digits.push(digit); <span class="hljs-comment">// Add the digit to the end of the array</span>
  }

  <span class="hljs-keyword">if</span> (number &lt; <span class="hljs-number">0</span>) {
    digits[<span class="hljs-number">0</span>] = -digits[<span class="hljs-number">0</span>]; <span class="hljs-comment">// Modify the first digit to include the negative sign</span>
  }

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

<span class="hljs-keyword">const</span> number = <span class="hljs-number">-12345</span>;
<span class="hljs-keyword">const</span> digits = splitNumberUsingForLoop(number);
<span class="hljs-built_in">console</span>.log(digits); <span class="hljs-comment">// [-1, 2, 3, 4, 5]</span>
</code></pre>
<p>In this updated code, we first convert the absolute value of the number to a string using <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs"><code>Math.abs()</code></a> to ensure we're working with positive numbers. The rest of the logic remains the same, where each character is converted back to a number and added to the digits array.</p>
<p>After the loop, we check if the original number is negative (number &lt; <code>0</code>). If it is, we modify the first digit in the digits array to include the negative sign. This way, the resulting array represents the correct split digits of the negative number.</p>
<blockquote>
<p>Note: Here we have used the <code>for loop</code> approach only but you can do the same with other approaches too.</p>
</blockquote>
<h3 id="heading-handling-negative-numbers-in-math-operations">Handling Negative Numbers in Math Operations</h3>
<p>When splitting numbers using Math Operations, we can also incorporate handling for negative numbers within the code. By making a simple adjustment, we can ensure accurate results even when dealing with negative values.</p>
<p>Here's the updated code for handling negative numbers using math operations:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">splitNumberUsingWhileLoop</span>(<span class="hljs-params">number</span>) </span>{
  <span class="hljs-keyword">const</span> digits = [];
  <span class="hljs-keyword">let</span> tempNumber = <span class="hljs-built_in">Math</span>.abs(number);

  <span class="hljs-keyword">while</span> (tempNumber &gt; <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">const</span> digit = tempNumber % <span class="hljs-number">10</span>;
    digits.unshift(digit);
    tempNumber = <span class="hljs-built_in">Math</span>.floor(tempNumber / <span class="hljs-number">10</span>);
  }

  <span class="hljs-keyword">if</span> (number &lt; <span class="hljs-number">0</span>) {
    digits[<span class="hljs-number">0</span>] = -digits[<span class="hljs-number">0</span>]; <span class="hljs-comment">// Adjust the sign of the first digit for negative numbers</span>
  }

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

<span class="hljs-keyword">const</span> number = <span class="hljs-number">-12345</span>;
<span class="hljs-keyword">const</span> digits = splitNumberUsingWhileLoop(number);
<span class="hljs-built_in">console</span>.log(digits); <span class="hljs-comment">// [-1, 2, 3, 4, 5]</span>
</code></pre>
<p>In this updated code, we first obtain the absolute value of the number using <code>Math.abs()</code> and assign it to the <code>tempNumber</code> variable. Then, we perform the splitting process as before using the <code>while loop</code>. After the loop, we add an additional check to adjust the sign of the first digit if the original number is negative. This ensures that negative numbers are correctly handled during the splitting operation.</p>
<blockquote>
<p>Note: Here we have used the <code>while loop</code> approach only but you can do the same with the recursion approach too.</p>
</blockquote>
<h2 id="heading-handling-float-numbers">Handling Float Numbers</h2>
<p>Just like negative numbers, When it comes to splitting float numbers, additional considerations are necessary to handle both the integer and fractional parts accurately. Let's explore techniques to split float numbers into their integer and fractional components:</p>
<h3 id="heading-handling-float-numbers-in-string-conversion">Handling Float Numbers in String Conversion</h3>
<p>To split float numbers using string conversion, we can leverage the same approach as discussed earlier but need to do some extra stuff to handle the floating point.</p>
<p>First, we convert the float number to a string and then split it based on the decimal point. The resulting array will contain two elements: the integer part and the fractional part.</p>
<p>Here's the updated code for the split approach:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">splitFloatNumberUsingStringConversion</span>(<span class="hljs-params">floatNumber</span>) </span>{
  <span class="hljs-keyword">const</span> numberString = floatNumber.toString();
  <span class="hljs-keyword">const</span> [integerPart, fractionalPart] = numberString.split(<span class="hljs-string">"."</span>);

  <span class="hljs-keyword">const</span> integerDigits = integerPart.split(<span class="hljs-string">""</span>).map(<span class="hljs-built_in">Number</span>);
  <span class="hljs-keyword">const</span> fractionalDigits = fractionalPart ? fractionalPart.split(<span class="hljs-string">""</span>).map(<span class="hljs-built_in">Number</span>) : [];

  <span class="hljs-keyword">return</span> { integerDigits, fractionalDigits };
}

<span class="hljs-comment">// Example usage</span>
<span class="hljs-keyword">const</span> floatNumber = <span class="hljs-number">12.345</span>;
<span class="hljs-keyword">const</span> { integerDigits, fractionalDigits } = splitFloatNumberUsingStringConversion(floatNumber);
<span class="hljs-built_in">console</span>.log(integerDigits);     <span class="hljs-comment">// [1, 2]</span>
<span class="hljs-built_in">console</span>.log(fractionalDigits);  <span class="hljs-comment">// [3, 4, 5]</span>
</code></pre>
<p>In this code, the <code>splitFloatNumberUsingStringConversion</code> function takes a floating-point number and converts it to a string. It then splits the string into separate parts for the integer and fractional portions using the dot (<code>.</code>) as the delimiter.</p>
<p>The integer part is converted to an array of digits by splitting the string and mapping each character to a number using the map function. The fractional part is also converted to an array of digits in a similar way. If there is no fractional part, an empty array is returned for <code>fractionalDigits</code>.</p>
<p>Finally, the function returns an object containing the <code>integerDigits</code> and <code>fractionalDigits</code> arrays. These arrays can be accessed separately and used as needed. In the provided example, integerDigits contains <code>[1, 2]</code> and fractionalDigits contains <code>[3, 4, 5]</code>, representing the integer and fractional parts of the original floating-point number, respectively.</p>
<blockquote>
<p>Note: We have not covered the handling of float numbers in the math operation approach to keep things simple. Float numbers can introduce precision limitations and rounding errors in JavaScript. To handle float numbers accurately, additional steps and considerations are required. In this article, we have focused on the handling of whole numbers to provide a straightforward explanation.</p>
</blockquote>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we explored various techniques for splitting a number into an array in JavaScript. Whether you prefer string conversion or mathematical operations each approach offers its advantages and can be applied based on your specific requirements.</p>
<p>By mastering the art of splitting numbers, you'll have the flexibility to handle numerical data effectively and perform various calculations with ease.</p>
<p>Remember to consider factors such as decimal numbers, negative numbers, and performance optimizations when implementing these techniques. With a solid understanding of splitting numbers in JavaScript, you'll be well-equipped to tackle complex numeric tasks in your projects.</p>
<p>Happy coding :)</p>
]]></content:encoded></item><item><title><![CDATA[How to Rename an Object Key in JavaScript]]></title><description><![CDATA[Introduction
You may encounter scenarios where you need to rename an object key When working with objects in JavaScript. Renaming object keys can help to maintain consistency, enhance code readability, or align with specific naming conventions.
In th...]]></description><link>https://robiul.dev/how-to-rename-an-object-key-in-javascript</link><guid isPermaLink="true">https://robiul.dev/how-to-rename-an-object-key-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[tips]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Sun, 11 Jun 2023 07:24:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1686377375166/369fbd1e-6091-4ff4-8357-2fb1feeb922f.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>You may encounter scenarios where you need to rename an object key When working with objects in JavaScript. Renaming object keys can help to maintain consistency, enhance code readability, or align with specific naming conventions.</p>
<p>In this blog post, we will delve into different techniques and approaches to effectively rename object keys in JavaScript. We'll cover both mutable and immutable methods, including manual approaches using <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign"><code>Object.assign()</code></a>, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty"><code>Object.defineProperty()</code></a>, object destructuring, property assignment, and more.</p>
<p>Additionally, we'll discover the benefits of leveraging external libraries like <a target="_blank" href="https://lodash.com/">Lodash</a> that provide specialized functions for renaming object keys.</p>
<p>By the end of this article, you'll have a solid understanding of how to tackle key renaming tasks in JavaScript, empowering you to write more concise and organized code.</p>
<p>So, Let's start!</p>
<h2 id="heading-prerequisites"><strong>Prerequisites</strong></h2>
<p>Before diving into the concept of renaming object keys in JavaScript, it's important to have a basic understanding of the language and its fundamental concepts like <a target="_blank" href="https://robiul.dev/javascript-variables-beginner-thinking">variables</a>, functions, and basic control flow (such as if statements and <a target="_blank" href="https://robiul.dev/javascript-loop-best-practices-for-optimal-performance">loops</a>).</p>
<p>If you are new to JavaScript or need a refresher, there are several online resources available, such as <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript">MDN Web Docs</a>, <a target="_blank" href="https://www.w3schools.com/js/">W3Schools</a>, and <a target="_blank" href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/">freeCodeCamp</a>, that offer comprehensive tutorials and guides.</p>
<p>In addition to these resources, two highly recommended books for beginners in JavaScript are:</p>
<ul>
<li><p><a target="_blank" href="https://amzn.to/3Clu7un">Head First JavaScript Programming: A Brain-Friendly Guide</a></p>
</li>
<li><p><a target="_blank" href="https://amzn.to/43VPa2B">JavaScript: The Definitive Guide: Master the World's Most-Used Programming Language</a></p>
</li>
</ul>
<p>These books will provide you with a solid foundation in JavaScript programming, allowing you to confidently explore the techniques and concepts discussed in this article.</p>
<p>By having a strong grasp of JavaScript fundamentals, you'll be well-prepared to understand the various methods and approaches for renaming object keys in JavaScript.</p>
<h2 id="heading-immutable-object-approach">Immutable Object Approach</h2>
<p>In JavaScript, objects are mutable, meaning you can modify their properties directly. However, when it comes to renaming object keys, you may prefer to maintain immutability and create a new object with the updated key.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686465314171/f1beca2c-9c13-4420-a556-3642e50bd249.webp" alt="Immutable Object Approach" class="image--center mx-auto" /></p>
<p>To achieve this, you can follow the immutable object approach, which involves creating a new object with the desired key name while preserving the other properties. This approach ensures that the original object remains unchanged.</p>
<p>By employing the immutable object approach, you ensure that the original object remains intact and create a new object with the desired key renaming.</p>
<p>There are a few commonly used techniques for achieving this.</p>
<p>Let's explore them:</p>
<h3 id="heading-using-object-destructuring-and-property-assignment">Using Object Destructuring and Property Assignment</h3>
<p>One way to rename an object key in an immutable approach is by utilizing <a target="_blank" href="https://medium.com/javascript-in-plain-english/level-up-your-code-in-5-ways-using-destructuring-assignment-1e4cbbe96a99">object destructuring</a> and property assignment. This technique involves extracting the value associated with the existing key and assigning it to a new key without altering the original object.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myObject = { <span class="hljs-attr">oldKey</span>: <span class="hljs-string">'value'</span> };  

<span class="hljs-comment">// Renaming the key from 'oldKey' to 'newKey' </span>
<span class="hljs-keyword">const</span> { <span class="hljs-attr">oldKey</span>: newKey, ...rest } = myObject; 
<span class="hljs-keyword">const</span> updatedObject = { newKey, ...rest };

<span class="hljs-built_in">console</span>.log(updatedObject); <span class="hljs-comment">// { newKey: 'value' }</span>
</code></pre>
<p>In the above example, we start with an object <code>myObject</code> that has a key called <code>oldKey</code> with a corresponding value. By using object destructuring, we create a new variable <code>newKey</code> and assign it the value of <code>oldKey</code>. The rest of the properties in the object are collected using the spread operator <code>...rest</code>.</p>
<p>This ensures that all other properties of the original object are preserved in the <code>updatedObject</code>.</p>
<p>Finally, we create a new object <code>updatedObject</code> with the renamed key <code>newKey</code> and include the remaining properties from <code>myObject</code>.</p>
<blockquote>
<p>Note: It's important to note that this method does not modify the original object <code>myObject</code>. Instead, it creates a new object <code>updatedObject</code> with the desired key renaming. The original object <code>myObject</code> remains unchanged and can still be accessed separately.</p>
</blockquote>
<p>Using object destructuring and property assignment provides a concise and elegant way to rename object keys while maintaining the integrity of the original object. This approach can be especially useful when you want to create a modified version of an object without altering the original data.</p>
<h3 id="heading-creating-a-new-object-with-renamed-keys">Creating a New Object with Renamed Keys</h3>
<p>Another approach to renaming object keys while preserving the original object is by creating a new object with the renamed keys.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myObject = { <span class="hljs-attr">oldKey</span>: <span class="hljs-string">'value'</span> };  

<span class="hljs-comment">// Creating a new object with renamed key </span>
<span class="hljs-keyword">const</span> updatedObject = { <span class="hljs-attr">newKey</span>: myObject.oldKey };  

<span class="hljs-built_in">console</span>.log(updatedObject); <span class="hljs-comment">// { newKey: 'value' }</span>
</code></pre>
<p>In the above example, we directly create a new object <code>updatedObject</code> with the desired key <code>newKey</code> and assign it the corresponding value from the original object <code>myObject</code>.</p>
<p>This allows us to achieve the renaming effect while keeping the original object intact. Unlike the object destructuring approach, which extracts all properties and creates a new object, this method selectively picks the specific key-value pair from the original object and assigns it to a new key in the updated object.</p>
<p>This approach can be useful when you only need to rename a few specific keys and want to avoid creating a duplicate object with all properties. It provides a straightforward and concise way to achieve key renaming without modifying the original object.</p>
<h3 id="heading-using-objectassign-method">Using <code>Object.assign()</code> method</h3>
<p>Another method to rename an object key while not modifying the original object is by using the <code>Object.assign()</code> method. This method allows you to copy the properties of one or more source objects to a target object.</p>
<p>For example, you can create a new object and assign the desired key-value pair using <code>Object.assign()</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myObject = { <span class="hljs-attr">oldKey</span>: <span class="hljs-string">'value'</span> };

<span class="hljs-comment">// Creating a new object with renamed key using Object.assign()</span>
<span class="hljs-keyword">const</span> updatedObject = <span class="hljs-built_in">Object</span>.assign({}, {
    <span class="hljs-attr">newKey</span>: myObject.oldKey
 });

<span class="hljs-built_in">console</span>.log(updatedObject); <span class="hljs-comment">// { newKey: 'value' }</span>
</code></pre>
<p>In the above example, we use <code>Object.assign()</code> to create a new object by merging an empty target object (<code>{}</code>) with the properties of the <code>myObject</code> and an additional key-value pair (<code>{ newKey: myObject.oldKey }</code>).</p>
<p>This allows us to achieve key renaming without modifying the original object.</p>
<h3 id="heading-using-objectdefineproperty-method">Using <code>Object.defineProperty()</code> method</h3>
<p>Another approach to renaming object keys while maintaining immutability is by using the <code>Object.defineProperty()</code> method. This method allows you to define or modify the properties of an object, including renaming keys.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myObject = { <span class="hljs-attr">oldKey</span>: <span class="hljs-string">'value'</span> };

<span class="hljs-comment">// Creating a new object with the renamed key using Object.defineProperty()</span>
<span class="hljs-keyword">const</span> updatedObject = <span class="hljs-built_in">Object</span>.defineProperty(
  {},
  <span class="hljs-string">'newKey'</span>,
  <span class="hljs-built_in">Object</span>.getOwnPropertyDescriptor(myObject, <span class="hljs-string">'oldKey'</span>)
);

<span class="hljs-built_in">console</span>.log(updatedObject); <span class="hljs-comment">// { newKey: 'value' }</span>
</code></pre>
<p>In the above example, we create a new object <code>updatedObject</code> and use <code>Object.defineProperty()</code> to define the property <code>newKey</code> based on the descriptor of the <code>oldKey</code> from the original object. This creates a new object with the desired key renamed while preserving the associated value.</p>
<p>By utilizing <code>Object.defineProperty()</code>, we can achieve key renaming in an immutable manner by creating a new object with the renamed key, leaving the original object unchanged.</p>
<h2 id="heading-modifying-the-original-object">Modifying the Original Object</h2>
<p>If you are open to modifying the original object, you can directly rename the key within the existing object by deleting the old key and assigning a new key-value pair. This approach allows you to update the object in place and achieve the desired key renaming effect.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686465361907/95b0b39a-b945-4153-8874-0e372277616c.webp" alt="Modifying the Original Object" class="image--center mx-auto" /></p>
<p>We can achieve this by using <code>delete</code> operator or combining other methods with <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete"><code>delete</code> operator</a>.</p>
<p>Let's explore them:</p>
<blockquote>
<p>Note: It's important to note that this approach directly modifies the original object. If you have any dependencies or references to the original key, they will be impacted by this renaming operation.</p>
<p>Therefore, consider this method when it is acceptable and desired to update the object in place.</p>
</blockquote>
<h3 id="heading-using-delete-operator">Using <code>delete</code> operator</h3>
<p>Using the <code>delete</code> operator is the most commonly used approach to rename object keys by modifying the original object in Javascript.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myObject = { <span class="hljs-attr">oldKey</span>: <span class="hljs-string">'value'</span> };  

<span class="hljs-comment">// Renaming the key within the original object </span>
myObject.newKey = myObject.oldKey; 
<span class="hljs-keyword">delete</span> myObject.oldKey;  

<span class="hljs-built_in">console</span>.log(myObject); <span class="hljs-comment">// { newKey: 'value' }</span>
</code></pre>
<p>In the above example, we start with an object <code>myObject</code> that has a key called <code>oldKey</code> with a corresponding value. To rename the key, we first assign the value of <code>myObject.oldKey</code> to a new key called newKey within the same object. This effectively renames the key while preserving the associated value.</p>
<p>Next, using the delete operator, we remove the <code>oldKey</code> from the object, ensuring that only the new key remains. As a result, the object is modified, and we obtain the desired key renaming within the original object itself.</p>
<p>You can also use bracket notation to assign the new value and delete the old one:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myObject = { <span class="hljs-attr">oldKey</span>: <span class="hljs-string">'value'</span> };  

<span class="hljs-comment">// Renaming the key within the original object </span>
myObject[<span class="hljs-string">"newKey"</span>] = myObject[<span class="hljs-string">"oldKey"</span>]; 
<span class="hljs-keyword">delete</span> myObject[<span class="hljs-string">"oldKey"</span>];  

<span class="hljs-built_in">console</span>.log(myObject); <span class="hljs-comment">// { newKey: 'value' }</span>
</code></pre>
<h3 id="heading-combining-other-methods-with-delete-operator">Combining Other methods with <code>delete</code> operator</h3>
<p>While renaming an object key Modifying the Original Object approach typically refers to using the delete operator, it is worth noting that you can achieve the same effect by combining other techniques like <code>Object.assign()</code> or <code>Object.defineProperty()</code> with the <code>delete</code> operator.</p>
<p>Here's an example that demonstrates the combination of techniques:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myObject = { <span class="hljs-attr">oldKey</span>: <span class="hljs-string">'value'</span> };

<span class="hljs-comment">// Renaming the key using Object.assign() and delete operator</span>
<span class="hljs-built_in">Object</span>.assign(myObject, { <span class="hljs-attr">newKey</span>: myObject.oldKey });
<span class="hljs-keyword">delete</span> myObject.oldKey;

<span class="hljs-built_in">console</span>.log(myObject); <span class="hljs-comment">// { newKey: 'value' }</span>
</code></pre>
<p>In the above example, we first use <code>Object.assign()</code> to assign a new key-value pair to the original object, effectively renaming the key. Then, we use the delete operator to remove the old key from the object.</p>
<p>By combining these techniques, we achieve the desired key renaming effect while modifying the original object.</p>
<p>It's important to consider the implications of combining these techniques. Ensure that the properties you are assigning using <code>Object.assign()</code> does not conflict with existing keys in the object.</p>
<p>By combining different techniques, you can customize the key renaming process and choose the most suitable approach for your specific use case.</p>
<h2 id="heading-using-a-library-or-utility-function">Using a Library or Utility Function</h2>
<p>In addition to the manual approaches discussed earlier, you can leverage existing JavaScript libraries or utility functions specifically designed for renaming object keys. These libraries provide convenient methods that simplify the process and offer additional functionalities.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1686465402589/1db98f0a-fd33-4b8c-a870-0235aface8b0.webp" alt="Using a Library or Utility Function" class="image--center mx-auto" /></p>
<p>One such popular library is <code>Lodash</code>, which provides a rich set of utility functions for JavaScript. Lodash includes a renameKeys function that allows you to rename object keys easily.</p>
<blockquote>
<p>Note: The approach mentioned in this section requires the lodash.js library, which is not available in standard JavaScript. To use this method, you need to install the <code>lodash</code> library using the following command:</p>
<pre><code class="lang-bash">npm i --save lodash
</code></pre>
<p>Please note that this command assumes you have npm (Node Package Manager) installed and configured in your development environment. Installing the <code>lodash</code> library will provide you with additional functionality for renaming object keys in JavaScript.</p>
</blockquote>
<p>Here's an example of how you can use <code>Lodash</code>'s <code>renameKeys</code> function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> _ = <span class="hljs-built_in">require</span>(<span class="hljs-string">'lodash'</span>);  
<span class="hljs-keyword">const</span> myObject = { <span class="hljs-attr">oldKey</span>: <span class="hljs-string">'value'</span> };  

<span class="hljs-comment">// Renaming the key using Lodash </span>
<span class="hljs-keyword">const</span> updatedObject = _.renameKeys(myObject, { <span class="hljs-attr">oldKey</span>: <span class="hljs-string">'newKey'</span> });  

<span class="hljs-built_in">console</span>.log(updatedObject); <span class="hljs-comment">// { newKey: 'value' }</span>
</code></pre>
<p>In the above example, we start by importing the <code>Lodash</code> library using the <code>require</code> statement. We have an object <code>myObject</code> with a key called <code>oldKey</code> and its corresponding value.</p>
<p>By using Lodash's <code>renameKeys</code> function, we pass in the <code>myObject</code> and an object specifying the key mapping to perform the renaming. In this case, we want to rename the oldKey to newKey.</p>
<p>The <code>renameKeys</code> function performs the key renaming operation and returns a new object updatedObject with the renamed key.</p>
<p>By utilizing a library like <code>Lodash</code>, you can benefit from well-tested and optimized code, reducing the amount of custom code you need to write and potentially improving performance.</p>
<h2 id="heading-rename-multiple-keys-using-map-method">Rename multiple keys using <code>map()</code> method</h2>
<p>So far, we have explored various approaches to renaming object keys in javascript. However, there may be situations where you need to rename multiple keys simultaneously.</p>
<p>In such cases, you can leverage the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map"><code>map()</code></a> method in combination with any of the techniques discussed in this article.</p>
<p>The <code>map()</code> method allows you to iterate over the keys of an object and perform a transformation operation on each key-value pair. By utilizing this method, you can easily rename multiple keys in one go.</p>
<p>Here's an example that demonstrates the use of the <code>map()</code> method for renaming multiple keys:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myObject = {
  <span class="hljs-attr">oldKey1</span>: <span class="hljs-string">'value1'</span>,
  <span class="hljs-attr">oldKey2</span>: <span class="hljs-string">'value2'</span>,
  <span class="hljs-attr">oldKey3</span>: <span class="hljs-string">'value3'</span>
};

<span class="hljs-keyword">const</span> keyMap = {
  <span class="hljs-attr">oldKey1</span>: <span class="hljs-string">'newKey1'</span>,
  <span class="hljs-attr">oldKey2</span>: <span class="hljs-string">'newKey2'</span>,
  <span class="hljs-attr">oldKey3</span>: <span class="hljs-string">'newKey3'</span>
};

<span class="hljs-keyword">const</span> updatedObject = <span class="hljs-built_in">Object</span>.fromEntries(
  <span class="hljs-built_in">Object</span>.entries(myObject).map(<span class="hljs-function">(<span class="hljs-params">[key, value]</span>) =&gt;</span> [keyMap[key] || key, value])
);

<span class="hljs-built_in">console</span>.log(updatedObject);
<span class="hljs-comment">/*
{
  newKey1: 'value1',
  newKey2: 'value2',
  newKey3: 'value3'
}
*/</span>
</code></pre>
<p>In the above example, we define a <code>keyMap</code> object that maps the old keys to their corresponding new keys. We then use the <code>map()</code> method in combination with <code>Object.entries()</code> to iterate over the object's key-value pairs.</p>
<p>Within the <code>map()</code> callback, we check if a key exists in the keyMap object and use the mapped new key if available, or keep the original key as is.</p>
<p>Finally, we use <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries"><code>Object.fromEntries()</code></a> to convert the updated key-value pairs back into an object.</p>
<p>By using the <code>map()</code> method, you can efficiently rename multiple keys in an object with ease. This approach provides flexibility and allows for more complex key renaming scenarios.</p>
<h2 id="heading-deep-object-key-renaming">Deep Object Key Renaming</h2>
<p>In some cases, you may need to rename keys that are nested within nested objects or arrays. The techniques mentioned earlier can be extended to handle deep object key renaming.</p>
<blockquote>
<p>Note: This section covers an advanced technique for renaming keys within deeply nested objects. If you find it challenging or are not familiar with nested data structures in JavaScript, feel free to skip this section.</p>
</blockquote>
<p>One approach is to use recursion to traverse through the object and rename keys at each level.</p>
<p>Here's an example implementation:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">renameKeysDeep</span>(<span class="hljs-params">obj, keyMap</span>) </span>{
   <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> obj !== <span class="hljs-string">'object'</span> || obj === <span class="hljs-literal">null</span>) {
     <span class="hljs-keyword">return</span> obj;
   }

   <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Array</span>.isArray(obj)) {
     <span class="hljs-keyword">return</span> obj.map(<span class="hljs-function">(<span class="hljs-params">item</span>) =&gt;</span> renameKeysDeep(item, keyMap));
   }

  <span class="hljs-keyword">const</span> renamedObj = {};

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">in</span> obj) {
     <span class="hljs-keyword">if</span> (obj.hasOwnProperty(key)) {
       <span class="hljs-keyword">const</span> newKey = keyMap[key] || key;
       renamedObj[newKey] = renameKeysDeep(obj[key], keyMap);
     }
   }
   <span class="hljs-keyword">return</span> renamedObj; 
}  

<span class="hljs-keyword">const</span> myObject = {
   <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>,
   <span class="hljs-attr">info</span>: {
     <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>,
     <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>,
     <span class="hljs-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-keyword">const</span> updatedObject = renameKeysDeep(myObject, {
   <span class="hljs-attr">id</span>: <span class="hljs-string">'userId'</span>,
   <span class="hljs-attr">name</span>: <span class="hljs-string">'fullName'</span>,
   <span class="hljs-attr">street</span>: <span class="hljs-string">'location.street'</span>,
 });  

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

<span class="hljs-comment">/* 
{
   userId: 1,
   info: {
     fullName: 'John',
     age: 30,
     address: {
       location.street: '123 Main St',
       city: 'New York',
     },
   },
 } 
*/</span>
</code></pre>
<p>In this provided example, the <code>renameKeysDeep</code> function is employed to recursively traverse the object and rename keys based on the provided <code>keyMap</code> object.</p>
<p>The function intelligently handles nested objects and arrays, ensuring that keys are appropriately renamed throughout the data structure.</p>
<p>By implementing deep object key renaming, you gain the flexibility to work with intricate data structures and maintain consistent key renaming across all levels of nesting.</p>
<p>This technique proves valuable when you encounter complex objects that require key modifications within deeply nested hierarchies.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this blog post, we explored various techniques for renaming object keys in JavaScript. We discussed the Immutable Object Approach, Modifying the Original Object with Renamed Keys, Using a Library or Utility Function, and Deep Object Key Renaming.</p>
<p>These approaches provide different ways to achieve key renaming based on factors such as immutability, in-place modification, external library usage, renaming multiple keys, and handling nested objects.</p>
<p>By understanding these techniques, you now have the tools to efficiently rename object keys according to your specific needs. Choose the approach that suits your project and enjoy the benefits of consistent and readable code.</p>
<p>Happy coding :)</p>
]]></content:encoded></item><item><title><![CDATA[How to Check if a String is Empty in JavaScript]]></title><description><![CDATA[Introduction
Working with strings is a common task in JavaScript development. Whether you're validating user input, processing data, or implementing string manipulation operations, it's important to have robust techniques to check if a string is empt...]]></description><link>https://robiul.dev/how-to-check-if-a-string-is-empty-in-javascript</link><guid isPermaLink="true">https://robiul.dev/how-to-check-if-a-string-is-empty-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[tips]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Sun, 04 Jun 2023 06:08:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1685714395868/e51df285-5fa2-4a34-ba88-4314d1ab3742.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Working with strings is a common task in JavaScript development. Whether you're validating user input, processing data, or implementing string manipulation operations, it's important to have robust techniques to check if a string is empty in javascript.</p>
<p>In this blog post, we will dive into various approaches to check if a string is empty in JavaScript. We'll cover methods that not only detect an empty string but also handle scenarios where the string may contain only whitespace characters, or it may be <code>null</code> or <code>undefined</code>.</p>
<p>By familiarizing yourself with these techniques, you'll gain the knowledge and tools necessary to handle empty string scenarios effectively in your JavaScript code.</p>
<p>Let's get started!</p>
<h2 id="heading-why-do-we-need-to-check-empty-string">Why do we need to check Empty string</h2>
<p>Before we jump into different ways of checking if a string is empty or not, let's take a moment to understand why it's important. At first, it may seem like a small detail, but there are good reasons why we need to pay attention to empty strings.</p>
<p>By understanding the reason, we can see how this seemingly simple task can have a big impact on our code.</p>
<p>To illustrate the importance of checking for an empty string, let's consider a simple example.</p>
<p>Imagine a scenario where you have a search feature on your website that allows users to input a search query. Let's say the search functionality uses JavaScript to process the query and display the search results.</p>
<p>Here's a code example without checking for an empty string:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: Search functionality without checking for an empty string </span>
<span class="hljs-keyword">let</span> performSearch = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-comment">// code here</span>
}
<span class="hljs-keyword">let</span> searchQuery = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'search input'</span>).value 
<span class="hljs-comment">// Process the search query and display the results </span>
performSearch(searchQuery)
</code></pre>
<p>In this code, the <code>searchQuery</code> variable is assigned the value of the user's input from an HTML input field with the ID <code>searchInput</code>. However, this code doesn't include any validation to check if the user has actually entered a search query or left the field empty.</p>
<p>The problem arises when a user submits the form without entering any search query. Without checking for an empty string, the code will proceed to process the empty search query. This can lead to unexpected behavior, such as displaying incorrect or irrelevant search results or throwing errors in the search functionality.</p>
<p>By not checking for an empty string in the search functionality, if the user submits the form without entering any search query, the code will still proceed to execute the search logic.</p>
<p>In this case, it will log an error message indicating an empty search query. This helps to highlight the unexpected behavior that can occur when empty input is not properly validated.</p>
<p>To address this issue, it is important to check if the search query is empty before proceeding with the search functionality.</p>
<h2 id="heading-method-1-using-the-length-property">Method 1: Using the Length Property</h2>
<p>The simplest way of checking if a string is empty in JavaScript is the <a target="_blank" href="https://www.w3schools.com/jsref/jsref_length_string.asp"><code>length</code></a> property. By comparing the length of a string to zero, we can determine if it is empty or not.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myStr = <span class="hljs-string">''</span>

<span class="hljs-keyword">if</span> (myStr.length === <span class="hljs-number">0</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'This is a javascript empty string!'</span>)
}
</code></pre>
<p>However, this approach will not handle cases where the string contains only whitespace characters.</p>
<p>To overcome this, we can use the <code>trim()</code> method to remove the leading and trailing whitespace before checking the length.</p>
<p>Consider the following code snippet:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myStr = <span class="hljs-string">' '</span>;

<span class="hljs-keyword">if</span> (myStr.trim().length === <span class="hljs-number">0</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'This is a javascript empty string!'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'This is NOT a javascript empty string!'</span>);
}
</code></pre>
<p>In this case, the initial check would erroneously classify the string as non-empty due to the presence of whitespace.</p>
<p>However, by applying the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim"><code>trim()</code></a> method, we ensure that whitespace is eliminated before checking the length, and correctly identifying an empty string.</p>
<p>It's important to note that the <code>length</code> property does not work for <a target="_blank" href="https://www.programiz.com/javascript/null-undefined"><code>null</code></a> or <a target="_blank" href="https://www.programiz.com/javascript/null-undefined"><code>undefined</code></a> values, and attempting to access the length property of a <code>null</code> or <code>undefined</code> value will throw an error.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685724626793/74b2095a-d063-4a1e-a82a-35899cdef507.webp" alt="the length property does not work for null or undefined values" class="image--center mx-auto" /></p>
<p>To handle these, we can add additional conditions to check if the value is of a type string before performing the length check.</p>
<p>For instance:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myStr = <span class="hljs-literal">null</span>;

<span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> myStr === <span class="hljs-string">'string'</span> &amp;&amp; myStr.trim().length === <span class="hljs-number">0</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'This is a javascript empty string!'</span>);
}
</code></pre>
<p>This code first verifies that the value is a string using the <code>typeof</code> operator before applying the <code>trim()</code> method and checking the <code>length</code>. This approach prevents errors when dealing with <code>null</code> or <code>undefined</code> values.</p>
<p>To handle all of these <code>null</code>, <code>undefined</code>, and empty string at the same time, we can combine the conditions using the logical (<code>||</code>) <a target="_blank" href="https://www.geeksforgeeks.org/or-logical-operator-in-javascript/">OR operator</a>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myStr = <span class="hljs-literal">null</span>;

<span class="hljs-keyword">if</span> (myStr === <span class="hljs-literal">null</span> || myStr === <span class="hljs-literal">undefined</span> || myStr.trim().length === <span class="hljs-number">0</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'This is a javascript empty string!'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'This is not a javascript empty string!'</span>);
}
</code></pre>
<p>By considering all these scenarios, we can accurately determine whether a string is empty or not, ensuring proper handling and avoiding potential issues in our code.</p>
<h2 id="heading-method-2-comparing-to-a-string">Method 2: comparing to a string</h2>
<p>Another approach to checking if a string is empty is by comparing it to an empty string.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myStr = <span class="hljs-string">""</span>;

<span class="hljs-keyword">if</span> (myStr === <span class="hljs-string">""</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"This is a javascript empty string!"</span>);
}
</code></pre>
<p>However, similar to the previous method, this approach does not consider strings that contain only whitespace characters. To treat a string containing only whitespace as empty, we can use the <code>trim()</code> method before comparing it to an empty string.</p>
<p>Here's an example function that checks if a string is empty, considering whitespace characters:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkIfEmpty</span>(<span class="hljs-params">str</span>) </span>{
  <span class="hljs-keyword">if</span> (str.trim() === <span class="hljs-string">''</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'String is empty string'</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'String is NOT empty string'</span>);
  }
}

<span class="hljs-keyword">const</span> str1 = <span class="hljs-string">'not empty'</span>;
<span class="hljs-keyword">const</span> str2 = <span class="hljs-string">''</span>;      <span class="hljs-comment">// empty</span>
<span class="hljs-keyword">const</span> str3 = <span class="hljs-string">' '</span>;     <span class="hljs-comment">// contains only whitespace</span>

checkIfEmpty(str1);   <span class="hljs-comment">// outputs: String is NOT empty</span>
checkIfEmpty(str2);   <span class="hljs-comment">// outputs: String is empty</span>
checkIfEmpty(str3);   <span class="hljs-comment">// outputs: String is empty</span>
</code></pre>
<p>In the <code>checkIfEmpty</code> function, we call the <code>trim()</code> method on the string to remove any leading or trailing whitespace. Then, we compare the resulting trimmed string with an empty string to determine if it's empty or not.</p>
<p>Using the <code>trim()</code> method ensures that strings containing only whitespace characters are treated as empty. It removes all whitespace from the beginning and end of the string, returning a new string without modifying the original.</p>
<blockquote>
<p>Note: Trimming a string is particularly useful when validating required fields in a form, as it helps ensure that the user entered actual data instead of just whitespace.</p>
</blockquote>
<h2 id="heading-method-3-using-the-operator">Method 3: Using the <code>!</code> Operator</h2>
<p>Javascript treats empty strings as falsy values, which means they evaluate to <code>false</code> in a boolean context. We can take advantage of this behavior to check if a string is empty using the negation operator <code>(!)</code>.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isEmptyString</span>(<span class="hljs-params">str</span>) </span>{
  <span class="hljs-keyword">return</span> !str;
}
</code></pre>
<p>In this example, the <code>isEmptyString</code> function takes a string as an argument and returns <code>true</code> if the string is empty, and <code>false</code> otherwise. By using the negation operator <code>!</code>, we are essentially checking if the string is falsy, which includes empty strings.</p>
<p>However, like the previous methods, this approach does not consider strings that contain only whitespace characters. To handle whitespace characters, we can combine this approach with the <code>trim()</code> method.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkIfEmpty</span>(<span class="hljs-params">str</span>) </span>{
  <span class="hljs-keyword">if</span> (!str.trim()) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'String is empty'</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'String is NOT empty'</span>);
  }
}

<span class="hljs-keyword">const</span> str1 = <span class="hljs-string">'not empty'</span>;
<span class="hljs-keyword">const</span> str2 = <span class="hljs-string">''</span>;      <span class="hljs-comment">// empty</span>
<span class="hljs-keyword">const</span> str3 = <span class="hljs-string">' '</span>;     <span class="hljs-comment">// contains only whitespace</span>

checkIfEmpty(str1);   <span class="hljs-comment">// outputs: String is NOT empty</span>
checkIfEmpty(str2);   <span class="hljs-comment">// outputs: String is empty</span>
checkIfEmpty(str3);   <span class="hljs-comment">// outputs: String is empty</span>
</code></pre>
<p>In the <code>checkIfEmpty</code> function, we call the <code>trim()</code> method on the string to remove leading and trailing whitespace. Then, we compare the trimmed string with an empty string to determine if it's empty or not.</p>
<p>The <code>trim()</code> method removes all whitespace from the beginning and end of a string and returns a new string, without modifying the original. This allows us to accurately handle strings with whitespace characters.</p>
<p>It's important to note that checking for an empty string using the negation operator or combining it with <code>trim()</code> will not handle null and undefined values. If you also need to handle null and undefined, you can modify the condition as follows:</p>
<pre><code class="lang-javascript">javascriptCopy codefunction checkIfEmpty(str) {
  <span class="hljs-keyword">if</span> (!str || str.trim() === <span class="hljs-string">''</span>) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'String is empty'</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'String is NOT empty'</span>);
  }
}
</code></pre>
<p>In the above code, the condition <code>!str</code> checks if the <code>str</code> variable is <code>falsy</code> (<code>null</code>, <code>undefined</code>, an empty string, or a <code>0</code>). If it is, the code inside the <code>if</code> block will be executed, indicating that the string is empty.</p>
<p>By incorporating these checks, we ensure proper handling of empty strings, including those with whitespace characters, null values, and undefined variables, in our JavaScript code.</p>
<h2 id="heading-method-4-using-the-nullish-coalescing-operator">Method 4: Using the Nullish Coalescing Operator (<code>??</code>)</h2>
<p>Until now, we have explored three ways to check for an empty string. However, there is an advanced approach introduced in ECMAScript 2020 that can help reduce the amount of code needed.</p>
<p>The <a target="_blank" href="https://javascript.info/nullish-coalescing-operator">nullish coalescing operator</a> (<code>??</code>) provides a concise way to check if a string is empty or bullish:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isEmptyString</span>(<span class="hljs-params">str</span>) </span>{
  <span class="hljs-keyword">return</span> (str ?? <span class="hljs-string">''</span>) === <span class="hljs-string">''</span>;
}
</code></pre>
<p>In the code above, the nullish coalescing operator (<code>??</code>) checks if the value of <code>str</code> is either <code>null</code> or <code>undefined</code>. If it is, the operator returns an empty string <code>''</code>. We then compare the result with an empty string <code>''</code> to determine if the string is empty or nullish.</p>
<p>By using the nullish coalescing operator, we can handle the scenario where the string is either <code>null</code> or <code>undefined</code>.</p>
<p>Additionally, we can leverage the <a target="_blank" href="https://www.freecodecamp.org/news/javascript-optional-chaining/">optional chaining</a> (<code>?.</code>) operator to handle <code>null</code> and <code>undefined</code> values:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> str = <span class="hljs-string">' '</span>;

<span class="hljs-keyword">if</span> (str?.trim()) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The string is NOT empty'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The string is empty'</span>);
}
</code></pre>
<p>The optional chaining operator (<code>?.</code>) short-circuits and returns <code>undefined</code> if the value to the left is nullish (<code>null</code> or <code>undefined</code>). This allows us to handle cases where the string variable holds an <code>undefined</code> value:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> str = <span class="hljs-literal">undefined</span>;

<span class="hljs-keyword">if</span> (str?.trim()) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The string is NOT empty'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The string is empty'</span>);
}
</code></pre>
<p>Instead of encountering an error when trying to call the <code>trim()</code> method on an <code>undefined</code> value, the optional chaining operator prevents the error by returning <code>undefined</code>.</p>
<p>Using the nullish coalescing operator and optional chaining operator can simplify your code and handle <code>null</code>, <code>undefined</code>, and empty string scenarios more effectively.</p>
<h2 id="heading-value-is-not-an-empty-string-undefined-or-null">Value is NOT an empty string, undefined or null</h2>
<p>Previously, we learned how to check if a string is empty, null, or undefined. Now, let's explore how to check if a string is not an empty string, undefined, or null using a similar approach.</p>
<p>To determine if a value is not an empty string, <code>undefined</code>, or <code>null</code>, you can use the logical AND (<code>&amp;&amp;</code>) operator in JavaScript. This approach ensures that all conditions must be met for the if block to be executed.</p>
<p>Let's break down the code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> str = <span class="hljs-string">'bobbyhadz.com'</span>;

<span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> str !== <span class="hljs-string">'undefined'</span> &amp;&amp; str !== <span class="hljs-literal">null</span> &amp;&amp; str.trim() !== <span class="hljs-string">''</span>) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The value is NOT undefined, null, or an empty string'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The value is undefined, null, or an empty string'</span>);
}
</code></pre>
<p>In the code above, we perform the following checks:</p>
<ol>
<li><p>First, we use <code>typeof</code> to check if the variable <code>str</code> is not of type <code>undefined</code>. This condition prevents the code from throwing an error if <code>str</code> has not been declared or defined.</p>
</li>
<li><p>Next, we check if <code>str</code> is not <code>null</code>. The null value represents the intentional absence of any object value. In javascript, By checking whether the string is <code>null</code> or empty, we ensure that the variable has a valid value.</p>
</li>
<li><p>Finally, we verify that <code>str.trim()</code> is not an empty string. An empty string has no characters and is represented by two quotation marks with nothing in between.</p>
</li>
</ol>
<p>By combining these conditions with the logical AND operator (<code>&amp;&amp;</code>), we ensure that all of them must evaluate to <code>true</code> for the if block to be executed. If any of the conditions is not met, the else block runs, indicating that the value is either <code>undefined</code>, <code>null</code>, or an empty string.</p>
<p>Using this approach provides a comprehensive check to determine if a value has valid content, helping you avoid unexpected behavior or errors in your code.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this blog post, we have explored various techniques to check for empty, <code>null</code>, or <code>undefined</code> strings in JavaScript. By using methods such as length comparison, string comparison, negation operator (<code>!</code>), and nullish coalescing operator (<code>??</code>), we can effectively handle these scenarios.</p>
<p>By incorporating these techniques into your code, you can ensure the reliability and stability of your JavaScript applications. Remember to practice and experiment with these methods to deepen your understanding and proficiency.</p>
<p>Continuously refining your skills will make you a more adept JavaScript developer, capable of leveraging these techniques to enhance the functionality of your applications.</p>
<p>Keep exploring and enjoy the journey of mastering JavaScript!</p>
<h2 id="heading-resources"><strong>Resources</strong></h2>
<ul>
<li><p>https://www.freecodecamp.org/news/javascript-check-empty-string-checking-null-or-empty-in-js/</p>
</li>
<li><p>https://bobbyhadz.com/blog/javascript-check-if-string-is-empty</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[How to Round a Number to 2 Decimal Places in JavaScript]]></title><description><![CDATA[Introduction
There are many ways to round a number to 2 Decimal Places in javascript. Also, you may have read a few articles on the internet discussing different approaches to do that.
But one thing that I have realized all of the articles has just t...]]></description><link>https://robiul.dev/round-to-2-decimal-places-in-javascript</link><guid isPermaLink="true">https://robiul.dev/round-to-2-decimal-places-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[tips]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Sun, 28 May 2023 09:05:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1685258237186/8c412ae0-5e81-4a30-8b7b-cfe2004c993b.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>There are many ways to round a number to 2 Decimal Places in javascript. Also, you may have read a few articles on the internet discussing different approaches to do that.</p>
<p>But one thing that I have realized all of the articles has just talked about a few techniques of doing that but not much about the use case of it or things that we need to consider about it.</p>
<p>In this article, I will try to give you the full explanation of it not only discussing various techniques and methods that can be used to achieve the desired rounding effect but also shed light on the practical use cases and considerations associated with rounding. And we are taking two 2 decimal points it doesn't mean we will always use 2 decimal places it can be any number of decimal places depending on the specific use case and requirements of the application.</p>
<p>But, since we are talking about so many things it doesn't mean this will make things so complicated, not at all. I will make sure that we are getting the whole Idea and also keeping things very easy to understand at the same time.</p>
<p>So let's begin.</p>
<h2 id="heading-why-do-we-need-to-round-a-number">Why Do We Need to Round a Number?</h2>
<p>Let's start our journey by answering the question that might appear in a person's mind when he will first hears the term "Round a Number to 2 Decimal Places".</p>
<p>And that is "Why do we need it?".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685259020958/bf01d64c-ff44-4ab6-939a-67b872b8a498.webp" alt="Why Do We Need to Round a Number?" class="image--center mx-auto" /></p>
<p>This is a very important and at the same time very relevant question that needs to be answered.</p>
<p>To answer the question let's consider a practical scenario:</p>
<p>Suppose you have an application that tracks the temperature readings from different sensors. Each sensor provides temperature measurements with high precision, including values beyond two decimal places.</p>
<p>For example:</p>
<ul>
<li><p>Sensor 1: <code>25.7689°C</code></p>
</li>
<li><p>Sensor 2: <code>26.1356°C</code></p>
</li>
<li><p>Sensor 3: <code>25.9241°C</code></p>
</li>
</ul>
<p>To calculate the average temperature from these sensor readings, you add them up and divide them by the total number of sensors. The average temperature without rounding would be <code>25.9429°C</code>.</p>
<p>However, displaying the average temperature with all the decimal places can be visually overwhelming and unnecessary for most users. It's more appropriate to round the average temperature to a desired level of precision, such as 2 decimal places, to provide a more concise and meaningful representation.</p>
<p>By rounding the average temperature to 2 decimal places, the displayed value becomes <code>25.94°C</code>.</p>
<p>In this scenario rounding the number helps to simplify the temperature representation, making it easier to read and understand without sacrificing the overall accuracy significantly.</p>
<p>This is just a simple example, there are many scenarios where we will be in need of rounding the number to desired decimal places.</p>
<h2 id="heading-different-ways-to-round-a-number">Different Ways to Round a Number</h2>
<p>Rounding numbers in JavaScript can be achieved using various approaches.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685259270531/55014e14-a7d4-4dde-87ed-d00e250f48d6.webp" alt="Different Ways to Round a Number" class="image--center mx-auto" /></p>
<p>Here are different ways to do that:</p>
<h3 id="heading-javascript-tofixed-method">JavaScript toFixed Method</h3>
<p>The first way that we will talk about is the <a target="_blank" href="https://www.w3schools.com/jsref/jsref_tofixed.asp"><code>toFixed()</code></a> method. This is a built-in JavaScript function that allows you to round a number to a specific number of decimal places. It provides a convenient way to format and display numeric values precisely.</p>
<p>The <code>toFixed()</code> method is particularly useful when you need to ensure a consistent number of decimal places in your calculations, financial applications, or data representation.</p>
<p>Here's how you can use the <code>toFixed()</code> method to round numbers to 2 decimal places:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> number = <span class="hljs-number">3.14159</span>; 
<span class="hljs-keyword">const</span> roundedNumber = number.toFixed(<span class="hljs-number">2</span>); 
<span class="hljs-built_in">console</span>.log(roundedNumber); <span class="hljs-comment">// Output: "3.14"</span>
</code></pre>
<p>In this method, you call the <code>toFixed()</code> method on a number and provide the desired number of decimal places as an argument. The method returns a string representation of the rounded number with the specified decimal places.</p>
<p>One key advantage of using <code>toFixed()</code> is that it automatically adds trailing zeros if necessary.</p>
<p>For example:</p>
<p>If you have the number <code>3</code>, calling <code>toFixed(2)</code> will return <code>3.00</code>, ensuring that the output always has the specified number of decimal places.</p>
<blockquote>
<p>Note: It's important to note that the <code>toFixed()</code> method uses rounding rules, which means that if the next decimal place is <code>5</code> or greater, it rounds up the preceding digit.</p>
<p>For example:</p>
<p>if you have the number <code>3.145</code>, calling <code>toFixed(2)</code> will round it to <code>3.15</code></p>
</blockquote>
<h3 id="heading-mathround-method">Math.round() Method</h3>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round"><code>Math.round()</code></a> function is another approach to round a number to the nearest integer. By combining it with some arithmetic operations, we can round a number to 2 decimal places.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> number = <span class="hljs-number">3.14159</span>; 
<span class="hljs-keyword">const</span> roundedNumber = <span class="hljs-built_in">Math</span>.round(number * <span class="hljs-number">100</span>) / <span class="hljs-number">100</span>; 
<span class="hljs-built_in">console</span>.log(roundedNumber); <span class="hljs-comment">// Output: 3.14</span>
</code></pre>
<p>In this example, we have multiplied the number by <code>100</code> to shift the decimal places to the right. Then, we have applied <code>Math.round()</code> to round the adjusted number to the nearest integer. Finally, we have divided the result by <code>100</code> to shift the decimal places back to the original position.</p>
<p>This way of rounding numbers is a little bit tricky but it can be useful in scenarios where more precise control over the rounding process is required, or when you want to avoid using the <code>toFixed()</code> method.</p>
<h3 id="heading-mathfloor-or-mathceil">Math.floor() or Math.ceil()</h3>
<p>If you want to round a number to <code>2</code> decimal places but always javascript round down or always round up, you can use the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor"><code>Math.floor()</code></a> or <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil"><code>Math.ceil()</code></a> function, respectively.</p>
<p>Here are the examples:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> number = <span class="hljs-number">3.14159</span>;

<span class="hljs-comment">// Rounding down</span>
<span class="hljs-keyword">const</span> roundedDown = <span class="hljs-built_in">Math</span>.floor(number * <span class="hljs-number">100</span>) / <span class="hljs-number">100</span>;
<span class="hljs-built_in">console</span>.log(roundedDown); <span class="hljs-comment">// Output: 3.14</span>

<span class="hljs-comment">// Rounding up</span>
<span class="hljs-keyword">const</span> roundedUp = <span class="hljs-built_in">Math</span>.ceil(number * <span class="hljs-number">100</span>) / <span class="hljs-number">100</span>;
<span class="hljs-built_in">console</span>.log(roundedUp); <span class="hljs-comment">// Output: 3.15</span>
</code></pre>
<p>In the above example, we have used both <code>Math.floor()</code> and <code>Math.ceil()</code> functions to round the number to <code>2</code> decimal places.</p>
<p>Using <code>Math.floor()</code> ensures that the number is always rounded down to the nearest integer. In our example, we multiply the number by <code>100</code> to shift the decimal places to the right, apply <code>Math.floor()</code> to round it down to the nearest integer, and then divide it by 100 to shift the decimal places back.</p>
<p>On the other hand, <code>Math.ceil()</code> always rounds up to the nearest integer. Similarly, we multiply the number by <code>100</code>, use <code>Math.ceil()</code> to round it up, and divide it by <code>100</code> to restore the original decimal places.</p>
<p>These methods are particularly useful when you have specific rounding rules to follow, such as in financial calculations or when dealing with quantities that cannot be fractional.</p>
<h3 id="heading-parsefloat-in-combination-with-toprecision">parseFloat() in combination with toPrecision()</h3>
<p>Rounding a number to <code>2</code> decimal places can also be achieved by using <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat"><code>parseFloat()</code></a> in combination with the <a target="_blank" href="https://www.w3schools.com/jsref/jsref_toprecision.asp"><code>toPrecision()</code></a> function. This method provides an alternative approach to obtaining the desired rounded value.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> number = <span class="hljs-number">3.14159</span>; 
<span class="hljs-keyword">const</span> roundedNumber = <span class="hljs-built_in">parseFloat</span>(number.toPrecision(<span class="hljs-number">3</span>));
<span class="hljs-built_in">console</span>.log(roundedNumber); <span class="hljs-comment">// Output: 3.14</span>
</code></pre>
<p>In this approach, we utilize the <code>toPrecision(3)</code> function, which returns a string representation of the number with four significant digits. By specifying <code>3</code> as the argument, we ensure that the resulting string contains the necessary precision for rounding to <code>2</code> decimal places.</p>
<p>Next, we apply the <code>parseFloat()</code> function to the resulting string. This converts the string representation back into a number, effectively rounding it to 2 decimal places.</p>
<p>Using <code>parseFloat()</code> in combination with <code>toPrecision()</code> allows us to round the number to <code>2</code> decimal places without resorting to explicit multiplication or arithmetic operations. It provides a concise and straightforward approach to achieving the desired rounding effect.</p>
<blockquote>
<p>Note: It's important to note that <code>toPrecision()</code> method works based on significant digits rather than a specific decimal place.</p>
<p>Therefore, it may yield slightly different results when dealing with numbers that have trailing zeros or non-zero digits after the second decimal place.</p>
<p>For Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> number = <span class="hljs-number">0.3442</span>; 
<span class="hljs-built_in">console</span>.log(number.toPrecision(<span class="hljs-number">3</span>)); <span class="hljs-comment">// Output: 0.344</span>
</code></pre>
<p>In this example you can see we are getting <code>0.344</code> as output where our expected result is <code>0.30</code></p>
<p>So, be carefull of this thing when choosing this approach.</p>
</blockquote>
<h3 id="heading-mathtrunc-method">Math.trunc() method</h3>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc"><code>Math.trunc()</code></a> method, in combination with appropriate arithmetic operations, offers a concise solution for rounding numbers to 2 decimal places.</p>
<p>Let's explore the following example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> number = <span class="hljs-number">3.14159</span>; 
<span class="hljs-keyword">const</span> roundedNumber = <span class="hljs-built_in">Math</span>.trunc(number / <span class="hljs-number">0.01</span>) * <span class="hljs-number">0.01</span>;
<span class="hljs-built_in">console</span>.log(roundedNumber); <span class="hljs-comment">// Output: 3.14</span>
</code></pre>
<p>In this example, we begin by dividing the number by <code>0.01</code>. This operation effectively shifts the decimal places two positions to the left.</p>
<p>By doing so, we convert the number to an integer value, discarding the decimal portion.</p>
<p>Next, we apply the <code>Math.trunc()</code> function to the result of the division. <code>Math.trunc()</code> returns the integer part of a number and discards any fractional digits.</p>
<p>This step ensures that we retain only the whole number part obtained from the previous division.</p>
<p>Finally, we multiply the truncated number by <code>0.01</code> This multiplication restores the original decimal places, effectively rounding the number to 2 decimal places.</p>
<blockquote>
<p>Note: it's important to note that this method relies on integer manipulation and may not be suitable for all rounding scenarios.</p>
<p>Consider the specific requirements of your use case, such as handling negative numbers or ensuring consistent behavior with rounding rules, when selecting this approach.</p>
</blockquote>
<h3 id="heading-rounding-with-bitwise-operators">Rounding with Bitwise Operators</h3>
<p>So far, we have discussed 5 ways of rounding but all of these were using javascript built in methods. If you prefer a more customized approach, you can use <a target="_blank" href="https://www.w3schools.com/js/js_bitwise.asp">Bitwise operators</a> for doing that.</p>
<p>By using the bitwise <code>OR</code> operator (<code>|</code>) in combination with multiplication and division, you can effectively round the number.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> number = <span class="hljs-number">3.14159</span>; 
<span class="hljs-keyword">const</span> roundedNumber = (number * <span class="hljs-number">100</span> | <span class="hljs-number">0</span>) / <span class="hljs-number">100</span>; 
<span class="hljs-built_in">console</span>.log(roundedNumber); <span class="hljs-comment">// Output: 3.14</span>
</code></pre>
<p>In this example, we multiply the number by <code>100</code>, effectively shifting the decimal places 2 positions to the right.</p>
<p>Then, we apply the bitwise OR operation (<code>|</code>) with <code>0</code>. This bitwise operation converts the multiplied number to an integer by truncating the decimal portion.</p>
<p>Finally, we divide the truncated number by <code>100</code>, shifting the decimal places back to their original position, resulting in a rounded number with two decimal places.</p>
<blockquote>
<p>Note: it's important to note that bitwise operations are typically used for manipulating integer values and may not be as intuitive for rounding purposes.</p>
<p>While this method provides an alternative approach to rounding, it's crucial to consider the implications of using bitwise operators and the potential for unexpected behavior if applied incorrectly.</p>
<p>It's recommended to use bitwise rounding with caution and ensure it aligns with your specific requirements.</p>
</blockquote>
<h2 id="heading-things-to-consider">Things to Consider</h2>
<p>At this point of this article, we have learned 6 ways of rounding a number. But there are a few important factors to consider When rounding a number.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685261741541/f8895eb1-bbb4-40e0-96ae-4b1f99625fe9.webp" alt="Things to Consider when rounding a number" class="image--center mx-auto" /></p>
<p>Because if you don't consider these things it may occur complications in your code sometimes. Also, there are different ways to round a number and every way of rounding has its own pros and cons. These considerations will help you to find out which one fits best for your specific use case.</p>
<p>Let's explore some key considerations to keep in mind:</p>
<h3 id="heading-negative-numbers">Negative Numbers</h3>
<p>When rounding numbers to two decimal places in JavaScript, it's important to consider how negative numbers should be handled.</p>
<p>Depending on your specific use case and desired outcome, you may need to decide whether negative numbers should be rounded away from zero (upwards) or towards zero (downwards). If you want to round negative numbers away from zero, you can use the <code>Math.ceil()</code> function. This function always rounds up to the nearest greater or equal integer. When applied to negative numbers, it rounds them toward positive infinity.</p>
<p>For example:</p>
<p><code>-3.14 would be rounded to -3.00</code></p>
<p>On the other hand, If you prefer to round negative numbers toward zero, you can use the <code>Math.floor()</code> function. This function always rounds down to the nearest lesser or equal integer. When applied to negative numbers, it rounds them toward negative infinity.</p>
<p>For example:</p>
<p><code>-3.14 would be rounded to -4.00</code></p>
<p>Consider the specific requirements of your application and the desired behavior for negative numbers and choose the rounding approach that best aligns with your use case.</p>
<h3 id="heading-handling-nan-and-infinity">Handling NaN and Infinity</h3>
<p>When dealing with floating-point numbers in JavaScript, it's essential to handle special cases like <code>NaN</code> (Not a Number) and <code>Infinity</code>. These values can occur as a result of specific calculations or user input and can lead to unexpected results or errors if not properly handled.</p>
<p>Therefore, it's important to check for these special cases before performing any rounding operations.</p>
<p>Let's have a look at how can we handle these:</p>
<ul>
<li><p><code>NaN Detection</code>: Use the <code>isNaN()</code> function to check if a value is <code>NaN</code>. This function returns <code>true</code> if the value is <code>NaN</code> and <code>false</code> otherwise. By checking for <code>NaN</code> before rounding, you can handle this special case appropriately based on your application's requirements.</p>
</li>
<li><p><code>Infinity Detection</code>: To detect <code>Infinity</code>, you can use the <code>isFinite()</code> function. This function returns <code>true</code> if the value is a finite number (including negative and positive values) and <code>false</code> if it is <code>Infinity</code> or <code>NaN</code>. Similar to <code>NaN</code>, it is important to handle Infinity separately to avoid any unexpected behavior during rounding.</p>
</li>
</ul>
<p>By handling <code>NaN</code> and <code>Infinity</code> cases appropriately, you can prevent unexpected results or errors in your rounding logic. Implementing proper checks and error handling mechanisms will enhance the robustness and reliability of your code, ensuring that it can handle a wide range of input scenarios without encountering issues related to these special values.</p>
<h3 id="heading-intermediate-calculations">Intermediate Calculations</h3>
<p>When performing intermediate calculations before rounding numbers to 2 decimal places in JavaScript, you have two options to consider:</p>
<ul>
<li><p><code>Rounding at Each Step</code>: Rounding at each step involves rounding the intermediate result at every calculation step. This approach helps maintain accuracy throughout the calculations by minimizing rounding errors. It is particularly useful for complex calculations that involve multiple arithmetic operations.<br />  However, rounding at each step may increase computational overhead and potentially impact performance, especially when dealing with a large number of intermediate calculations.</p>
</li>
<li><p><code>Rounding at the End</code>: Rounding at the end means performing the rounding operation after all the intermediate calculations are completed. This approach can be more efficient, especially for simpler calculations or cases where the rounding precision requirement is not critical at each intermediate step.<br />  By rounding at the end, you reduce the number of rounding operations performed and potentially improve performance.<br />  However, it's important to be aware that rounding errors may accumulate throughout the intermediate calculations, which can impact the final result.</p>
</li>
</ul>
<p>The choice between rounding at each step or rounding at the end depends on the complexity of your calculations, the level of accuracy required, and the performance considerations of your specific use case.</p>
<p>It is recommended to conduct thorough testing and validation to determine which approach yields the desired accuracy and performance characteristics for your application.</p>
<p>By carefully considering the timing of rounding during intermediate calculations, you can strike a balance between accuracy and efficiency, ensuring that your rounded results are both precise and reliable.</p>
<h3 id="heading-precision-and-data-integrity">Precision and Data Integrity</h3>
<p>When rounding numbers in JavaScript, it's important to consider the precision and data integrity implications. Rounding introduces a level of imprecision, which can impact the accuracy of calculations and data analysis.</p>
<p>While rounding to two decimal places improves readability and is commonly used for display purposes, it's crucial to assess whether this level of precision is acceptable for your specific application.</p>
<p>Depending on the nature of your data and the requirements of your calculations, you may need higher precision to maintain data integrity.</p>
<p>To determine the right precision level:</p>
<ul>
<li><p><code>Check Application Requirements</code>: Different applications have different precision needs. Evaluate your specific requirements, such as financial data, scientific calculations, or statistical analysis.</p>
</li>
<li><p><code>Assess Calculation Accuracy</code>: Complex calculations or intermediate steps may benefit from rounding at each stage, while simpler operations can be rounded at the end for efficiency.</p>
</li>
<li><p><code>Consider Data Sensitivity</code>: Determine if small deviations are significant in your context. If precision is crucial for data analysis or decision-making, higher decimal places or alternative methods may be needed.</p>
</li>
</ul>
<p>By considering these factors, you can choose the appropriate rounding method that meets your needs and maintains accuracy in your calculations.</p>
<h3 id="heading-consistency-and-communication">Consistency and Communication</h3>
<p>Maintaining consistency in rounding practices is of paramount importance to ensure accurate interpretation and avoid confusion in your application. When rounding numbers to two decimal places in JavaScript, it's crucial to establish clear and consistent rounding rules throughout your codebase. To maintain consistency, follow these guidelines:</p>
<ul>
<li><p><code>Document Rounding Approach</code>: Clearly document and communicate the rounding method and precision used in your JavaScript code. Share this information with developers, testers, and future maintainers so that everyone understands how rounding is handled.</p>
</li>
<li><p><code>Consider Context-Specific Rules</code>: Be aware of any industry or domain-specific rules or regulations regarding rounding. Align your rounding approach with these guidelines, especially in areas such as finance or currency calculations.</p>
</li>
<li><p><code>Maintain Consistency Across the Application</code>: Apply the same rounding method and precision consistently throughout your application. This ensures that the interpretation of rounded values remains uniform and avoids confusion caused by inconsistent rounding practices.</p>
</li>
<li><p><code>Update Documentation and Communicate Changes</code>: Keep your rounding documentation up to date and communicate any changes or refinements to the rounding methodology. This ensures that all stakeholders are aware of the updates and can adjust their understanding accordingly.</p>
</li>
</ul>
<p>By following these principles, you can establish a reliable and consistent rounding approach in your JavaScript code, promoting accuracy and clarity in the interpretation of rounded numbers.</p>
<h3 id="heading-localization-and-internationalization">Localization and Internationalization</h3>
<p>When rounding numbers, it's essential to consider the localization and internationalization aspects. Rounding conventions can vary across different regions and languages, and it's important to be aware of specific rounding rules or cultural expectations that may apply to your target audience.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685263526706/8d8dd0d9-2589-4404-b803-8f3594ba1ddc.webp" alt="Localization and Internationalization" class="image--center mx-auto" /></p>
<p>If your application supports multiple locales, it's crucial to ensure that the rounding behavior aligns with the conventions of the selected locale.</p>
<p>Here are some key points to consider:</p>
<ul>
<li><p><code>Regional Rounding Conventions</code>: Different regions may have different ways of rounding numbers. It's important to understand the rounding practices in your target regions to ensure accuracy and cultural appropriateness.</p>
</li>
<li><p><code>Language and Presentation</code>: Rounding can affect how numbers are presented in different languages. Pay attention to language-specific nuances and present rounded numbers in a culturally and linguistically appropriate manner.</p>
</li>
<li><p><code>Locale-specific Formatting</code>: Follow the formatting conventions of the selected locale when displaying rounded numbers, including decimal and thousand separators, currency symbols, and other numeric representations.</p>
</li>
<li><p><code>Localization Libraries and APIs</code>: Use localization libraries and APIs in JavaScript to handle localized rounding and number formatting. These tools simplify the implementation of localized rounding based on specific locales.</p>
</li>
<li><p><code>User Preferences</code>: Consider allowing users to customize the rounding behavior to meet their preferences, as some users may have specific rounding requirements based on their cultural or professional context.</p>
</li>
</ul>
<p>By considering localization and internationalization aspects in rounding numbers, you ensure that your application respects cultural conventions, meets user expectations, and provides a seamless experience for users from different regions and languages. Adapting rounding behavior and number presentation to the specific locale creates a more inclusive and user friendly application.</p>
<h3 id="heading-testing-and-validation">Testing and Validation</h3>
<p>Testing and validating your rounding implementation is crucial to ensure that it performs as expected in various scenarios. By conducting thorough tests, including edge cases and boundary values, you can verify the accuracy and consistency of the rounding results.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685263173797/5fad152f-4161-45e2-bc32-3ef3a4459bf0.webp" alt="Testing and Validation" class="image--center mx-auto" /></p>
<p>Consider the following points when testing and validating your rounding implementation:</p>
<ul>
<li><p><code>Test Coverage</code>: Design test cases that cover a wide range of input values, including both positive and negative numbers. Test scenarios that involve rounding up, rounding down, and rounding to the nearest value. Include edge cases such as numbers close to the rounding thresholds and extreme values to ensure your implementation handles them correctly.</p>
</li>
<li><p><code>Consistency Checks</code>: Validate that the rounding results are consistent across multiple rounds of testing. Run the same set of tests multiple times to ensure the output remains the same. This helps identify any non-deterministic behavior or inconsistencies in the rounding process.</p>
</li>
<li><p><code>Boundary Values</code>: Pay special attention to test cases involving boundary values. These are values that are close to the rounding thresholds, such as numbers ending in <code>.005</code> or <code>.995</code>.<br />  Verify that the rounding behavior aligns with your desired outcome and adheres to the rounding rules you've defined.</p>
</li>
<li><p><code>Comparison to Expected Results</code>: For each test case, compare the rounding results to the expected outcomes. This can be done manually or through automated assertions.<br />  Ensure that the rounded values match your expectations, considering factors such as the rounding method, precision, and specific rounding rules.</p>
</li>
<li><p><code>Automated Testing</code>: Implement automated tests using testing frameworks or libraries available in JavaScript. Automated tests can be run repeatedly and integrated into your development workflow, providing efficient and consistent validation of your rounding implementation.<br />  Consider writing unit tests, integration tests, or even end-to-end tests that cover rounding scenarios across different parts of your application.</p>
</li>
<li><p><code>Validation with Real World Data</code>: If possible, validate your rounding implementation using real-world data or datasets representative of your application's usage. This can help identify any issues or unexpected behavior that may arise when dealing with actual data.</p>
</li>
<li><p><code>Performance Considerations</code>: Assess the performance impact of your rounding implementation, especially if it's applied to a large number of data points or performed in computationally intensive calculations.<br />  Measure the execution time and resource consumption to ensure that the rounding process is efficient and does not introduce significant bottlenecks in your application.</p>
</li>
</ul>
<p>By following these testing practices, you can ensure the accuracy, consistency, and performance of your rounding implementation, giving you confidence in its reliability and suitability for your application.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Rounding numbers to desired decimal places is a common requirement in JavaScript, and having control over precision is essential for accurate calculations and data representation.</p>
<p>In this blog post, we've explored 6 different ways to do that. Each way of rounding offers a way to achieve the desired rounding effect. Depending on your specific use case, you can choose the method that best suits your needs.</p>
<p>Remember to practice and experiment with these techniques to deepen your understanding and proficiency. With experience, you'll unlock their full potential and discover even more creative ways to enhance the functionality of your JavaScript applications. Keep exploring and refining your skills to become a more adept JavaScript developer.</p>
<p>Happy coding :)</p>
]]></content:encoded></item><item><title><![CDATA[Javascript hasOwnProperty:  A Powerful Property Checking tool]]></title><description><![CDATA[Introduction
Javascript hasOwnProperty method is a built-in function in JavaScript that allows you to check whether an object has a specific property. This method is particularly important when you want to determine if a property exists directly on a...]]></description><link>https://robiul.dev/javascript-hasownproperty-method</link><guid isPermaLink="true">https://robiul.dev/javascript-hasownproperty-method</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[JavaScript Object Methods]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Thu, 25 May 2023 14:27:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1685013181925/3c031390-62c2-4d65-8b74-c29e81edfc82.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p><strong>Javascript hasOwnProperty</strong> method is a built-in function in JavaScript that allows you to check whether an object has a specific property. This method is particularly important when you want to determine if a property exists directly on an object and not on its <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes">prototype chain</a>(not inherited from its prototype).</p>
<p>This statement can be confusing. right?</p>
<p>Don't get panic, I am here to make you understand this in a very easy and efficient way.</p>
<p>In this article, we will explore the <code>hasOwnProperty()</code> method in detail, discussing its purpose and significance in property checking. We will deep dive into its syntax, purpose, and various scenarios where it can be applied.</p>
<p>By the end, you'll have a solid understanding of how to effectively utilize the <code>hasOwnProperty()</code> method in your JavaScript projects.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before diving into the concepts of <strong>javascript hasOwnProperty</strong> method, it's beneficial to have a basic understanding of JavaScript and its fundamental concepts. Familiarity with <a target="_blank" href="https://robiul.dev/javascript-variables-beginner-thinking">javascript variables</a>, functions, and basic control flow (such as if statements and <a target="_blank" href="https://robiul.dev/javascript-loop-best-practices-for-optimal-performance">loops</a> will make it easier to grasp the concepts discussed in this article.</p>
<p>If you're new to JavaScript or need a refresher, there are a few online resources available to learn the basics. Websites like <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript">MDN Web Docs</a>, <a target="_blank" href="https://www.w3schools.com/js/">W3Schools</a>, and <a target="_blank" href="https://www.freecodecamp.org/">freeCodeCamp</a> offer comprehensive tutorials and guides that can help you get started on your JavaScript journey.</p>
<p>Additionally, I highly recommend the following two books for beginners in JavaScript:</p>
<ul>
<li><p><a target="_blank" href="https://amzn.to/3IESIOn">Head First JavaScript Programming: A Brain-Friendly Guide</a></p>
</li>
<li><p><a target="_blank" href="https://amzn.to/3IGbjJN">JavaScript: The Definitive Guide: Master the World's Most-Used Programming Language</a></p>
</li>
</ul>
<p>By diving into these resources, you'll gain a solid foundation in JavaScript programming, equipping you with the necessary knowledge to explore the intricacies of hasOwnProperty and unlock new possibilities in your web development projects.</p>
<p>So, before we dive into the intricacies of javascript hasOwnProperty, make sure you have a solid foundation in JavaScript programming.</p>
<p>Once you're ready, let's explore the power of <strong>hasOwnProperty method</strong> and unlock new possibilities in your web development projects.</p>
<h2 id="heading-syntax-and-parameters">Syntax and parameters</h2>
<p>To effectively utilize the <strong>JavaScript hasOwnProperty</strong> method, the First thing we need to do is getting know its syntax and get used to it by understanding its syntax and parameters in detail.</p>
<p>let's explore the syntax of it.</p>
<blockquote>
<p>Note: If you find the syntax confusing, don't worry! In the upcoming sections of this article, we will explore various examples and use cases. I assure you that by reading the full article, you will gain a clear understanding of how to use hasOwnProperty() effectively. So, be patient and keep reading to unlock the full potential of this powerful JavaScript method.</p>
</blockquote>
<p>The <code>hasOwnProperty() method</code> follows the following syntax:</p>
<pre><code class="lang-javascript">object.hasOwnProperty(property)
</code></pre>
<p>Here,</p>
<ul>
<li><p><code>object</code>: This parameter represents the object on which the property check is performed. It can be any JavaScript object, including built-in objects, user-defined objects, or instances of classes.</p>
</li>
<li><p><code>property</code>: This parameter specifies the name of the property being checked. It should be a string representing the property name.</p>
</li>
<li><p><code>return value</code>: The hasOwnProperty() method returns a boolean value indicating whether the object has the specified property. It returns true if the object has the property, and false otherwise.</p>
</li>
</ul>
<blockquote>
<p>The <code>hasOwnProperty() method</code> returns true if the specified property is a direct property of the object — even if the value is null or undefined. The method returns false if the property is inherited, or has not been declared at all. Which we will discuss in later sections.</p>
</blockquote>
<h2 id="heading-working-with-hasownproperty">Working with hasOwnProperty()</h2>
<p>Now we know the syntax of the javascript hasOwnProperty() method, let's look at an example of how to apply it in practical code.</p>
<p>let's consider an object called myObject:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> person = {   <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>,   <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> }
</code></pre>
<p>To check if myObject has the property named <code>name</code> and <code>gender</code>, we would use the <strong>hasOwnProperty() method</strong> as follows:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(person.hasOwnProperty(<span class="hljs-string">'name'</span>)) <span class="hljs-comment">// Output: true </span>
<span class="hljs-built_in">console</span>.log(person.hasOwnProperty(<span class="hljs-string">'gender'</span>)) <span class="hljs-comment">// Output: false</span>
</code></pre>
<p>In the above example, the person object has the properties <code>name</code> and <code>age</code>. The first <code>console.log()</code> statement checks if the object has the <code>name</code> property, and since the person object has the name property it returns <code>true</code>.</p>
<p>On the other hand, The second <code>console.log()</code> statement checks if the object has the <code>gender</code> property, and it returns <code>false</code> because the object does not have that property.</p>
<p>pretty straightforward. right?</p>
<p>Not really!</p>
<h2 id="heading-handling-inherited-properties">Handling inherited properties</h2>
<p>In the previous section, we have seen that <strong>javascript hasOwnProperty</strong> method behaves in a very straightforward manner when we are checking for a property of the object.</p>
<p>But it works differently when we check for an inherited property of an object.</p>
<p>We know that In JavaScript, objects can inherit properties from their prototypes through the prototype chain. This inheritance behavior brings the importance of the <code>hasOwnProperty() method</code> into the spotlight, especially when dealing with <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain">inherited properties</a>.</p>
<p>The hasOwnProperty() method ignores inherited properties. It focuses solely on the properties directly owned by the object itself.</p>
<p>When you invoke hasOwnProperty() on an object, it evaluates whether the object possesses a non-inherited property with the specified name. If such a property exists, the method returns <code>true</code>; otherwise, it returns <code>false</code>.</p>
<p>This method serves as a reliable indicator of whether an object has a specific property, regardless of its inheritance.</p>
<p>To clarify, consider the following example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {   <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>,   <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> }  
<span class="hljs-built_in">console</span>.log(person.hasOwnProperty(<span class="hljs-string">'name'</span>)) <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(person.hasOwnProperty(<span class="hljs-string">'toString'</span>)) <span class="hljs-comment">// Output: false</span>
</code></pre>
<p>In this example, we have an object called <code>person</code> with properties <code>name</code> and <code>age</code>. When we call <code>hasOwnProperty()</code> on the <code>person</code> object with <code>name</code> as the argument, it returns <code>true</code> since 'name' is a direct property owned by the object itself.</p>
<p>However, when we call <code>hasOwnProperty()</code> with <code>toString</code> as the argument, it returns <code>false</code> because <code>toString</code> is an inherited property from the object's prototype.</p>
<h2 id="heading-purpose-of-hasownproperty">Purpose of hasownproperty()</h2>
<p>At this point of this article after understanding the behavior of <strong>javascript hasOwnProperty</strong>, you might be thinking what is the purpose of it, more specifically why do we need it?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685023134668/68635a42-a099-4b1e-bc77-67378d92d80c.webp" alt="Purpose of hasownproperty()" class="image--center mx-auto" /></p>
<p>Let's find out the answer. Probably you have heard the statement</p>
<blockquote>
<p><strong>everything is object in javascript</strong>.</p>
</blockquote>
<p>What does it mean actually?</p>
<p>of course, we won't discuss its full explanation here.</p>
<p>In short, This means you can treat almost anything as an object in javascript. This includes numbers, strings, functions, and even arrays. And since almost anything can be treated as <a target="_blank" href="https://blog.bitsrc.io/the-chronicles-of-javascript-objects-2d6b9205cd66#:~:text=Almost%20everything%20in%20JavaScript%20is,primitive%20values%20or%20primitive%20types.">object</a>, they also inherit properties from their parent objects through the prototype chain as an Object does.</p>
<p>That's why When working with objects, it can be challenging to differentiate between properties that are locally defined and those inherited from prototypes.</p>
<p>To address this, JavaScript provides the <strong>hasOwnProperty() method</strong>, which allows you to determine if a property exists directly on an object or is inherited from its prototype chain.</p>
<p>By using hasOwnProperty(), we ensure that we don't unintentionally modify any inherited properties or methods. It allows us to safely customize the behavior according to our requirements without affecting properties inherited from the prototype chain.</p>
<p>Here's an example to illustrate this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {
   <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>,   <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> 
}  
<span class="hljs-keyword">if</span> (person.hasOwnProperty(<span class="hljs-string">'greet'</span>)) {
   person.greet = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, my name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>)   
  } 
}  

person.greet() <span class="hljs-comment">// Output: Hello, my name is John</span>
</code></pre>
<p>In this example, we have an object called <code>person</code> with properties like <code>name</code> and <code>age</code>. We want to customize the <code>greet()</code> method to provide a personalized greeting.</p>
<p>Using <code>hasOwnProperty()</code>, we check if the <code>greet</code> property already exists directly on the person object. If it does, we override the existing method with a new implementation that says <code>Hello, my name is John</code> In that way we are ensuring that we don't unintentionally modify inherited <code>greed</code> method in the <code>person</code> object.</p>
<blockquote>
<p>Note: In some browsers where it is supported, Object.hasOwn() is recommended over hasOwnProperty().</p>
</blockquote>
<h2 id="heading-hasownproperty-on-different-javascript-objects">hasOwnProperty() on Different JavaScript Objects</h2>
<p><strong>javascript hasOwnProperty</strong> method can be called on various JavaScript objects since most objects inherit its methods.</p>
<p>For example, let's consider the Array object. Since Array is an object itself, you can use the <code>hasOwnProperty()</code> method to check the existence of an index within the array:</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">'Watermelon'</span>, <span class="hljs-string">'Orange'</span>] 
<span class="hljs-built_in">console</span>.log(fruits.hasOwnProperty(<span class="hljs-number">3</span>)) <span class="hljs-comment">// Output: true (corresponding to 'Orange') </span>
<span class="hljs-built_in">console</span>.log(fruits.hasOwnProperty(<span class="hljs-number">4</span>)) <span class="hljs-comment">// Output: false (index not defined)</span>
</code></pre>
<p>In this example, the <code>fruits</code> array contains several elements. By calling <code>hasOwnProperty()</code> on the array object with the argument <code>3</code>, it returns true because the element at index <code>3</code> (<code>Orange</code>) exists within the array.</p>
<p>On the other hand, calling <code>hasOwnProperty()</code> with the argument <code>4</code> returns <code>false</code> because the array does not have an element at that index.</p>
<p>The ability to use <code>hasOwnProperty()</code> on arrays allows you to verify the presence of specific indices or elements within the array. It provides a convenient way to check the existence of array elements, ensuring that you access valid and defined values.</p>
<h2 id="heading-objects-where-hasownproperty-is-unavailable">Objects where hasOwnProperty() is unavailable</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1685023078861/4a46a482-3431-465d-a838-0e9937bc12d9.webp" alt="Objects where hasOwnProperty() is unavailable" class="image--center mx-auto" /></p>
<p>Although the <strong>javascript hasOwnProperty</strong> method is generally available in most JavaScript objects, there are certain cases where it may not be accessible.</p>
<h3 id="heading-hasownproperty-as-a-property-name">hasOwnProperty as a property name</h3>
<p>If an object redefines or overrides the <code>hasOwnProperty()</code> method, the original implementation from <code>Object.prototype</code> will not be available.</p>
<p>Here's an illustration of this scenario:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> customObj = {
   <span class="hljs-attr">hasOwnProperty</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">'Custom hasOwnProperty'</span>  
   } 
}
customObj.hasOwnProperty(<span class="hljs-string">'prop'</span>) <span class="hljs-comment">// 'Custom hasOwnProperty'</span>
</code></pre>
<p>In this case, the <code>customObj</code> object has its own implementation of <code>hasOwnProperty()</code>, which returns a custom message instead of the usual behavior.</p>
<p>As a result, when trying to call <code>hasOwnProperty()</code> on <code>customObj</code>, output will be the text(<code>Custom hasOwnProperty</code>) returned from the custom <code>hasOwnProperty</code> function.</p>
<h3 id="heading-object-created-using-objectcreatenull">Object created using Object.create(null)</h3>
<p>Another scenario where <code>hasOwnProperty()</code> may not be accessible is when an object is created using <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create"><code>Object.create(null)</code></a>. Objects created this way do not inherit from <code>Object.prototype</code>, and therefore do not have access to its methods, including <code>hasOwnProperty()</code>.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> foo = <span class="hljs-built_in">Object</span>.create(<span class="hljs-literal">null</span>) 
foo.prop = <span class="hljs-string">'exists'</span> 
foo.hasOwnProperty(<span class="hljs-string">'prop'</span>) <span class="hljs-comment">// Error: foo.hasOwnProperty is not a function</span>
</code></pre>
<p>In this case, foo is created using <code>Object.create(null)</code>, which explicitly specifies that the object should not inherit from <code>Object.prototype</code>.</p>
<p>As a result, calling <code>hasOwnProperty()</code> on foo will throw an error because the method is not available.</p>
<blockquote>
<p>Note: To handle these cases, you can use alternative approaches. One option is to use <strong>Object.hasOwn()</strong> method, which is a safer alternative that works even in situations where hasOwnProperty() may not be available.</p>
<p>Another option is to use hasOwnProperty() from another object that does inherit from Object.prototype, such as a plain {} object.</p>
</blockquote>
<p>It's important to be aware of these scenarios and handle them accordingly to ensure your code functions as intended and avoids any unexpected errors or inconsistencies.</p>
<h2 id="heading-handling-non-object-values">Handling non-object values</h2>
<p>When the <strong>javascript hasOwnProperty</strong> method is invoked on non-object values, such as primitive data types or null, its behavior differs from when it is used on actual objects. It's important to understand these differences and the impact they have on property checks.</p>
<p>When <code>hasOwnProperty()</code> is called on a non-object value, the method will create a temporary wrapper object of the corresponding type and check for the existence of the property. If the property exists directly on the wrapper object, <code>hasOwnProperty()</code> will return <code>true</code>. Otherwise, it will return false.</p>
<p>Here's how <code>hasOwnProperty()</code> behaves with different types of values:</p>
<ul>
<li><p><code>String Primitive</code>:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> name = <span class="hljs-string">'John'</span> 
  <span class="hljs-built_in">console</span>.log(name.hasOwnProperty(<span class="hljs-string">'length'</span>)) <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>  In this case, the name variable is a string primitive. When <code>hasOwnProperty()</code> is called on it, JavaScript automatically converts it into a temporary String object. The String object has a property named <code>length</code> that it directly owns, so the method returns <code>true</code>.</p>
</li>
<li><p><code>Number Primitive</code>:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> age = <span class="hljs-number">30</span> <span class="hljs-built_in">console</span>.log(age.hasOwnProperty(<span class="hljs-string">'toString'</span>)) <span class="hljs-comment">// Output: false</span>
</code></pre>
<p>  Here, the age variable is a number primitive. When <code>hasOwnProperty()</code> is called on it, it is converted into a temporary Number object.<br />  The Number object doesn't have a property named <code>toString</code> that it directly owns, so the method returns <code>false</code>.</p>
</li>
<li><p><code>Boolean Primitive</code>:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> isValid = <span class="hljs-literal">true</span> 
  <span class="hljs-built_in">console</span>.log(isValid.hasOwnProperty(<span class="hljs-string">'valueOf'</span>)) <span class="hljs-comment">// Output: false</span>
</code></pre>
<p>  In this example, the <code>isValid</code> variable is a boolean primitive. When <code>hasOwnProperty()</code> is called on it, it is converted into a temporary Boolean object. The Boolean object doesn't have a property named <code>valueOf</code> that it directly owns, so the method returns <code>false</code>.</p>
</li>
<li><p><code>Null and Undefined</code>:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">let</span> obj = <span class="hljs-literal">null</span> 
  <span class="hljs-built_in">console</span>.log(obj.hasOwnProperty(<span class="hljs-string">'property'</span>)) <span class="hljs-comment">// Output: TypeError: Cannot convert null to object  let value </span>
  <span class="hljs-built_in">console</span>.log(value.hasOwnProperty(<span class="hljs-string">'property'</span>)) <span class="hljs-comment">// Output: TypeError: Cannot convert undefined to object</span>
</code></pre>
<p>  When <code>hasOwnProperty()</code> is called on <code>null</code> or <code>undefined</code> values, a TypeError is thrown. These values cannot be converted to objects, so invoking <code>hasOwnProperty()</code> directly on them results in an error.</p>
</li>
</ul>
<p>It's important to be aware of how <code>hasOwnProperty()</code> behaves with different data types to ensure accurate property checks and handle any potential errors that may arise.</p>
<p>To avoid these errors, it is recommended to perform a type check before using the hasOwnProperty() method.</p>
<p>You can use the <code>typeof</code> operator to determine if the value is an object before calling <code>hasOwnProperty()</code>.</p>
<p>For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj = { <span class="hljs-attr">prop</span>: <span class="hljs-string">'value'</span> } 
<span class="hljs-keyword">const</span> str = <span class="hljs-string">'Hello'</span>  

<span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> obj === <span class="hljs-string">'object'</span> &amp;&amp; obj.hasOwnProperty(<span class="hljs-string">'prop'</span>)) {           
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Object has own property 'prop'"</span>) 
}  

<span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> str === <span class="hljs-string">'object'</span> &amp;&amp; str.hasOwnProperty(<span class="hljs-string">'length'</span>)) {  
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"String has own property 'length'"</span>) 
} <span class="hljs-keyword">else</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Value is not an object or does not have own property 'length'"</span>) 
}
</code></pre>
<p>In this example, we first check if obj is of type <code>object</code> and then use <code>hasOwnProperty()</code> to determine if it has the property <code>prop</code>.</p>
<p>Similarly, we perform the same check for str to verify if it is of type <code>object</code> and has the property <code>length</code>. If the conditions are met, the corresponding success message is logged.</p>
<p>Otherwise, if the value is not an object or doesn't have the expected property, an appropriate error message is displayed.</p>
<p>By performing the type check before calling <code>hasOwnProperty()</code>, you ensure that the method is only invoked on valid object values, mitigating any potential errors that could occur.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p><strong>Javascript hasOwnProperty</strong> method is a useful tool for checking the existence of properties on objects. This provides more control and accuracy when performing property checks and manipulations.</p>
<p>Now that you have a solid understanding of <code>hasOwnProperty()</code>, you have a powerful tool at your disposal to handle property-related tasks with precision.</p>
<p>By leveraging this method, you can confidently work with object properties, tailor their behavior, and create more robust and reliable JavaScript applications.</p>
<p>Remember to practice and experiment with <code>hasOwnProperty()</code> to further deepen your understanding and proficiency. As you gain experience, you'll unlock its full potential and discover even more creative ways to enhance the functionality of your JavaScript applications.</p>
<h2 id="heading-resource">Resource</h2>
<ul>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty">Object.prototype.hasOwnProperty()</a></p>
</li>
<li><p><a target="_blank" href="https://flexiple.com/javascript/hasownproperty-javacript/"><strong>Javascript hasownproperty method</strong></a></p>
</li>
<li><p><a target="_blank" href="https://idiallo.com/javascript/object-hasown-property-use-case-example">When to use Object.hasOwnProperty</a></p>
</li>
<li><p><a target="_blank" href="https://docs.w3cub.com/javascript/global_objects/object/hasownproperty">Object.prototype.hasOwnProperty()</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[forEach method in JavaScript - A Comprehensive Guide]]></title><description><![CDATA[Introduction
forEach method In JavaScript is an essential component that simplifies the process of iterating over elements in an array. It provides a convenient and straightforward way to perform actions on each element without using the traditional ...]]></description><link>https://robiul.dev/foreach-method-in-javascript-a-comprehensive-guide</link><guid isPermaLink="true">https://robiul.dev/foreach-method-in-javascript-a-comprehensive-guide</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[programming languages]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Mon, 22 May 2023 02:00:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684956064300/e8dfd88e-b009-415e-a16d-88ea97d062d1.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>forEach method In JavaScript is an essential component that simplifies the process of iterating over elements in an array. It provides a convenient and straightforward way to perform actions on each element without using the traditional loop.</p>
<p>With its ease of use and versatility, it allows developers to perform operations on each element individually, such as accessing its value, modifying it, or invoking other functions based on specific conditions.</p>
<p>In this comprehensive blog post, we will dive deep into the <code>forEach</code> method, and try to understand its concepts through practical examples.</p>
<p>By the end, you'll have a solid understanding of how to leverage the full potential of forEach in your JavaScript projects, enhancing your coding skills and productivity.</p>
<p>So let's dive into the world of forEach and unlock its capabilities together!</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before diving into the world of forEach, it's very important to have a basic understanding of JavaScript fundamentals, arrays, functions, and iteration concepts.</p>
<p>I assume you are familiar with fundamental topics such as variables, data types, operators, control flow, array properties and methods, function definition and invocation, and loops and conditional statements.</p>
<p>Before reading the full article please make sure you understand these topics. Because without having knowledge of these topics there is a high chance you won't understand the examples I have used in this article.</p>
<p>Additionally, If you're new to JavaScript or need a refresher, there are few online resources available to learn the basics.</p>
<p>Websites like <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript">MDN Web Docs</a>, <a target="_blank" href="https://www.w3schools.com/js/">W3Schools</a>, and <a target="_blank" href="https://www.freecodecamp.org/">freeCodeCamp</a> offer comprehensive tutorials and guides that can help you get started on your JavaScript journey.</p>
<p>Also, I highly recommend the following two books for beginners in JavaScript:</p>
<ul>
<li><p><a target="_blank" href="https://amzn.to/3BHIXem">Head First JavaScript Programming: A Brain-Friendly Guide</a></p>
</li>
<li><p><a target="_blank" href="https://amzn.to/3MIM0Jw">JavaScript: The Definitive Guide: Master the World's Most-Used Programming Language</a></p>
</li>
</ul>
<p>By diving into these resources, you'll gain a solid foundation in JavaScript programming and acquire the skills required to explore the world of forEach method in JavaScript and open up new opportunities for your web development projects.</p>
<h2 id="heading-understanding-the-purpose-of-foreach">Understanding the purpose of forEach</h2>
<p>To study and explore the forEach method in-depth, it's crucial to understand its purpose first. Because It may seem pointless to go into its details before understanding the goal.</p>
<p>So, let's take a moment to understand why the <code>forEach</code> method exists and what it aims to achieve.</p>
<p>The purpose of the <strong>forEach method in JavaScript</strong> is to simplify the process of iterating over elements in an array and performing an action on each element. It provides a more elegant and expressive alternative to traditional <a target="_blank" href="https://www.w3schools.com/js/js_loop_for.asp"><code>for loops</code></a>, making code more readable and concise.</p>
<p>By using the forEach method in JavaScript, you can avoid the hassle of manually managing everything and focus on the logic you want to execute for each array element. It abstracts away the low-level details of iteration and allows you to concentrate on the specific operation you wish to perform.</p>
<p>For example, consider an array of names:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> names = [<span class="hljs-string">'Alice'</span>, <span class="hljs-string">'Bob'</span>, <span class="hljs-string">'Charlie'</span>]
</code></pre>
<p>If you wanted to print each name to the console using a traditional <code>for loop</code>, you would need to handle the index and access the array elements explicitly:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; names.length; i++) {
   <span class="hljs-built_in">console</span>.log(names[i]) 
}
</code></pre>
<p>However, with the forEach method, the syntax becomes much more straightforward:</p>
<pre><code class="lang-javascript">names.forEach(<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(name) 
})
</code></pre>
<blockquote>
<p>Note: If you're feeling confused about the syntax of the <code>forEach</code> method at this point, don't worry! We will dive into the syntax and explain all its parameters using examples.</p>
<p>So, please be patient and read the full article until the end. We'll make sure everything becomes clear and understandable.</p>
</blockquote>
<p>The <code>forEach</code> method abstracts away the index management, providing a clean and concise way to iterate over the array and execute the desired action for each element. It simplifies the code structure, enhances readability, and reduces the chances of introducing errors.</p>
<p>So, by understanding the purpose of the forEach method, you can appreciate its value and leverage it effectively in your JavaScript projects. It serves as a powerful tool for iterating over arrays and performing actions on each element, making your code more elegant and efficient.</p>
<h2 id="heading-syntax-and-parameters">Syntax and parameters</h2>
<p>The syntax of forEach is quite straightforward. It follows this format:</p>
<pre><code class="lang-javascript">array.forEach(callback(currentValue, index, array), thisArg)
</code></pre>
<p>The key component of forEach is the <code>callback</code> function, which is executed for each element in the array. It plays a vital role in defining the actions to be performed on each element.</p>
<p>The callback function accepts three parameters:</p>
<ul>
<li><p><code>currentValue</code></p>
</li>
<li><p><code>index</code></p>
</li>
<li><p><code>array</code></p>
</li>
</ul>
<p>These parameters provide valuable information during the iteration process.</p>
<p>The callback function allows you to define the actions to be performed on each element during the iteration.</p>
<p>The <code>currentValue</code> parameter represents the current element being processed, while the <code>index</code> parameter provides the index of the current element. The <code>array</code> parameter refers to the array on which the <code>forEach</code> method is being called.</p>
<p>Additionally, you can optionally specify the <code>thisArg</code> parameter to determine the value of this within the <code>callback</code>.</p>
<p>By utilizing the callback function and these parameters effectively, you can perform custom operations on each element of the array, such as modifying the values, accessing properties, or invoking other functions.</p>
<p>Now that we have learned the syntax of the forEach method in JavaScript, let's explore how to work with it and understand its functionality in the next sections.</p>
<h2 id="heading-defining-and-passing-callbacks-to-foreach">Defining and passing callbacks to forEach</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684956086196/32314a50-34fe-4a19-bd44-4915116fd481.webp" alt="Defining and passing callbacks to forEach (robiul.dev)" class="image--center mx-auto" /></p>
<p>To use the <code>forEach</code> method, you need to define and pass a <a target="_blank" href="https://www.w3schools.com/js/js_callback.asp">callback function</a> as its parameter. This callback function will be invoked for each element in the array.</p>
<p>There are two common ways to define the callback function:</p>
<ul>
<li><p>Inline function</p>
</li>
<li><p>named function</p>
</li>
</ul>
<p>Let's see how we can use the Inline function as the callback through an example:</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>]  
numbers.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">element</span>) </span>{
   <span class="hljs-built_in">console</span>.log(element) 
})
</code></pre>
<p>In the above example, we define an inline callback function directly as an argument to the forEach method. This function takes an element parameter, representing each element in the numbers array.</p>
<p>By using inline callback functions, you can keep the code concise and avoid the need for defining separate named functions. Inline functions are particularly useful for simple operations that don't require reusability.</p>
<p>Now let's see Passing a named function as the callback:</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-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logElement</span>(<span class="hljs-params">element</span>) </span>{
   <span class="hljs-built_in">console</span>.log(element) 
}  

numbers.forEach(logElement)
</code></pre>
<p>In the above example, we define a named function <code>logElement</code> that takes an element parameter. We then pass this named function as an argument to the <code>forEach</code> method.</p>
<p>Passing a named function is useful when you have complex or reusable operations that you want to separate from the <code>forEach</code> loop. It enhances code modularity and allows you to reuse the same function in other parts of your codebase.</p>
<blockquote>
<p>Note: Whether you choose to define the callback function inline or as a named function depends on the complexity and reusability of the operations you need to perform on each element. Both approaches are valid and provide flexibility in how you work with the <code>forEach</code> method.</p>
</blockquote>
<h2 id="heading-accessing-element-index-and-original-array-within-the-callback">Accessing element, index, and original array within the callback</h2>
<p>When working with the forEach method in JavaScript, the parameters of the <code>forEach</code> method allows you to access and work with the current element, index, and the original array within the callback function.</p>
<p>Let's explore how to use each parameter effectively:</p>
<ul>
<li><p><code>Current Element (element)</code>: The first parameter of the callback function represents the current element being processed. You can use this parameter to perform actions or operations on each element individually.<br />  For example:</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">'orange'</span>];  

  fruits.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">fruit</span>) </span>{
     <span class="hljs-built_in">console</span>.log(fruit); 
  });
</code></pre>
<p>  In this example, the callback function logs each fruit to the console. The <code>fruit</code> parameter represents the current element being processed, allowing you to access and work with it within the function.</p>
</li>
<li><p><code>Index (index)</code>: The second parameter of the callback function represents the index of the current element. It provides the position of the element within the array.</p>
<p>  For example:</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">'orange'</span>];  

  fruits.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">fruit, index</span>) </span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Fruit at index <span class="hljs-subst">${index}</span> is <span class="hljs-subst">${fruit}</span>`</span>); 
  });
</code></pre>
<p>  In this example, the callback function logs each fruit along with its corresponding <code>index</code>. The index parameter allows you to access and utilize the index information within the function.</p>
</li>
<li><p><code>Original Array (array)</code>: The third parameter of the callback function represents the original array being iterated. It allows you to reference the entire array and perform operations or make decisions based on its properties or other elements.</p>
<p>  For example:</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">'orange'</span>]; 

  fruits.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">fruit, index, array</span>) </span>{
     <span class="hljs-keyword">if</span> (array.length &gt; <span class="hljs-number">3</span>) {
       <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The array is too long'</span>);   
     } 
  });
</code></pre>
<p>  In this example, the callback function checks if the length of the array is greater than <code>3</code> and logs a message if it is. The array parameter provides access to the original array, enabling you to use its properties or perform operations based on the array as a whole.</p>
</li>
</ul>
<p>By utilizing these parameters effectively within the callback function, you can access and work with the current element, index, and the original array to perform various operations, make decisions, or modify the array elements as needed.</p>
<h2 id="heading-thisarg-parameter-in-foreach-method">'thisArg' Parameter in forEach Method</h2>
<p>The second parameter of the forEach method in JavaScript is called <code>thisArg</code>. It is an optional parameter that allows you to specify the value of this within the callback function.</p>
<p>By default, when the callback function is executed, the value of <code>this</code> inside the callback function refers to the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/Global_object"><code>global object</code></a> (<code>window</code> in a browser environment or <code>global</code> in Node.js).</p>
<p>However, if you pass a value for <code>thisArg</code>, the <code>this</code> value within the callback function will be set to the provided value. The <code>thisArg</code> parameter can be useful in scenarios where you want to explicitly set the context or scope for the callback function.</p>
<p>For example, if you have an object and you want to use a method from that object as the callback function, you can pass the object as <code>thisArg</code> to ensure the method is invoked with the correct context.</p>
<p>Here's an example to illustrate the usage of the <code>thisArg</code> parameter:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {   
   <span class="hljs-attr">name</span>: <span class="hljs-string">'John'</span>,
   <span class="hljs-attr">greet</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>!`</span>);
   } 
};  

<span class="hljs-keyword">const</span> names = [<span class="hljs-string">'Alice'</span>, <span class="hljs-string">'Bob'</span>, <span class="hljs-string">'Charlie'</span>];  

names.forEach(person.greet, person);
</code></pre>
<p>In this example, we have an object <code>person</code> with a <code>greet</code> method. We use the <code>forEach</code> method on an array of names and pass <code>person.greet</code> as the callback function.</p>
<p>By passing <code>person</code> as the <code>thisArg</code> parameter, we ensure that the <code>greet</code> method is invoked with <code>person</code> as the <code>this</code> value, allowing it to access the name property correctly.</p>
<p>By understanding and utilizing the <code>thisArg</code> parameter effectively, you can control the context in which the callback function is executed and tailor it to your specific needs.</p>
<h2 id="heading-arrow-functions-for-concise-and-expressive-callbacks">Arrow functions for concise and expressive callbacks</h2>
<p>In the previous section, we have seen how to define and pass callback in the forEach method and we have used normal functions as the callbacks.</p>
<p>But it is also possible to use arrow functions instead of normal functions as callbacks.</p>
<p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a> provide a more compact syntax for defining functions and automatically bind the current scope, eliminating the need for explicit binding or preserving the <code>this</code> keyword. This results in code that is easier to read and understand.</p>
<p>Here's an example demonstrating the use of arrow functions as callbacks with the forEach method:</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>]  

numbers.forEach(<span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(element) 
})
</code></pre>
<p>In the above example, we have an array called <code>numbers</code> containing a sequence of numeric values. Instead of using a traditional function expression, we utilize an arrow function as the callback for the <code>forEach</code> method.</p>
<p>The arrow function takes <code>element</code> as its parameter, representing the current element being processed. Arrow functions provide a concise and expressive way to define callback functions.</p>
<p>They have a more compact syntax, and the lexical scoping of arrow functions allows them to automatically bind the current scope, which means you don't need to explicitly bind or preserve the <code>this</code> keyword.</p>
<p>By using arrow functions as callbacks, you can make your code more readable and maintainable. They offer a clean and concise way to define functions, especially for short and straightforward operations within the <code>forEach</code> loop.</p>
<h2 id="heading-benefits-of-using-foreach">Benefits of Using forEach</h2>
<p>After exploring various aspects of the forEach method, Now it's time to explore the benefits it offers.</p>
<p>To understand the benefits of forEach Let's consider the example that we are using so far. Iterating over an array of numbers and performing various actions on each element using the forEach method.</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">// Example using forEach </span>

numbers.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">element</span>) </span>{
   <span class="hljs-built_in">console</span>.log(element * <span class="hljs-number">2</span>); 
});
</code></pre>
<p>Here are the benefits that we are getting from forEach method in JavaScript:</p>
<ul>
<li><p><code>Cleaner Syntax</code>: In the example, forEach provides a cleaner syntax compared to traditional <code>for loops</code>. The callback function focuses on the action to be performed on each element (<code>console.log(element * 2)</code>), without the need for manual index management or loop control.</p>
</li>
<li><p><code>Improved Readability</code>: By using forEach, the purpose of the iteration is clearly stated. Other developers can easily understand that we are doubling each element (<code>element * 2</code>), making the code more readable and comprehensible.</p>
</li>
<li><p><code>Simplified Iteration</code>: With <code>forEach</code>, we don't need to worry about initializing counters, defining loop conditions, or incrementing indexes manually. The <code>forEach</code> method takes care of all the iteration details, allowing us to focus on the specific action of doubling each element.</p>
</li>
<li><p><code>Avoiding Common Pitfalls</code>: The <code>forEach</code> method automatically handles the iteration logic, ensuring that the callback function is executed for each element in the array. This avoids common pitfalls like off-by-one errors or infinite loops, as <code>forEach</code> guarantees that every element is processed correctly.</p>
</li>
<li><p><code>Enhancing Functional Programming</code>: The example aligns with functional programming principles by using <code>forEach</code>. We define the desired action for each element within the callback function, separating the iteration logic from the specific action of doubling the elements. This promotes a declarative style of coding, enhancing immutability and predictability.</p>
</li>
<li><p><code>Compatibility with Array-like Objects</code>: Although the example uses an array, forEach is also compatible with array-like objects. This flexibility allows us to apply the same iteration logic to different types of collections, such as NodeList or HTMLCollection, expanding the utility of the forEach method.</p>
</li>
</ul>
<p>By considering these benefits within the context of the provided example, we can see how <code>forEach</code> simplifies iteration, improves readability, and aligns with functional programming principles.</p>
<h2 id="heading-real-world-example-of-foreach">Real-world example of forEach</h2>
<p>So far, we have learned so many things related to forEach method in JavaScript. Now let's see a real-world example of forEach so that we can feel all things we have learned so far.</p>
<p>Suppose you have an array of user objects representing customers in an e-commerce application. Each user object contains properties such as <code>name</code>, <code>email</code>, and <code>purchasedItems</code>. You want to send a personalized email to each customer, thanking them for their purchase and providing additional information about related products.<br />Here is the code snippet to do that:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> users = [
  {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'John Doe'</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">'johndoe@example.com'</span>,
    <span class="hljs-attr">purchasedItems</span>: [<span class="hljs-string">'Shirt'</span>, <span class="hljs-string">'Shoes'</span>, <span class="hljs-string">'Hat'</span>],
  },
  {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Jane Smith'</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">'janesmith@example.com'</span>,
    <span class="hljs-attr">purchasedItems</span>: [<span class="hljs-string">'Dress'</span>, <span class="hljs-string">'Handbag'</span>],
  },
  <span class="hljs-comment">// ... more user objects</span>
];

users.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">user</span>) </span>{
  <span class="hljs-keyword">const</span> { name, email, purchasedItems } = user;

  <span class="hljs-comment">// Generate personalized email content</span>
  <span class="hljs-keyword">const</span> emailContent = <span class="hljs-string">`
    Hi <span class="hljs-subst">${name}</span>,
    Thank you for your recent purchase of <span class="hljs-subst">${purchasedItems.join(<span class="hljs-string">', '</span>)}</span> from our store. We appreciate your support!

    We thought you might also be interested in checking out our new arrivals. Feel free to visit our website for more amazing products.

    If you have any questions or need assistance, please don't hesitate to contact us.

    Best regards,
    Your Store Team
  `</span>;

  <span class="hljs-comment">// Send the email to the customer</span>
  sendEmail(email, emailContent);
});
</code></pre>
<p>In the given example, the <code>forEach</code> method is used to iterate over the <code>users</code> array. For each user, a personalized email is generated using template literals and the user's data. The email is then sent to the respective user's email address using the <code>sendEmail</code> function.</p>
<p>Inside the <code>forEach</code> loop, a callback function is defined, which takes a single argument, <code>user</code>. This parameter represents the current user object being processed during each iteration. By destructuring the <code>user</code> object, we extract the relevant properties such as <code>name</code>, <code>email</code>, and <code>purchasedItems</code> using object destructuring.</p>
<p>Using template literals, we then generate personalized email content for each user. The email content includes a thank-you message, the purchased items, and a suggestion to explore new arrivals. The <code>join()</code> method is used to concatenate the purchased items into a comma-separated string.</p>
<p>Once the email content is generated, it can be passed to the <code>sendEmail</code> function along with the customer's email address (<code>email</code>) to send the email. You can assume that the <code>sendEmail</code> function is a custom function that handles the logic of sending emails.</p>
<p>The <code>forEach</code> loop ensures that the callback function is executed for each user in the <code>users</code> array, allowing you to send personalized emails to all customers who made purchases.</p>
<p>Cool, right?</p>
<p>This example highlights the benefits of using <code>forEach</code> in a real-world scenario. It simplifies the process of iterating over an array, eliminating the need for manual loop control and index management. It allows you to focus on the specific task of generating personalized emails for each user, enhancing code readability and maintainability.</p>
<p>It's just a simple example of a use case that we can achieve using the <code>forEach</code> method in JavaScript. And I believe now you can feel how much powerful this <code>forEach</code> method is.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>forEach method in JavaScript is a fundamental tool in JavaScript that empowers developers to iterate over arrays with ease and flexibility.</p>
<p>By understanding its features and concepts you can leverage the full potential of <code>forEach</code> in your projects, making your code more concise, readable, and efficient.</p>
<p>With the knowledge gained from this comprehensive guide, you are well-equipped to use the power of forEach and elevate your JavaScript programming skills to new heights.</p>
<p>Remember to practice and experiment with the concepts discussed in this blog post to solidify your understanding and become a master of the forEach method in JavaScript.</p>
<p>Happy coding :)</p>
]]></content:encoded></item><item><title><![CDATA[Javascript setTimeout method - All you need to know]]></title><description><![CDATA[Introduction
JavaScript is a powerful programming language that allows developers to create dynamic and interactive web applications. One important feature of JavaScript is the Javascript setTimeout method function, which enables the javascript wait....]]></description><link>https://robiul.dev/javascript-settimeout-method-all-you-need-to-know</link><guid isPermaLink="true">https://robiul.dev/javascript-settimeout-method-all-you-need-to-know</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[asynchronous]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Tutorial]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Wed, 17 May 2023 15:42:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684955248096/14313ed5-db0e-4736-8843-fc4905a3cb14.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>JavaScript is a powerful programming language that allows developers to create dynamic and interactive web applications. One important feature of JavaScript is the Javascript <a target="_blank" href="https://www.w3schools.com/jsref/met_win_settimeout.asp">setTimeout</a> method function, which enables the <strong>javascript wait</strong>.</p>
<p>Understanding how to effectively use <code>setTimeout</code> is crucial for controlling the timing and flow of your JavaScript programs. In this comprehensive guide, we will dive deep into the world of Javascript setTimeout method and explore its various functionalities.</p>
<p>Whether you are a beginner or an experienced developer, this article will provide you with all the knowledge you need to harness the full potential of <code>setTimeout</code> in your JavaScript projects.</p>
<p>So, Get ready to master the art of timing in JavaScript and unlock new possibilities for creating responsive and efficient web applications.</p>
<p>Let's delve into the world of <code>setTimeout</code> and discover all its secrets!</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before delving into the world of <code>setTimeout</code>, it's beneficial to have a basic understanding of JavaScript and its fundamental concepts. Familiarity with <a target="_blank" href="https://robiul.dev/javascript-variables-beginner-thinking"><code>variables</code></a>, <code>functions</code>, and basic control flow (such as <code>if statements</code> and <a target="_blank" href="https://robiul.dev/javascript-loop-best-practices-for-optimal-performance"><code>loops</code></a>) will make it easier to grasp the concepts discussed in this article.</p>
<p>If you're new to JavaScript or need a refresher, there are numerous online resources available to learn the basics. Websites like <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript"><code>MDN Web Docs</code></a>, <a target="_blank" href="https://www.w3schools.com/js/"><code>W3Schools</code></a>, and <a target="_blank" href="https://www.freecodecamp.org/"><code>freeCodeCamp</code></a> offer comprehensive tutorials and guides that can help you get started on your JavaScript journey.</p>
<p>Additionally, I highly recommend the following two books for beginners in JavaScript:</p>
<ul>
<li><p><a target="_blank" href="https://amzn.to/42ZzPNS">Head First JavaScript Programming: A Brain-Friendly Guide</a></p>
</li>
<li><p><a target="_blank" href="https://amzn.to/456OFns">JavaScript: The Definitive Guide: Master the World's Most-Used Programming Language</a></p>
</li>
</ul>
<p>By diving into these resources, you'll gain a solid foundation in JavaScript programming, equipping you with the necessary knowledge to explore the intricacies of <code>setTimeout</code> and unlock new possibilities in your web development projects.</p>
<p>So, before we dive into the intricacies of <code>setTimeout</code>, make sure you have a solid foundation in JavaScript programming.</p>
<p>Once you're ready, let's explore the power of <code>setTimeout</code> and unlock new possibilities in your web development projects.</p>
<h2 id="heading-the-purpose-of-settimeout">The purpose of setTimeout</h2>
<p>To begin, let's understand the purpose of <code>setTimeout</code> first.</p>
<p><code>setTimeout</code> is commonly used in scenarios where you want to introduce delays, schedule events, or perform tasks at specific time intervals.</p>
<p>little confusing right?</p>
<p>Let's understand this with an example:</p>
<blockquote>
<p>Note: please avoid thinking about its syntax for now. we will discuss the Syntex later on.</p>
</blockquote>
<p>Suppose you want to declare a function but instead of calling it immediately, you want to call it after a certain period of time.</p>
<p>This is where <code>setTimeout</code> comes into the picture. It provides the functionality to delay the execution of a function.</p>
<p>Take a look at the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetUser</span>(<span class="hljs-params"></span>) </span>{  
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello, user!'</span>) 
}  
<span class="hljs-built_in">setTimeout</span>(greetUser, <span class="hljs-number">1000</span>)
</code></pre>
<p>In this example, we have a function called <code>greetUser</code> that simply logs a greeting message to the console. We want to delay the execution of this function by <code>1</code> seconds.</p>
<p>To achieve this, we use the <code>setTimeout</code> function and pass the <code>greetUser</code> function as the first argument and <code>1000</code> as the second argument.</p>
<p>And that's it!</p>
<p>When you run this code, it will make <strong>javascript wait 1 second</strong> and then print the greeting message <code>"Hello, user!"</code> to the console.</p>
<h2 id="heading-syntax-and-parameters-of-settimeout">Syntax and Parameters of setTimeout</h2>
<p>To effectively use <code>setTimeout</code>, it's important to grasp its syntax and parameters.</p>
<p>The basic syntax of setTimeout is as follows:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>, <span class="hljs-title">delay</span>, <span class="hljs-title">param1</span>, <span class="hljs-title">param2</span>, ...);</span>
</code></pre>
<p>Let's break down the different components:</p>
<ul>
<li><p>The first parameter is the <code>function</code> or code snippet that you want to execute after the specified delay. It can be a named function or an anonymous function.</p>
</li>
<li><p>The second parameter <code>delay</code> represents the time interval in <code>milliseconds</code> before the code execution begins. It determines the delay duration before the specified function is invoked.</p>
</li>
<li><p>Additional parameters, such as <code>param1</code>, <code>param2</code>, and so on, are optional. You can use them to pass arguments to the function specified in the first parameter.</p>
</li>
</ul>
<p>These <strong>setTimeout parameters</strong> allow you to customize the behavior of the function when it is executed.</p>
<p>The <code>setTimeout()</code> returns a <code>timeoutID</code> which is a positive integer identifying the timer created as a result of calling the method. The <code>timeoutID</code> can be used to cancel timeout by passing it to the <code>clearTimeout()</code> method which we will discuss in another article.</p>
<blockquote>
<p>Note: If you find the syntax confusing, don't worry!</p>
<p>In the upcoming sections of this blog, we will explore various examples and use cases for each parameter in detail. I assure you that by reading the full article, you will gain a clear understanding of how to use <code>setTimeout</code> effectively.</p>
<p>So, be patient and keep reading to unlock the full potential of this powerful JavaScript function.</p>
</blockquote>
<h2 id="heading-settimeout-code-breakdown">setTimeout code breakdown</h2>
<p>I know you already got an idea of what happened to the code that we used before. But To reinforce our understanding let's break down the code together:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetUser</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello, user!'</span>)
}

<span class="hljs-built_in">setTimeout</span>(greetUser, <span class="hljs-number">1000</span>)
</code></pre>
<p>In this code snippet:</p>
<ol>
<li><p>We define a function called <code>greetUser</code> using the function keyword. This function is responsible for printing the greeting message to the console.</p>
</li>
<li><p>We use the <code>setTimeout</code> function to schedule the execution of the <code>greetUser</code> function after a specified delay. The delay is set to <code>1000</code> milliseconds, which is equivalent to <code>1</code> seconds.</p>
</li>
<li><p>The first argument passed to <code>setTimeout</code> is the function reference <code>greetUser</code>. This tells setTimeout which function to execute after the specified delay.</p>
</li>
<li><p>The second argument <code>1000</code> represents the delay in milliseconds. It determines the time period before the code execution begins.</p>
</li>
</ol>
<p>By using <code>setTimeout</code>, we instruct <strong>JavaScript wait 1 second</strong> and then invoke the <code>greetUser</code> function. As a result, the greeting message <code>"Hello, user!"</code> will be printed on the console.</p>
<h2 id="heading-using-the-anonymous-function-as-a-callback">Using the anonymous function as a callback</h2>
<p>In the previous code example, we used a named function as the callback function in the <code>setTimeout</code> function.</p>
<p>However, <code>setTimeout</code> also allows you to provide an anonymous function as a callback that will be executed after the specified <code>delay</code>.</p>
<p>Anonymous functions are commonly used when the code to be executed is simple and doesn't require a separate named function.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{  
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'This code executes after the delay'</span>) 
}, <span class="hljs-number">1000</span>)
</code></pre>
<p>In this case, the anonymous function serves as the callback. It logs a message to the console after a delay of <code>1000</code> milliseconds (or <code>1</code> seconds).</p>
<p>You can replace the <code>console.log</code> statement with any code you want to execute after the delay. Using anonymous functions as callbacks in <code>setTimeout</code> provides flexibility and allows you to define and execute code inline without the need for separate function declarations.</p>
<h2 id="heading-passing-arguments-to-the-callback-function">Passing arguments to the callback function</h2>
<p>In the setTimeout callback function, You can easily pass parameters or arguments.</p>
<p>Suppose you have a function that accepts parameters, and you want to provide specific values to those parameters when the function is executed after the delay:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>) </span>{   
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello, '</span> + name + <span class="hljs-string">'!'</span>) 
}  

<span class="hljs-built_in">setTimeout</span>(greet, <span class="hljs-number">5000</span>, <span class="hljs-string">'John'</span>)
</code></pre>
<p>In this example, the greet function is scheduled to <strong>wait 5 seconds</strong> (<code>5000</code> milliseconds), and the argument <code>John</code> is passed as the name parameter.</p>
<p>You can adjust the delay and the argument values according to your specific use case.</p>
<p>Using this approach, you can customize the behavior of the callback function by passing different values as arguments, allowing for more dynamic and flexible code execution.</p>
<p>Here are some additional tips for passing arguments to the callback function:</p>
<ul>
<li><p>You can pass any number of arguments to the callback function.</p>
</li>
<li><p>The arguments will be passed to the callback function in the same order that they were passed to <code>setTimeout</code>.</p>
</li>
<li><p>If you pass a variable number of arguments to the callback function, you can use the arguments object to access them.</p>
</li>
</ul>
<p>Here is an example below:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processArgs</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">arguments</span>.length; i++) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Argument "</span> + (i + <span class="hljs-number">1</span>) + <span class="hljs-string">": "</span> + <span class="hljs-built_in">arguments</span>[i]);
  }
}

<span class="hljs-built_in">setTimeout</span>(processArgs, <span class="hljs-number">1000</span>, <span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"cherry"</span>);
</code></pre>
<p>In this example, the <code>processArgs</code> function prints each argument along with its corresponding index to the console. The output will be:</p>
<pre><code class="lang-markdown">Argument 1: apple
Argument 2: banana
Argument 3: cherry
</code></pre>
<h2 id="heading-passing-string-literals">Passing string literals</h2>
<p>Passing a string as the first argument to <code>setTimeout</code> instead of a function can lead to potential issues and is generally not recommended.</p>
<p>It has similar problems to using <code>eval()</code>.</p>
<p>Here's an example of passing a string literals to <code>setTimeout</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Don't do this </span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-string">"console.log('Hello World!');"</span>, <span class="hljs-number">500</span>)
</code></pre>
<p>In this case, the string <code>"console.log('Hello World!');"</code> is evaluated as code in the global context when the timeout expires.</p>
<p>However, using a string in this way can cause problems because the evaluation happens in a different context, and local symbols or variables may not be available.</p>
<p>To avoid these issues, it's recommended to pass a function as the first argument to <code>setTimeout</code> instead. This ensures that the code is executed within the correct context and has access to local symbols.</p>
<p>Here's an alternative approach using a function as the callback:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Do this instead </span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World!'</span>) 
}, <span class="hljs-number">500</span>)
</code></pre>
<p>In this example, an arrow function is used as the callback. The arrow function provides a concise and safer way to execute code after the specified delay.</p>
<p>It avoids the pitfalls associated with passing string literals to <code>setTimeout</code> and ensures that the code is executed within the correct scope.</p>
<p>By passing a function instead of a string, you can maintain better control over the execution context and avoid potential issues with accessing local variables or symbols.</p>
<h2 id="heading-maximum-delay-value">Maximum delay value</h2>
<p>The maximum <code>delay</code> value that can be set in the Javascript setTimeout method function depends on the JavaScript implementation and the environment in which it is running.</p>
<p>In most modern browsers and JavaScript environments, the maximum delay value is approximately <code>2^31 - 1</code> milliseconds, which is roughly <code>24.85</code> days. If you attempt to set a delay value greater than this maximum, it will be automatically clamped to the maximum allowable value.</p>
<p>Therefore, if you need to schedule a task that exceeds this maximum delay, you might need to consider alternative approaches or use a combination of multiple <code>setTimeout</code> calls.</p>
<p>It's worth noting that extremely long delay values should be used with caution, as they may not be reliable or practical for many real-world scenarios. If you require precise timing or longer delays, you may want to explore other techniques or APIs specifically designed for such purposes.</p>
<p>Here are some alternative approaches for scheduling tasks that exceed the maximum delay value:</p>
<ul>
<li><p>Use a combination of multiple <code>setTimeout</code> calls. This can be used to break down a long task into smaller chunks that can be scheduled individually.</p>
</li>
<li><p>Use a background thread or process. This can be used to execute tasks that do not need to interact with the main thread or user interface.</p>
</li>
<li><p>Use a third-party library or API. There are a number of libraries and APIs available that provide support for scheduling tasks with longer delays.</p>
</li>
</ul>
<p>The best approach for scheduling a task that exceeds the maximum delay value will depend on the specific requirements of the task.</p>
<h2 id="heading-how-settimeout-works-behind-the-scenes">How setTimeout works behind the scenes</h2>
<p>So far we have discussed so many things about Javascript setTimeout method.</p>
<p>But, To fully grasp the concept of Javascript setTimeout method, it's crucial to understand its underlying mechanism and how it works behind the scenes.</p>
<p>Now let's understand how this works behind the scenes.</p>
<blockquote>
<p>Note: This section explores advanced concepts of JavaScript such as the <code>Event Loop</code>, <code>Call Stack</code>, and <code>Web API</code>. If you're not familiar with these concepts, feel free to skip this section as it won't affect your understanding of setTimeout and its usage.</p>
<p>However, if you're interested in delving deeper into the inner workings of JavaScript and gaining insights into the mechanisms behind the <code>setTimeout</code> function, this section is specifically tailored for you.</p>
</blockquote>
<p>JavaScript is a single-threaded programming language, which means it can only handle one task at a time.</p>
<p>However, web browsers have additional components like the <code>Event Loop</code>, <code>Call Stack</code>, and <code>Web API</code> that helps manage asynchronous tasks and enables non-blocking behavior.</p>
<p>When you use the <code>setTimeout</code> function in JavaScript. It follows a specific workflow involving these components.</p>
<p>Let's break it down step by step from a beginner's perspective:</p>
<ul>
<li><p>The <code>setTimeout</code> function is added to the <code>call stack</code>, which creates a timer in the Web API component of the browser. The specified delay is set, and the timer starts counting down.</p>
</li>
<li><p>While the timer is running, the JavaScript engine continues executing other code if there is any. It doesn't wait for the timer to expire before moving forward.</p>
</li>
<li><p>After the specified time interval (e.g., <strong>javascript wait 5 seconds</strong>) elapses, the timer expires, and the callback function provided to <code>setTimeout</code> is moved from the Web API to the <code>callback queue</code>. The callback queue holds the functions that are ready to be executed.</p>
</li>
<li><p>The <code>Event Loop</code> is responsible for continuously monitoring both the <code>call stack</code> and the <code>callback queue</code>. It checks if the call stack is empty.</p>
</li>
<li><p>If the <code>call stack</code> is empty, the event loop takes the callback function from the callback queue and pushes it onto the <code>call stack</code> for execution. This process ensures that the callback functions are executed in the order they were added to the queue.</p>
</li>
</ul>
<p>Let's consider an example to better understand this process:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">task</span>(<span class="hljs-params"></span>) </span>{   
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'setTimeout Demo!'</span>) 
}  
<span class="hljs-built_in">setTimeout</span>(task, <span class="hljs-number">5000</span>)
</code></pre>
<p>In this example, the task function is scheduled to execute after <strong>javascript wait 5 seconds</strong> (<code>5000</code> milliseconds).</p>
<p>Here's how it unfolds:</p>
<ul>
<li><p>The <code>setTimeout</code> function is added to the <code>call stack</code>, creating a timer in the <code>Web API</code>.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684955488313/f2fc07ec-c676-4241-9e40-0b0dbba4ec6a.webp" alt="How setTimeout works behind the scenes part_1 (robiul.dev)" class="image--center mx-auto" /></p>
<p>  The timer starts counting down, and the JavaScript engine proceeds to execute other code if present.</p>
</li>
<li><p>After approximately 3 seconds, the timer expires, and the task function is moved<br />  from the <code>Web API</code> to the <code>callback queue</code>.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684955557529/14e373a1-6632-47aa-aba7-50b6dfb18ca9.webp" alt="How setTimeout works behind the scenes part_2 (robiul.dev)" class="image--center mx-auto" /></p>
</li>
<li><p>Since the <code>call stack</code> is empty, the event loop removes the task function from the <code>callback queue</code>, pushes it onto the call stack, and executes it.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684955594575/1755b53a-6834-4530-9187-54eb4f3a3f43.webp" alt="How setTimeout works behind the scenes part_3 (robiul.dev)" class="image--center mx-auto" /></p>
</li>
<li><p>Inside the task function, the <code>console.log()</code> statement is executed, creating a new function execution context.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684955639855/8538b044-c497-48b5-877a-cfa0ca2514e7.webp" alt="How setTimeout works behind the scenes part_4 (robiul.dev)" class="image--center mx-auto" /></p>
</li>
<li><p>Finally, when the <code>console.log()</code> and task function are completed, they are popped out of the <code>call stack</code>.</p>
</li>
</ul>
<p>By following this process, JavaScript can handle asynchronous tasks, such as delayed execution with <code>setTimeout</code>, without blocking the execution of other code.</p>
<h2 id="heading-the-this-problem">The <code>this</code> Problem</h2>
<p>When using <code>setTimeout</code> with a method, you may encounter a <code>this</code> keyword problem, where the value of <code>this</code> inside the method differs from your expectation.</p>
<p>This issue arises due to the way <code>setTimeout</code> works and the separate execution context it uses.</p>
<p>By default, when a method is invoked using setTimeout, the <code>this</code> value inside the method is set to the <code>window</code> (or <code>global</code>) object instead of the object you intended.</p>
<p>This behavior can lead to unexpected results, as shown in the following example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> myArray = [<span class="hljs-string">'zero'</span>, <span class="hljs-string">'one'</span>, <span class="hljs-string">'two'</span>]
myArray.myMethod = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">sProperty</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">arguments</span>.length &gt; <span class="hljs-number">0</span> ? <span class="hljs-built_in">this</span>[sProperty] : <span class="hljs-built_in">this</span>)
}

myArray.myMethod() <span class="hljs-comment">// prints "zero,one,two" (the whole array)</span>
myArray.myMethod(<span class="hljs-number">1</span>) <span class="hljs-comment">// prints "one"</span>
</code></pre>
<p>In the above example, when <code>myMethod</code> is called directly on <code>myArray</code>, the <code>this</code> value is correctly set to <code>myArray</code>.</p>
<p>However, when using <code>setTimeout</code> with <code>myArray.myMethod</code>, the <code>this</code> value defaults to the <code>window</code> object.</p>
<p>To overcome this issue, there are a few solutions you can employ:</p>
<ul>
<li><p>Use a wrapper function:</p>
<p>  A common approach is to use a wrapper function that explicitly sets the desired this value:</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ 
    myArray.myMethod() 
}, <span class="hljs-number">1000</span>) <span class="hljs-comment">// prints "zero,one,two" after 1 seconds</span>

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ 
   myArray.myMethod(<span class="hljs-string">'1'</span>) 
}, <span class="hljs-number">2500</span>) <span class="hljs-comment">// prints "one" after 2.5 seconds</span>
</code></pre>
<ul>
<li><p>Arrow function as the wrapper function:</p>
<p>  Arrow functions do not bind their own <code>this</code> value and instead inherit it from the surrounding scope.</p>
<p>  This behavior can be leveraged to maintain the expected <code>this</code> value inside the callback function.</p>
<p>  Here's an example of using an arrow function as a callback with <code>setTimeout</code>:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> myArray = [<span class="hljs-string">'zero'</span>, <span class="hljs-string">'one'</span>, <span class="hljs-string">'two'</span>] 

  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
   myArray.myMethod() 
  }, <span class="hljs-number">1000</span>) <span class="hljs-comment">// prints "zero,one,two" after 1 seconds </span>

  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
   myArray.myMethod(<span class="hljs-string">'1'</span>) 
  }, <span class="hljs-number">2500</span>) <span class="hljs-comment">// prints "one" after 2.5 seconds</span>
</code></pre>
<p>  In this case, the arrow function does not have its own <code>this</code> binding and instead uses the <code>this</code> value from the surrounding scope, which is the expected value of <code>myArray</code>.</p>
<p>  Using an arrow function as a callback can provide a concise and convenient solution to the <code>this</code> problem when working with <code>setTimeout</code> and methods.</p>
<p>  It's important to note that arrow functions have some differences in behavior compared to regular functions, so it's essential to consider their implications and choose the most suitable solution based on your specific use case.</p>
<pre><code class="lang-javascript">  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    myArray.myMethod()
  }, <span class="hljs-number">1000</span>) <span class="hljs-comment">// prints "zero,one,two" after 1 seconds</span>

  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    myArray.myMethod(<span class="hljs-string">'1'</span>)
  }, <span class="hljs-number">2500</span>) <span class="hljs-comment">// prints "one" after 2.5 seconds</span>
</code></pre>
</li>
<li><p>Use bind:<br />  Another option is to use the <code>bind()</code> method to bind the desired <code>this</code> value to the method:</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> myArray = [<span class="hljs-string">'zero'</span>, <span class="hljs-string">'one'</span>, <span class="hljs-string">'two'</span>]
  <span class="hljs-keyword">const</span> myBoundMethod = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">sProperty</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">arguments</span>.length &gt; <span class="hljs-number">0</span> ? <span class="hljs-built_in">this</span>[sProperty] : <span class="hljs-built_in">this</span>)
  }.bind(myArray)

  myBoundMethod() <span class="hljs-comment">// prints "zero,one,two" because 'this' is bound to myArray in the function</span>
  myBoundMethod(<span class="hljs-number">1</span>) <span class="hljs-comment">// prints "one"</span>

  <span class="hljs-built_in">setTimeout</span>(myBoundMethod, <span class="hljs-number">1000</span>) <span class="hljs-comment">// still prints "zero,one,two" after 1 second due to the binding</span>
  <span class="hljs-built_in">setTimeout</span>(myBoundMethod, <span class="hljs-number">1500</span>, <span class="hljs-string">'1'</span>) <span class="hljs-comment">// prints "one" after 1.5 seconds</span>
</code></pre>
<p>  By using <code>bind()</code>, you create a new function that is permanently bound to the specified <code>this</code> value, ensuring it remains consistent when passed to <code>setTimeout</code> or called elsewhere.</p>
</li>
</ul>
<p>These solutions help resolve the <code>this</code> problem when using <code>setTimeout</code> with methods, allowing you to maintain the desired context and avoid unexpected behavior.</p>
<h2 id="heading-nested-timeouts">Nested timeouts</h2>
<p>Nested timeouts refer to the situation where a <code>setTimeout</code> function is called within the callback function of another <code>setTimeout</code>.</p>
<p>This approach can be used to create a sequence of timed events or to introduce delays between consecutive actions.</p>
<p>Here's an example to illustrate nested timeouts:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{ 
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'First timeout executed.'</span>) 
   <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Second timeout executed.'</span>)
      <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
       <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Third timeout executed.'</span>)
     }, <span class="hljs-number">2000</span>)
   },<span class="hljs-number">1000</span>)
 }, <span class="hljs-number">500</span>)
</code></pre>
<p>In this example, we have three <code>setTimeout</code> functions nested inside each other. Each <code>setTimeout</code> has its own callback function and delay.</p>
<p>The first <code>setTimeout</code> executes after <code>500</code> milliseconds, the second executes after <code>1000</code> milliseconds (<code>1</code> second) from the first timeout, and the third executes after <code>2000</code> milliseconds (<code>2</code> seconds) from the second timeout.</p>
<p>When you run this code, it will output the following:</p>
<pre><code class="lang-markdown">First timeout executed. 
Second timeout executed. 
Third timeout executed.
</code></pre>
<p>By nesting timeouts, you can create a sequence of actions that occur at different time intervals. This can be useful for scenarios where you need to orchestrate a series of events or introduce delays between specific operations.</p>
<p>However, it's important to be mindful of the potential complexity that can arise from deeply nested timeouts. As the number of nested timeouts increases, the code can become harder to read and maintain.</p>
<p>In such cases, alternative approaches like using async/await or libraries/frameworks that handle asynchronous operations may be more appropriate.</p>
<p>Remember to use <code>nested timeouts</code> judiciously and consider other options depending on the complexity and requirements of your code.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The <code>setTimeout</code> function is a fundamental tool in JavaScript, enabling developers to create dynamic and interactive experiences on the web.</p>
<p>By mastering <code>setTimeout</code>, you gain the ability to control timing, schedule tasks, and build sophisticated applications. With the insights and examples shared in this blog, you're now equipped to leverage <code>setTimeout</code> effectively and unlock the full potential of JavaScript's timer capabilities.</p>
<p>Now you have a powerful tool at your disposal to handle timing-related tasks, manage delays, and create more interactive and dynamic web applications.</p>
<p>Remember to practice and experiment with <code>setTimeout</code> to deepen your understanding and unlock its full potential. With this knowledge, you are well-equipped to harness the power of <code>setTimeout</code> and enhance the functionality of your JavaScript applications.</p>
<p>Happy coding :)</p>
<h2 id="heading-resource"><strong>Resource</strong></h2>
<ul>
<li><p>https://developer.mozilla.org/en-US/docs/Web/API/setTimeout</p>
</li>
<li><p>https://www.javascripttutorial.net/javascript-bom/javascript-settimeout/</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[JavaScript Loop Best Practices for Optimal Performance]]></title><description><![CDATA[Introduction
JavaScript Loop is a fundamental part of any programming language, and JavaScript is no exception. JavaScript loop is a powerful tool that allows developers to iterate over collections of data, perform operations on each item, and make d...]]></description><link>https://robiul.dev/javascript-loop-best-practices-for-optimal-performance</link><guid isPermaLink="true">https://robiul.dev/javascript-loop-best-practices-for-optimal-performance</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Loops]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[best practices]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Sun, 14 May 2023 06:51:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684954621836/e8a31278-dcc7-4647-9bbd-764de364cdac.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p><strong>JavaScript Loop</strong> is a fundamental part of any programming language, and JavaScript is no exception. <strong>JavaScript loop</strong> is a powerful tool that allows developers to iterate over collections of data, perform operations on each item, and make decisions based on certain conditions.</p>
<p>However, loops can quickly become a source of problems if not implemented properly. Poorly written loops can lead to performance issues, bugs, and code that is difficult to maintain.</p>
<p>Whether you're a beginner or an experienced developer, writing efficient and effective loops can be a challenging task.</p>
<p>In this comprehensive guide, we'll explore the best practices for writing <strong>JavaScript loop</strong> that will help to take your code from noob to pro. We'll start with the basics, including choosing the right loop type and optimizing loop performance. Then we'll dive into more advanced topics like using functional programming techniques and being careful with the asynchronous loops to avoid weird things in your code.</p>
<p>Whether you're working with arrays, objects, or other data structures, our tips and tricks will help you write clean, concise, and bug-free loops.</p>
<p>So if you're ready to master the art of <strong>JavaScript loop</strong>, buckle up and let's dive in!</p>
<h2 id="heading-choosing-the-right-type-of-loop">Choosing the Right Type of Loop</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684954647619/e4713431-0855-4068-8563-579b4224fedf.webp" alt="Choosing the Right Type of Loop (robiul.dev)" class="image--center mx-auto" /></p>
<p>When you are writing a <strong>JavaScript Loop</strong>, the First thing you need to do is choose the right type of loop. JavaScript offers several types of loops, including <a target="_blank" href="https://www.w3schools.com/js/js_loop_for.asp"><code>for loop</code></a>, <a target="_blank" href="https://www.w3schools.com/js/js_loop_while.asp"><code>while loop</code></a>, and <a target="_blank" href="https://www.w3schools.com/jsref/jsref_dowhile.asp"><code>do-while loop</code></a>, each with its own strengths and weaknesses. Depending on the specific requirements of your code, one type of loop may be more efficient or more readable than another.</p>
<p>Therefore, it's essential to consider the situation and choose the appropriate loop type to achieve the desired results.</p>
<p>let's enlighten them one by one:</p>
<p>Starting with the most popular one, The <code>For loop</code>. It's the most common type of loop in JavaScript and is often used when you know how many times you want to execute a block of code.</p>
<p>For example, imagine you have an array of numbers and you want to calculate their sum:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</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">let</span> sum = <span class="hljs-number">0</span> 
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; numbers.length; i++) { 
    sum += numbers[i] 
} 
<span class="hljs-built_in">console</span>.log(sum) <span class="hljs-comment">// Output: 15</span>
</code></pre>
<p>Here, the <code>for loop</code> is used to iterate over each element in the numbers array and add its value to the <code>sum</code> variable.</p>
<p>Next <code>While loop</code>, it is useful when you want to repeatedly execute a block of code until a certain condition is met.</p>
<p>For example, imagine you want to generate random numbers between <code>0</code> and <code>1</code> until you get a number greater than <code>0.5</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> randomNumber = <span class="hljs-built_in">Math</span>.random() 
<span class="hljs-keyword">while</span> (randomNumber &lt;= <span class="hljs-number">0.5</span>) { 
    randomNumber = <span class="hljs-built_in">Math</span>.random() 
} 
<span class="hljs-built_in">console</span>.log(randomNumber) <span class="hljs-comment">// Output: a number greater than 0.5</span>
</code></pre>
<p>In this case, the while loop repeatedly generates a new random number until it gets one that is greater than <code>0.5</code>.</p>
<p>Next <code>Do-while loop</code>, It's similar to <code>while loop</code>, but the difference is that a <code>do-while loop</code> will always execute its block of code at least once, regardless of whether the condition is initially <code>true</code> or <code>false</code>.</p>
<p>For example, imagine you want to ask the user to enter a number between <code>1</code> and <code>10</code>, and keep asking until they enter a valid number:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> number 
<span class="hljs-keyword">do</span> { 
number = prompt(<span class="hljs-string">'Enter a number between 1 and 10:'</span>) 
} <span class="hljs-keyword">while</span> (number &lt; <span class="hljs-number">1</span> || number &gt; <span class="hljs-number">10</span>) 
<span class="hljs-built_in">console</span>.log(number) <span class="hljs-comment">// Output: a number between 1 and 10</span>
</code></pre>
<p>In this case, the <code>do-while loop</code> repeatedly prompts the user to enter a number until they enter a number between <code>1</code> and <code>10</code>.</p>
<p>So, as you can see, choosing the right type of loop depends on the specific task you are trying to accomplish. If you know how many times you want to execute a block of code, a <code>for loop</code> may be the best choice. If you want to repeatedly execute a block of code until a certain condition is met, <code>while loop</code> or <code>do-while loop</code> may be more appropriate.</p>
<p>By selecting the right type of loop, you can make your code more efficient and easier to read.</p>
<h2 id="heading-use-the-right-loop-control-statement">Use the Right Loop Control Statement</h2>
<p>After choosing the appropriate loop for your desired task, the Next thing you need to know is how to use the right loop control statement. There are two main loop control statements available in JavaScript: <code>break</code> and <code>continue</code>.</p>
<p>These Loop control statements allow you to control the flow of a loop. <code>break</code> is used to exit a loop completely when a certain condition is met, On the other hand, <code>continue</code> is used to skip the current iteration of the loop and move on to the next one.</p>
<p>For example, let's say you have an array of numbers and you want to find the first <code>even</code> number in the array using a for loop. You can use <code>break</code> to exit the loop once you find the first <code>even</code> number:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">4</span>, <span class="hljs-number">7</span>, <span class="hljs-number">6</span>] 
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; numbers.length; i++) { 
    <span class="hljs-keyword">if</span> (numbers[i] % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>) { 
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The first even number is <span class="hljs-subst">${numbers[i]}</span>`</span>) 
        <span class="hljs-keyword">break</span> 
    } 
}
</code></pre>
<p>In this example, the loop will exit as soon as it finds the first <code>even</code> number (which is <code>2</code>). Without the <code>break</code> statement, the loop would continue iterating through the rest of the array.</p>
<p>On the other hand, let's say you want to print out all the <code>odd</code> numbers in the array, skipping over any <code>even</code> numbers. You can use <code>continue</code> to skip the <code>even</code> numbers:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">5</span>, <span class="hljs-number">4</span>, <span class="hljs-number">7</span>, <span class="hljs-number">6</span>] 
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; numbers.length; i++) { 
        <span class="hljs-keyword">if</span> (numbers[i] % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>) { 
            <span class="hljs-keyword">continue</span> 
        }         
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Odd number: <span class="hljs-subst">${numbers[i]}</span>`</span>) 
}
</code></pre>
<p>In this example, the loop will skip over the numbers and only print out the <code>odd</code> numbers (which are <code>1</code>, <code>3</code>, <code>5</code>, and <code>7</code>). Without the continue statement, the loop would print out all the numbers in the array.</p>
<p>Now we know how to choose the right loop for our task also when to use <code>break</code> and <code>continue</code>.</p>
<p>let's move to the next thing we need to think of when writing a loop and this is optimizing the Loop performance.</p>
<h2 id="heading-optimizing-the-loop-performance">Optimizing The Loop Performance</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684954683902/c97db4f7-6717-4737-8bc3-5d97f8ee1e9c.gif" alt="Optimizing The Loop Performance (robiul.dev)" class="image--center mx-auto" /></p>
<p>In normal situations, it may not create a big change in our code performance but when we will work with a large number of data Optimizing the loop performance will become one of the most important things. Because Loop performance can have a significant impact on the overall performance of your JavaScript code.</p>
<p>Therefore, it's essential to profile and optimize the performance of your loops.</p>
<p>Here are some tips for optimizing loop performance:</p>
<h3 id="heading-avoiding-unnecessary-calculations">Avoiding unnecessary calculations</h3>
<p>One way to optimize <strong>JavaScript Loop</strong> performance is by avoiding unnecessary calculations.</p>
<p>To Understand the point let's have a look at the example below:</p>
<p>suppose you have a loop that iterates over an <code>array</code>. In that case, when you use a for loop to iterate over an array, the <code>length</code> of the array is checked in each iteration to see if the loop should continue.</p>
<p>For example, consider the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</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">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length; i++) { 
    <span class="hljs-built_in">console</span>.log(arr[i]) 
}
</code></pre>
<p>In each iteration of the loop, <code>arr.length</code> is checked to see if <code>i</code> is less than the <code>length</code> of the array.</p>
<p>However, <code>arr.length</code> is a property of the array, and accessing it in each iteration can be expensive if the array is very large.</p>
<blockquote>
<p>Note: In JavaScript, an array is a special type of object that can store a collection of values of any data type. Every array has a <code>length</code> property, which represents the number of elements in the array. This <code>length</code> property is automatically updated as elements are added to or removed from the array. Since an array is an object, it can have properties and methods just like any other object. However, the <code>length</code> property is unique to arrays and allows for easy access to the number of elements in the array.</p>
</blockquote>
<p>To improve performance, you can cache the <code>length</code> of the array outside the loop, like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</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">let</span> len = arr.length <span class="hljs-comment">// caching the length outside the loop </span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; len; i++) { 
    <span class="hljs-built_in">console</span>.log(arr[i]) 
}
</code></pre>
<p>By doing this, you avoid accessing the <code>length</code> property of the array in each iteration, which can improve the performance of your code. This technique can be particularly useful when working with large arrays.</p>
<blockquote>
<p>Note: It's worth noting that modern JavaScript engines like V8 are optimized to handle loops efficiently, and in some cases, caching the length of the array may not provide a significant performance boost. However, it's still a good practice to follow, especially when working with large arrays or in performance-critical code.</p>
</blockquote>
<h3 id="heading-use-efficient-loops">Use efficient loops</h3>
<p>Another way to optimize loop performance is by using efficient loops.</p>
<p>For example, <code>for loop</code> is generally more efficient than the <a target="_blank" href="https://robiul.dev/foreach-method-in-javascript-a-comprehensive-guide"><code>forEach</code></a> loop when iterating over arrays.</p>
<p>Let's see the code snippet below to understand this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</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-comment">// Using for loop for iterating over the array </span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>, len = arr.length; i &lt; len; i++) { 
    <span class="hljs-built_in">console</span>.log(arr[i]) 
}
</code></pre>
<p>In the above example, we are using a <code>for loop</code> to iterate over the <code>arr</code> array. But the question is we could do the same using the <code>forEach loop</code>.</p>
<p>why this is the better approach. right?</p>
<p>This topic is a bit complex and deserves a separate blog post to explain briefly. But one of the main reasons is When we use the <code>forEach</code> loop, it creates a new function scope for every element in the array. This means that for each element, a new function is created, and when the iteration is done, those functions are destroyed.</p>
<p>This process is not an issue if the array is small. However, for larger arrays, it can slow down the loop's execution.</p>
<p>On the other hand, <code>for loop</code> creates a single function scope for the entire loop, which means that it only has to create and destroy a single function scope.</p>
<p>Also, <code>for loop</code> provides a way to get control over the loop iteration using the <code>break</code> and <code>continue</code> which <code>forEach loop</code> simply doesn't provide.</p>
<p>That's why the <code>for loop</code> is more optimized for looping over arrays.</p>
<h3 id="heading-minimize-dom-manipulation">Minimize DOM manipulation</h3>
<p>In <strong>JavaScript Loop</strong>, it's important to minimize DOM manipulation as much as possible. Because, When working with the Document Object Model (DOM) in JavaScript, manipulating the DOM can be a time-consuming process.</p>
<p>Each time you make a change to the DOM, the browser has to reflow and repaint the page, which can slow down your application, especially when working with large numbers of elements.</p>
<p>For Example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Inefficient DOM manipulation </span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000</span>; i++) {                 
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myDiv'</span>).innerHTML += <span class="hljs-string">'&lt;p&gt;'</span> + i + <span class="hljs-string">'&lt;/p&gt;'</span> 
} 
<span class="hljs-comment">// More efficient DOM manipulation let output = '' </span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000</span>; i++) { 
    output += <span class="hljs-string">'&lt;p&gt;'</span> + i + <span class="hljs-string">'&lt;/p&gt;'</span> 
} 
<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myDiv'</span>).innerHTML = output
</code></pre>
<p>In the given example, the first loop is inefficient because it manipulates the DOM on every iteration. The <code>innerHTML</code> property of the <code>myDiv</code> element is updated with a new paragraph element on every iteration, resulting in a total of <code>1000</code> manipulations of the DOM.</p>
<p>On the other hand, The second loop is more efficient because it minimizes DOM manipulation. Instead of updating the DOM on every iteration, the loop concatenates a string of HTML to a variable called output.</p>
<p>Once the loop is complete, the output string is used to update the <code>innerHTML</code> property of the <code>myDiv</code> element just once, resulting in a single manipulation of the DOM.</p>
<h2 id="heading-avoid-common-mistakes">Avoid Common Mistakes</h2>
<p>There are a few common mistakes that developers normally do and you should be aware of and <strong>avoid common mistakes</strong> when working with loops in JavaScript:</p>
<h3 id="heading-modifying-loop-variables-inside-the-loop">Modifying Loop Variables Inside the Loop</h3>
<p><strong>Modifying loop variables inside the loop</strong> can lead to unexpected results or errors. It's generally not a good practice to modify loop variables inside the loop. Instead, you should use a separate variable to store any values that you want to modify.</p>
<p>For example, consider the following loop:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) { 
    <span class="hljs-built_in">console</span>.log(i); i++; <span class="hljs-comment">// modifying i inside the loop </span>
}
</code></pre>
<p>In this loop, i is being modified inside the loop, which can lead to unexpected results. Instead, you should use a separate variable to store any values that you want to modify, like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) { 
    <span class="hljs-built_in">console</span>.log(i); 
    <span class="hljs-keyword">let</span> modifiedValue = i + <span class="hljs-number">1</span>; <span class="hljs-comment">// using a separate variable to modify i </span>
}
</code></pre>
<h3 id="heading-not-using-curly-braces">Not Using Curly Braces</h3>
<p>It's possible to write a loop without curly braces, but it's generally not recommended. Without curly braces, it can be difficult to read and understand your code, and it can also lead to unexpected results or errors.</p>
<p>For example, consider the following loop:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) 
<span class="hljs-built_in">console</span>.log(i);
</code></pre>
<p>This loop does not have curly braces, which can make it difficult to read and understand the code. It's better to always use curly braces, even for single-line statements:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++) { 
    <span class="hljs-built_in">console</span>.log(i); 
}
</code></pre>
<h3 id="heading-be-careful-of-infinite-loop">Be careful of Infinite Loop</h3>
<p>An <strong>infinite loop</strong> is a loop that never stops. This can happen if you don't set up the correct exit condition or if the exit condition is never met. Infinite loops can cause your program to crash or hang, and they can be difficult to debug.</p>
<p>For example:</p>
<p>consider a loop that always increments the value of a variable but never checks if it has exceeded a certain value:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span> 
<span class="hljs-keyword">while</span> (count &lt; <span class="hljs-number">10</span>) { 
    <span class="hljs-built_in">console</span>.log(count) 
}
</code></pre>
<p>This code will result in an <strong>infinite loop</strong> because the count variable is never incremented beyond <code>0</code>.</p>
<p>That's why you should always be careful about infinite loops. To avoid infinite loops, make sure you set up the correct exit condition and test it thoroughly.</p>
<h3 id="heading-off-by-one-errors">Off-by-One Errors</h3>
<p><code>Off-by-one</code> <strong>errors</strong> occur when you use the wrong comparison operator or when you don't take into account the initial value of a loop variable. These errors can lead to incorrect results in your program or even crashes in some cases.</p>
<p>For example, let's say you have an array with <code>10</code> elements, and you want to loop through it and perform some operation on each element.</p>
<p>Here's how you might write the loop:</p>
<pre><code class="lang-javascript"><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-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>]; 
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length; i++) { 
    <span class="hljs-built_in">console</span>.log(arr[i]); 
}
</code></pre>
<p>This code will loop through all <code>10</code> elements of the array and print their values to the console. However, what if you accidentally use the wrong comparison operator and write <code>i &lt;= arr.length</code> instead of <code>i &lt; arr.length</code>?</p>
<pre><code class="lang-javascript"><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-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">10</span>]; 
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt;= arr.length; i++) { 
    <span class="hljs-built_in">console</span>.log(arr[i]); 
}
</code></pre>
<p>This code will result in an <code>off-by-one</code> error, because it will try to access an element that doesn't exist when <code>i</code> is equal to <code>arr.length</code>. The loop will run a total of <code>11</code> times instead of <code>10</code>, and the final iteration will throw an error because <code>arr[10]</code> is <code>undefined</code>.</p>
<p>To avoid <code>off-by-one</code> errors, always double-check your loop conditions to make sure you're using the correct comparison operator and taking into account the initial value of your loop variable.</p>
<p>By avoiding these <strong>common mistakes</strong>, you can ensure that your loops are running as intended and reduce the chances of errors or crashes in your program. It's always a good idea to double-check your loops for these mistakes before running your code.</p>
<h2 id="heading-use-recursion-if-needed">Use Recursion if needed</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684954727764/7d50f193-7fba-404f-a157-0fc8656d3dbb.webp" alt="Use Recursion if needed (robiul.dev)" class="image--center mx-auto" /></p>
<p>While loops are powerful, sometimes <a target="_blank" href="https://medium.com/sessionstack-blog/how-javascript-works-recursion-in-javascript-what-it-is-and-how-it-is-used-eef3d734f20d">recursion</a> can be an even more elegant solution.</p>
<p>It is particularly useful for traversing hierarchical data structures, where it's not possible to know how many levels of nesting there are in advance. It can also lead to simpler and more elegant code than using nested loops, especially in cases where the depth of the structure is not known in advance.</p>
<blockquote>
<p>Note: It's important to use recursion carefully and avoid infinite recursion, which can lead to a stack overflow error.</p>
</blockquote>
<p>For example:</p>
<p>Let's say you have a nested array of numbers, and you want to find the <code>sum</code> of all the numbers in the array, including the nested ones. One way to do this is by using recursion. Here's an example of how you could use recursion to find the <code>sum</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> nestedArray = [[<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-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumArray</span>(<span class="hljs-params">arr</span>) </span>{ 
    <span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>; 
     <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; arr.length; i++) { 
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">Array</span>.isArray(arr[i])) { 
            <span class="hljs-comment">// If the element is an array, call the function recursively </span>
            sum += sumArray(arr[i]); } <span class="hljs-keyword">else</span> { 
            <span class="hljs-comment">// If the element is a number, add it to the sum </span>
            sum += arr[i]; 
        } 
      } 
<span class="hljs-keyword">return</span> sum; 
} 
<span class="hljs-built_in">console</span>.log(sumArray(nestedArray)); <span class="hljs-comment">// Output: 10</span>
</code></pre>
<p>In this example, we used <code>Recursion</code> because the input data, <code>nestedArray</code>, is a <code>hierarchical</code> data structure and the function need to traverse all the elements of the structure, regardless of the number of levels of nesting.</p>
<p><code>Recursion</code> allows the function to call itself repeatedly until it reaches the deepest level of nesting and returns a value that can be used to calculate the final <code>sum</code>. The function checks whether each element in the array is an array itself, and if it is, the function calls itself with that element as the input.</p>
<p>This process repeats until all the nested arrays are traversed and the function reaches the deepest level of nesting, which is a number.</p>
<p>At that point, the function returns the number to the previous level of recursion, which can then use that value to calculate the <code>sum</code> of all the elements in the current level of nesting.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p><strong>JavaScript loop</strong> is a fundamental part of any developer's toolbox, but they can be tricky to master. By following these best practices, you can write more efficient and effective loops that will help take your code to the next level.</p>
<p>Choose the right type of loop, use the right loop control statement, optimize loop performance, avoid common mistakes, and consider using recursion when appropriate. By keeping these tips in mind, you'll be well on your way to becoming a <strong>JavaScript loop</strong> expert.</p>
<p>So take the time to evaluate and optimize your loops, and your code will be better for it.</p>
]]></content:encoded></item><item><title><![CDATA[Is javascript compiled or interpreted language?]]></title><description><![CDATA[Introduction
You have probably read that JavaScript is an interpreted language, while others argue that it's not an interpreted language and that it's actually a compiled language. Is javascript compiled or interpreted?
This can be confusing,
I was o...]]></description><link>https://robiul.dev/is-javascript-compiled-or-interpreted-language</link><guid isPermaLink="true">https://robiul.dev/is-javascript-compiled-or-interpreted-language</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Tutorial]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[programming languages]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Fri, 12 May 2023 04:57:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684952659445/61ccf7f5-6385-487d-8744-342f1e89f7b4.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>You have probably read that JavaScript is an interpreted language, while others argue that it's not an interpreted language and that it's actually a compiled language. <strong>Is javascript compiled or interpreted</strong>?</p>
<p>This can be confusing,</p>
<p>I was often confused because I received conflicting answers whenever I read books or articles about JavaScript being an interpreted or compiled language. But the truth is that it depends on how the language is implemented.</p>
<p>Let me explain.</p>
<p>To clarify this point, let's first examine what are compiler and interpreter also the difference between them</p>
<h2 id="heading-compiler">Compiler</h2>
<p>A compiler is a software tool that translates human-readable source code into machine-executable code. The process of compilation involves several stages, including</p>
<ul>
<li><p>lexical analysis</p>
</li>
<li><p>syntax analysis (parsing)</p>
</li>
<li><p>semantic analysis</p>
</li>
<li><p>code generation</p>
</li>
<li><p>optimization</p>
</li>
</ul>
<p>During lexical analysis, the compiler breaks down the source code into a series of tokens, which are individual units of meaning. For example, in the statement <code>"x = 5 + 3;"</code>, the tokens would be <code>"x"</code>, <code>"="</code>, <code>"5"</code>, <code>"+"</code>, and <code>"3"</code>. The lexer also assigns a type to each token, such as "identifier", "operator", or "literal".</p>
<p>Then, during syntax analysis (parsing), the compiler checks the order and structure of the tokens to ensure that they form a valid program. This involves analyzing the grammar of the programming language and constructing a syntax tree that represents the structure of the program.</p>
<p>After the syntax analysis is complete, the compiler performs semantic analysis to check for logical errors in the code. This involves verifying that the program follows the rules of the language, such as type checking, scoping rules, and function calls.</p>
<p>Once the compiler has verified the correctness of the program, it generates machine code or bytecode that can be executed by the computer. This involves translating the syntax tree and semantic information into low-level instructions that can be executed by the computer's hardware.</p>
<p>Finally, the compiler performs optimization to improve the efficiency of the generated code. This process involves analyzing the code and making changes to improve the memory usage.</p>
<p>Overall, the compiler is an essential tool for translating human-readable source code into machine-executable code. The compilation process involves several stages, each of which is critical for producing correct and efficient code.</p>
<h2 id="heading-interpreter">Interpreter</h2>
<p>An interpreter is a program that reads and executes code written in a high-level programming language directly, without requiring an intermediate compilation step. Unlike a compiler, which translates the entire source code into machine code before execution, an interpreter reads and executes the source code line by line, translating and executing each statement as it is encountered.</p>
<p>When an interpreter runs a program,</p>
<ul>
<li><p>it first performs lexical analysis and parsing of the source code to generate an abstract syntax tree (AST) representing the program's structure.</p>
</li>
<li><p>The interpreter then walks through the AST, executing each node in turn. During execution, the interpreter may generate and manipulate additional data structures to represent the state of the program, such as a symbol table for tracking variable values.</p>
</li>
</ul>
<p>One advantage of using an interpreter is that it allows for more dynamic and interactive development, as programmers can test and modify their code on the fly without having to recompile the entire program. However, interpreting code can be slower than executing compiled code, since the interpreter has to perform additional work to translate and execute each statement.</p>
<p>Overall, an interpreter provides a convenient way to execute code in a high-level language, but may not be as performant as compiled code in certain situations.</p>
<h2 id="heading-compiler-vs-interpreter-in-a-simple-way">Compiler vs. Interpreter in a simple way</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684952710909/910e240e-0162-421f-8e63-11e4707b2947.jpeg" alt="Is javascript compiled or interpreted language? (robiul.dev)" class="image--center mx-auto" /></p>
<p>There is a lot of technical information about compilers and interpreters, so let's make it simple:</p>
<p>And like everything else in life, let's try to understand it with a cup of tea.</p>
<p>Let's say you want to make a cup of black tea, you go to Google and search for the ingredients list, this is what you came up with:</p>
<ul>
<li><p>Black tea leaves</p>
</li>
<li><p>Water</p>
</li>
<li><p>Sugar (optional)</p>
</li>
<li><p>Milk (optional)</p>
</li>
</ul>
<p>There are 2 ways to make the tea, the Compiler or the Interpreter way.</p>
<p>The compiler will first, before doing any steeping, organize all the ingredients in front of him, the specific amounts of every single ingredient, only then, will he steep all the ready components of the tea.</p>
<p>The interpreter will take his cup and will start by reading the ingredients, line by line. he will boil the water, add the tea leaves, steep them for a few minutes, add sugar or milk if desired, and then strain the tea into the cup.</p>
<p>The build (preparation) time of the compiler will be longer than the interpreter's. However, the run (steeping) time will be much shorter.</p>
<p>Now that you know the difference let’s talk about JavaScript.</p>
<h2 id="heading-is-javascript-compiled-or-interpreted-language">Is javascript compiled or interpreted Language?</h2>
<p>When I first started learning JavaScript, I, like many others, was taught that it was an interpreted language, and I believed it for a long time. However, after conducting further research, I have come to realize that this is not entirely accurate.</p>
<p>While many people still consider JavaScript to be an interpreted language, there is evidence to suggest that it is actually a compiled language. One example of this can be seen in the way that the JavaScript engine handles bugs.</p>
<p>When you encounter a syntax error in your JavaScript code, the engine will typically alert you to the problem before it even begins executing the code. This suggests that the code is compiled and validated before it is executed, which is a characteristic of compiled languages.</p>
<p>You can try this for yourself by opening the following HTML code in your browser and checking the console:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World from javascript!"</span>);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World from javascript!"</span>);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World from javascript!"</span>);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World from javascript!"</span>);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World from javascript!"</span>);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World from javascript!"</span>);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World from javascript!"</span>);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!);</span>
</code></pre>
<p>The last line of code is missing a closing quotation mark, which should trigger a syntax error. However, if JavaScript were truly an interpreted language, the console would have already printed the first nine lines before throwing an error.</p>
<p>Instead, the program crashes immediately,</p>
<pre><code class="lang-js">Uncaught <span class="hljs-built_in">SyntaxError</span>: Invalid or unexpected token
</code></pre>
<p>That indicates that it was compiled and validated before execution.</p>
<p>While there is still debate over whether <strong>Is javascript compiled or interpreted</strong>? it's clear that it's not entirely accurate to call it an interpreted language.</p>
<p>Another way to prove that JavaScript is not an entirely interpreted language is through the concept of <code>hoisting</code>. For example, consider the following code:</p>
<pre><code class="lang-javascript">max(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// 2</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">max</span>(<span class="hljs-params">num1, num2</span>)</span>{
  <span class="hljs-keyword">return</span> num1 &gt; num2 ? num1 : num2;
}
</code></pre>
<p>In traditional programming languages, a function must be defined before it can be called. However, in JavaScript, the function can be called before it is defined. This behavior is known as <code>hoisting</code>, and it's a fundamental aspect of how JavaScript works.</p>
<pre><code class="lang-md">Note: We will explore more about <span class="hljs-code">`hoisting`</span> in other blog for now this explanation is enough.
</code></pre>
<p>How does the JavaScript engine know about the <code>max</code> function before it reaches the declaration? The only reasonable answer to this question is that the code must first be compiled before execution.</p>
<p>So, <strong>Is javascript compiled</strong>?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684952769795/48a35db3-67a8-4d3d-b278-f48ce9f7d2cc.jpeg" alt="Is javascript compiled or interpreted language? (robiul.dev)" class="image--center mx-auto" /></p>
<p>Well, it's complicated. In the past, every programming language was fairly easy to categorize as either compiled or interpreted. However, with the modern approach of running source code, a sort of "in-between" area has been created.</p>
<h2 id="heading-how-does-javascript-actually-get-translated">How does JavaScript actually get translated?</h2>
<p>JavaScript has come a long way since its inception as a simple scripting language. In the early days, JavaScript engines were only interpreters, which executed code line by line. However, as JavaScript became more popular and its use cases expanded, performance issues emerged. Interpreting code on-the-fly resulted in a loss of performance, especially for complex applications. This led to the development of new engines that use a just-in-time (JIT) compiler.</p>
<p>A <strong>JIT compiler</strong> is different from traditional compilers, such as those used for C++. Traditional compilers have plenty of time to optimize the code during compilation, but the <strong>JIT compiler</strong> must compile code just before it's executed. As soon as the JavaScript code is about to run, it gets compiled into executable bytecode.</p>
<p>Despite the differences in how JavaScript is compiled compared to other compiled languages, the process still follows some of the same rules as traditional compilers. The JavaScript code is parsed before execution, which makes it look like a parsed language. However, the code is converted to binary form before execution.</p>
<p>To better understand this process, let's take a closer look at how code execution works behind the scenes:</p>
<ul>
<li><p>First, the code is transpiled using tools like Babel or Webpack.</p>
</li>
<li><p>The transpiled code is given to the engine, which parses it to an Abstract Syntax Tree (AST).</p>
</li>
<li><p>The AST is then converted to bytecode that is understood by the machine. This is an Intermediate Representation (IR), which is further optimized by the <strong>JIT compiler</strong>.</p>
</li>
<li><p>After optimization, the JS Virtual Machine (VM) executes the code.</p>
</li>
</ul>
<pre><code class="lang-javascript">Some people argue that the JS VM is <span class="hljs-string">"interpreting"</span> the bytecode, but <span class="hljs-built_in">this</span> is not entirely accurate. If we were to use that definition, we would also have to say that Java, which is another JVM-driven language, is also interpreted.
</code></pre>
<p>Thus, we can conclude that JavaScript is executed in three phases:</p>
<ul>
<li><p>Parsing</p>
</li>
<li><p>Compiling</p>
</li>
<li><p>Executing</p>
</li>
</ul>
<p>JavaScript code is initially interpreted before any execution begins. For example, consider the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello"</span>);
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>;i&lt;<span class="hljs-number">4</span>;i++) {
    <span class="hljs-built_in">console</span>.log(Hello);
}
</code></pre>
<p>The output shows the interpreter behavior in the above code example, where first <code>Hello</code> is printed to the console, and then an error is reported. This output strongly supports the fact that JavaScript is an interpreted language.</p>
<p>While it may seem like JavaScript code is being executed line by line, this is only true during the parsing phase. In reality, the entire code is compiled at once to convert it into machine-readable code before execution. Therefore, JavaScript is a just-in-time compiled language that uses an interpreter in its first phase.</p>
<pre><code class="lang-md">Note: JavaScript can operate in an interpreted manner in older browsers. However, every modern browser currently supports "JIT", so JavaScript code is always compiled. Whether JavaScript is compiled or interpreted depends on the environment in which it is run. If it runs in older browsers, it's interpreted. If it runs in modern browsers, it's compiled.
</code></pre>
<h2 id="heading-explaining-jit-in-javascript">Explaining JIT in JavaScript</h2>
<p>Now that we have a basic understanding of how JavaScript works and what a <strong>JIT compiler</strong> is, let's delve deeper into how JIT compiler work and why they're important.</p>
<p>But don't worry, we won't get too technical with jargon. Instead, we'll explore JIT compiler in simple terms to understand how they work, why they're important, and the reason they were introduced in the first place.</p>
<p>JIT (just-in-time) compilation is a technique used by modern JavaScript engines to improve the performance of JavaScript code. Unlike traditional compilers that optimize code during compilation, JIT compiler take a middle-ground approach. They initially interpret the code and then selectively compile parts of it that are used repeatedly. This approach balances fast start-up time with improved performance.</p>
<p>When a JavaScript engine encounters a function, it can either interpret the code on-the-fly or compile the code before execution. Interpreting the code can be faster to start execution but slower in terms of overall performance, as the code is translated line-by-line each time the function is executed. Compiling the code before execution can be slower to start, but it can result in faster execution due to machine code optimizations.</p>
<p>In this approach, the code is compiled into machine code, which is then executed by the processor.</p>
<p><strong>JIT compiler</strong> take a middle-ground approach, where they initially interpret the code and then selectively compile parts of it that are used repeatedly. As a result, the JIT compiler offers a balance of fast start-up time and improved performance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684952812308/70ce41af-7fea-4210-a81b-e5e789272d14.jpeg" alt="Is javascript compiled or interpreted language? (robiul.dev)" class="image--center mx-auto" /></p>
<p>To understand how JIT compilers work, let's consider an example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">100000000</span>; i++) {
  add(i, i + <span class="hljs-number">1</span>);
}
</code></pre>
<p>In this code, we have a simple <code>add</code> function that adds two numbers and a loop that calls this function <code>100</code> million times with different inputs.</p>
<p>When the JavaScript engine first encounters this code, it will interpret it on-the-fly and execute it. However, as the loop runs repeatedly, the engine detects that the <code>add</code> function is being called repeatedly and decides to compile it to machine code to improve performance.</p>
<p>The <strong>JIT compiler</strong> analyzes the code and optimizes it for the specific inputs being used in the loop.</p>
<p>For example, it may decide to inline the <code>add</code> function, which means replacing the function call with the actual addition code, eliminating the overhead of calling a function. Additionally, it may also perform other optimizations such as constant folding or dead-code elimination, which remove unnecessary computations.</p>
<p>Overall, the <strong>JIT compiler</strong> help improve the performance of JavaScript code by selectively compiling parts of it that are used repeatedly, while still allowing for fast start-up times.</p>
<p>Now that we have a better understanding of how the <strong>JIT compiler</strong> works, let's delve into the issues we previously discussed and their underlying causes.</p>
<h2 id="heading-why-the-pre-execution-syntax-error-alerts">Why the Pre-execution syntax error alerts</h2>
<p>Let's explore the reason behind syntax error alerts in JavaScript using the same example we discussed earlier.</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World from javascript!"</span>);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World from javascript!"</span>);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World from javascript!"</span>);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World from javascript!"</span>);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World from javascript!"</span>);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World from javascript!"</span>);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World from javascript!"</span>);
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello World!);</span>
</code></pre>
<p>In the case of the code example provided, the JavaScript engine compiles the code before execution, and the syntax error is detected during the compilation phase. This is because the engine uses the <code>JIT</code> compiler that optimizes code on the fly as it's executed. When the engine encounters an error during the compilation phase, it immediately throws an error without executing any code.</p>
<p>Therefore, the fact that JavaScript detects syntax errors during the compilation phase suggests that it's more like a compiled language than an interpreted one.</p>
<h2 id="heading-what-is-the-story-of-hoisting">What is the story of hoisting?</h2>
<p>Let's now understand the hoisting in the context of <code>JIT</code> engine using the code we used before:</p>
<pre><code class="lang-javascript">max(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>);
<span class="hljs-comment">// 2</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">max</span>(<span class="hljs-params">num1, num2</span>)</span>{
  <span class="hljs-keyword">return</span> num1 &gt; num2 ? num1 : num2;
}
</code></pre>
<p>So, how does the JavaScript engine know about the <code>max</code> function before it reaches the declaration?</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684953203202/c5ad1241-6c18-490e-aa33-5aab132feee1.webp" alt="Is javascript compiled or interpreted language? (robiul.dev)" class="image--center mx-auto" /></p>
<p>The answer lies in the Just-In-Time (<code>JIT</code>) compilation process that occurs behind the scenes when JavaScript code is executed in modern browsers.</p>
<p>During the optimization step, the <strong>JIT compiler</strong> can analyze the code to determine which functions are likely to be called frequently and which variables are likely to be accessed repeatedly. By identifying these patterns, the compiler can optimize the code for faster execution, which can result in significant performance gains.</p>
<p>In the case of hoisting, the compiler can recognize the pattern of a function being declared at the top of its scope and optimize the code accordingly.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In summary, while JavaScript is commonly thought of as an interpreted language, it is actually a Just-In-Time compiled language. Modern JavaScript engines use a <strong>JIT compiler</strong> to optimize the code for execution. This compiler allows JavaScript to be executed much faster and in an efficient way than traditional interpreted languages. While the compiling of Javascript works in a different way, if compared to other compiled languages, it still follows some rules that reflect the process of compiling.</p>
<p>JavaScript code is parsed before execution, which makes it look like a parsed language, but the code is actually converted to binary(machine code that is directly executed by the computer's hardware) form before execution. This conversion process involves several steps, including transpiling the code, parsing it to an Abstract Syntax Tree (<code>AST</code>), converting it to bytecode, and optimizing it with a <code>JIT</code> compiler.</p>
<p>So, to answer the question "<strong>Is javascript compiled or interpreted</strong> language?" the answer is that it is a bit of both. It is interpreted in older browsers, but in modern browsers, it is compiled with the help of a <strong>JIT compiler</strong>.</p>
<h2 id="heading-resource">Resource:</h2>
<ul>
<li><p>https://www.linkedin.com/pulse/javascript-compiled-language-st%C3%A9phane-moreau/</p>
</li>
<li><p>https://stackdiary.com/tutorials/is-javascript-a-compiled-or-interpreted-language/</p>
</li>
<li><p>https://almogad.medium.com/javascript-is-it-compiled-or-interpreted-9779278468fc</p>
</li>
<li><p>https://www.geeksforgeeks.org/is-javascript-interpreted-or-compiled/</p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Javascript variables (Beginner thinking)]]></title><description><![CDATA[Programming is all about manipulating and displaying data, which can be any kind of information used in computer programs, such as social media usernames, age, and profile photos. To work with this data and create interesting things, programmers need...]]></description><link>https://robiul.dev/javascript-variables-beginner-thinking</link><guid isPermaLink="true">https://robiul.dev/javascript-variables-beginner-thinking</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[variables]]></category><category><![CDATA[Beginner Developers]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[fundamentals]]></category><dc:creator><![CDATA[Robiul H.]]></dc:creator><pubDate>Thu, 04 May 2023 16:12:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1684952007784/5b5d1011-1b5e-459a-9b62-845464699a98.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Programming is all about manipulating and displaying data, which can be any kind of information used in computer programs, such as social media usernames, age, and profile photos. To work with this data and create interesting things, programmers need a way to store and keep track of it. This is where the concept of variables more specifically <strong>Javascript variables</strong> comes in.</p>
<p>Variable is an essential concept in almost every programming language, and there is much to know and understand about it. It is important for us to have a clear and deep understanding of these concepts related to the Variable.</p>
<p>In this post, we will explore almost all of the concepts related to <strong>Javascript variables</strong> in programming, but from a beginner's perspective. We will keep things simple to understand, and use examples to explore everything.</p>
<p>Even if you are new to programming and don't have much knowledge about JavaScript, you will be able to understand all the concepts we cover.</p>
<p>So, let's get started!</p>
<h2 id="heading-javascript-variables"><strong>Javascript variables</strong></h2>
<p>In JavaScript, a variable is a named reference to a memory location that can hold different types of data, such as numbers, strings, booleans, objects, or functions. To access variable or modify the data stored in a variable, we use its name.</p>
<p>It's a little confusing, right?</p>
<p>let's have a look at the computer memory.</p>
<p>If you have a basic understanding of computer memory then you must know that Computer memory has millions of cells on it and every cell has its own address.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684952050726/05637dcb-66e9-4c08-a66a-eeef3ff5a894.jpeg" alt="javascript Variables Beginner Thinking (robiul.dev)" class="image--center mx-auto" /></p>
<p>In our program, if we want to store value to access it later throughout the program, we have to keep it somewhere in the computer memory and we will need a way to call that value whenever we need.<br />we could have done that using the memory address after storing the data in the memory.<br />The problem is we can't use this address directly in our program. because you know the computer works in the binary system and in the binary system this memory address looks too weird and confusing. also, it's almost impossible to memorize.</p>
<p>Here variable comes in to solve this problem.</p>
<p>Variable gives us the simplest solution to handle it. We can simply create a variable and assign it to the value we want to store. now we don't need to memorize the weird and confusing memory address we can do the same using a simple and human-readable name.</p>
<p>When we are creating a variable and assigning a value to it. behind the since the Compilers and interpreters store the data inside the memory and replace the symbolic names of <strong>variables</strong> with the real data location/memory address.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684952122668/b98658d6-7609-4b67-b215-dc350fdf01b9.jpeg" alt="javascript Variables Beginner Thinking (robiul.dev).jpg" class="image--center mx-auto" /></p>
<p>That means our data is stored in memory and the variable is pointing to this memory location.</p>
<blockquote>
<p><strong>Note:</strong> In real scenarios, memory allocation is not as simple as I discussed here. also, Primitive type and Reference type values are treated differently when assigning them to <strong>Javascript variables</strong>. but for this post, I have avoided the advanced things and kept it simple so you can get an overall idea of how things work behind the scenes.</p>
</blockquote>
<p>If you are still confused about <strong>what are variables in javascript</strong>, simply think of variables as named containers that hold information and can be referred to the data simply by naming the container.</p>
<p>That means,</p>
<ul>
<li><p>Creating a variable</p>
</li>
<li><p>Giving a standard name to the variable</p>
</li>
<li><p>Assigning a value to it.</p>
</li>
</ul>
<p>Think of these steps as</p>
<ul>
<li><p>Taking a container</p>
</li>
<li><p>Labeling it</p>
</li>
<li><p>Putting something in this container.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1684952241518/883c0dc6-3453-4b62-bf5f-f5071bb66d59.jpeg" alt="javascript Variables Beginner Thinking (robiul.dev).jpg" class="image--center mx-auto" /></p>
<blockquote>
<p><strong>Note:</strong> A Javascript variable is a container, not a value, this means that <strong>variables</strong> aren’t themselves values; they are a named container for values.</p>
</blockquote>
<h2 id="heading-javascript-variable-declaration">Javascript Variable Declaration</h2>
<p>Before you use a variable in a JavaScript program, you must create or define variable, we call this declaring a variable.</p>
<p>we can Declare a JavaScript Variable using <code>var</code> or <code>let</code> :</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> name; 
<span class="hljs-keyword">let</span> age;
</code></pre>
<p>Here we are creating two variables, one using var and one using let.</p>
<p>var and let are the keywords that tell JavaScript you’re declaring a variable.</p>
<p>name and age are the names of those variables.</p>
<p>In Javascript, Semicolons(;) are totally optional (unless you want to have multiple statements in a single line, of course). (similar to a full stop(.) in the English language.)</p>
<blockquote>
<p>Note: Though Semicolons(;) are optional in javascript, there are many languages where Semicolon(;) is a big factor. In those languages you must end the line using a semicolon otherwise will occur an error to your program.</p>
</blockquote>
<p>In <strong>javascript multiple variable declaration</strong> can be done with the same <code>var</code> or <code>let</code> keyword:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> name, age;
<span class="hljs-keyword">let</span> birthYear, address;
</code></pre>
<blockquote>
<p>There is another keyword to declare <strong>Javascript variables</strong> which is const. This is used to declare the constant variables in javascript.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span>  Pi = <span class="hljs-number">3.1416</span>
</code></pre>
<p>we will talk about this in any other blog.</p>
</blockquote>
<hr />
<blockquote>
<p><strong>Question:</strong> Suppose, a store has 20 apples in its inventory. how can you store this information in a javascript variable?</p>
<ol>
<li><p>apples = 20;</p>
</li>
<li><p>let apples = 20;</p>
</li>
<li><p>ver apples = 20;</p>
</li>
<li><p>let apples;</p>
</li>
</ol>
</blockquote>
<h2 id="heading-naming-variables">Naming Variables</h2>
<p>Not only in JavaScript but also, in all other languages variables must be identified with unique names following some rules and regulations which is called <strong>naming variables</strong>. These unique names are called identifiers. These Identifiers or names can be short (like <code>a</code>, <code>b</code>, and <code>c</code>) or more descriptive (<code>age</code>, <code>name</code>, <code>userName</code>).</p>
<h3 id="heading-javascript-variable-name-rules">Javascript variable name rules</h3>
<p>There are some general rules to follow when we are <strong>naming variables</strong> (unique identifiers) for the variable.</p>
<p>Here are the rules below:</p>
<ul>
<li>Names can contain letters, Number digits(0-9), underscores <code>_</code>, and dollar signs <code>$</code> but Spaces and special symbols/punctuation characters (like <code>@</code>, <code>!</code>, <code>#</code>, etc.) are not allowed to be used in the variable's name.</li>
</ul>
<blockquote>
<p>Note: In Javascript '_' and '$' are just like letters. They don't have any special meaning.</p>
</blockquote>
<ul>
<li><p>Variable names must be started with either a letter, an underscore (<code>_</code>), or the dollar sign <code>$</code> in javascript. It is not allowed to start variable names using numbers (0-9).</p>
</li>
<li><p>JavaScript Names/identifiers are case sensitive (Variables named <code>apple</code> and <code>APPLE</code> are two different variables.).</p>
</li>
<li><p>There are some reserved words, which cannot be used as variable names in your program because they are used by the language itself.</p>
</li>
</ul>
<p><code>For example: let, var, for, and function are reserved.</code></p>
<p>The code below gives an Uncaught SyntaxError:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> <span class="hljs-keyword">var</span> = <span class="hljs-number">5</span>;   <span class="hljs-comment">//  Uncaught SyntaxError: Unexpected token 'var'</span>
<span class="hljs-keyword">let</span> <span class="hljs-function"><span class="hljs-keyword">function</span> = 5; // <span class="hljs-title">Uncaught</span> <span class="hljs-title">SyntaxError</span>: <span class="hljs-title">Unexpected</span> <span class="hljs-title">token</span> '<span class="hljs-title">function</span>'</span>
</code></pre>
<ul>
<li><p>In JavaScript, When the variable name contains multiple words, it is generally written in camelCase.<br />  That is: words go one after another, every word except the first one starting with a capital letter.</p>
<p>  <code>For example, firstName, lastName, birthYear, etc.</code></p>
</li>
<li><p>It is possible to use almost any language in a variable name, but not recommended. We should use English in variable names even if we’re writing a small script. so that if people from other countries need to read it they can read it. Because we will write code for global developers not only for our region.</p>
</li>
</ul>
<p>Here are some valid and invalid variable names below:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// Example of valid variables names</span>
<span class="hljs-keyword">let</span> camelCased         <span class="hljs-comment">//  first word is lowercase any additional word starts with an uppercase letter</span>
<span class="hljs-keyword">let</span> here2num                  <span class="hljs-comment">// number in the middle, but not starting with numbers</span>
<span class="hljs-keyword">let</span> JAVASCRIPT_IN_UPPERCASE       <span class="hljs-comment">// uppercase letters with underscores</span>
<span class="hljs-keyword">let</span> _Javascript_              <span class="hljs-comment">//start and end with an underscore, with letters in the middle</span>
<span class="hljs-keyword">let</span> $_$                       <span class="hljs-comment">// dollar signs and underscores</span>
<span class="hljs-keyword">let</span> $_foo3                <span class="hljs-comment">// mix the dollar sign, underscores, letters and numbers</span>
<span class="hljs-keyword">let</span> _12foo           <span class="hljs-comment">//start with underscores and contain numbers and letters</span>
<span class="hljs-keyword">let</span> _                 <span class="hljs-comment">//   contains only underscore</span>
<span class="hljs-keyword">let</span> $             <span class="hljs-comment">// contain only a dollar sign</span>


<span class="hljs-comment">// Example of invalid variables names</span>

<span class="hljs-keyword">let</span> random%         <span class="hljs-comment">//  Don't use the percentage symbol</span>
<span class="hljs-keyword">let</span> <span class="hljs-number">11</span>years           <span class="hljs-comment">//  Don't start with number(s)</span>
<span class="hljs-keyword">let</span> some-<span class="hljs-keyword">let</span>      <span class="hljs-comment">//  Don't use dashes</span>
<span class="hljs-keyword">let</span> one variable   <span class="hljs-comment">//  Don't use spaces</span>
<span class="hljs-keyword">let</span> <span class="hljs-function"><span class="hljs-keyword">function</span>           //  <span class="hljs-title">Don</span>'<span class="hljs-title">t</span> <span class="hljs-title">use</span> <span class="hljs-title">reserved</span> <span class="hljs-title">keywords</span></span>
</code></pre>
<p><strong>Task:</strong> Which of the following is a valid JavaScript variable name?</p>
<ol>
<li><p><code>123variable</code></p>
</li>
<li><p><code>var-name</code></p>
</li>
<li><p><code>_variable</code></p>
</li>
</ol>
<p>Write your answer in the comment section.</p>
<h3 id="heading-naming-variable-good-practices">Naming variable Good practices</h3>
<p>Giving a good name to the variable is one of the most important and complex skills in programming. Proper descriptive variable names can create a good impression for a programmer in the viewer's eyes.</p>
<p>In a real project, most of the time a programmer spends modifying and extending an existing code base rather than writing something completely new. When we return to the code after doing something else for a while or maybe for a long period of time, it’s much easier to get back into a flow for those codes that is well-labeled. Or, in other words, when the variables have been declared with good names.</p>
<p>So, Please spend time thinking about the right name when you are declaring a variable. Doing so will make you benefited in the future.</p>
<ul>
<li><p>Though variable names can be created in any way you want, it's a good practice to use human-readable, obvious meanings and maximally descriptive (the value the variable is referencing). If we name a variable as “user” then we should name related variables as currentUser or newUser.</p>
</li>
<li><p>Stay away from short names like a, b, and c. These kinds of short names are easy to type. But these are only useful in small programs. When you will work on a big project, will forget the context of these kinds of names.</p>
</li>
</ul>
<blockquote>
<p>Note: Though There is no limit to the length of the variable name and it can be almost unlimited in length, You should avoid creating extremely long variable names. Shorter variable names help the JavaScript engine to execute the program faster.</p>
</blockquote>
<ul>
<li><p>Since JavaScript is case-sensitive, apple and Apple are two different identifiers. But we should not use both of them in our program. Because this will occur confusion in the long term.</p>
</li>
<li><p>The best way to create a variable is to use multiple words in camelCase. (e.g., <code>myVarName</code>).</p>
</li>
</ul>
<h2 id="heading-undefined-value-of-a-variable">Undefined value of a variable</h2>
<p>When we declare a variable without assigning a value to it will have the value <code>undefined</code>.</p>
<p>It's the default behavior of javascript. Though this container should be empty, it is not. It still contains a value that is <code>undefined</code>.</p>
<blockquote>
<p>Note: <code>undefined</code> is one type of data in javascript. we will see about <code>undefined</code> and other data types in any other blog in detail.</p>
</blockquote>
<p>If you want to see their value, you can do that by simply doing <code>console.log()</code> in your web browser's console the output will be <code>undefined</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name, age, birthYear;
<span class="hljs-built_in">console</span>.log(name);          <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(age);           <span class="hljs-comment">// undefined</span>
<span class="hljs-built_in">console</span>.log(birthYear);     <span class="hljs-comment">// undefined</span>
</code></pre>
<h2 id="heading-undeclared-variable">Undeclared variable</h2>
<p>Suppose you want to use a variable in a statement, but you haven't declared this variable yet. In this case, your code will throw a <code>ReferenceError</code> showing that the variable is not defined. In short, if we want to access an Unassigned or <strong>undeclared variable</strong>, the code will throw a runtime error.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(xyz);  <span class="hljs-comment">// ReferenceError: xyz is not defined</span>
</code></pre>
<p>Try running the above line in the browser console.</p>
<p>In the real program, You should never try accessing a variable without declaring it.</p>
<blockquote>
<p>Note: Don't get confused with the undefined and Unassigned/<strong>Undeclared variable</strong> — they are very different things. An undefined variable is a variable that has been declared in the program but has not been initialized with a value. In contrast, an undeclared variable is a variable that has not been declared yet.</p>
</blockquote>
<h2 id="heading-variable-assignment">Variable Assignment</h2>
<p>After the declaration has been completed, we can use the equal(<code>=</code>) sign for <strong>Variable Assignment</strong>:</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age;
age = <span class="hljs-number">22</span>;
</code></pre>
<p>where the <code>age</code> is the name of the variable and it is assigned a value of <code>22</code>.</p>
<blockquote>
<p>Note: In JavaScript, the equal sign (<code>=</code>) is an <code>assignment operator</code>, not an <code>equal to</code> operator like in algebra. Though the following does not make sense in algebra:</p>
<pre><code class="lang-javascript">x = x + <span class="hljs-number">10</span>;
</code></pre>
</blockquote>
<p>But In JavaScript, it makes perfect sense:</p>
<p>First It calculates the value of <code>x + 10</code> and assigns the result to variable <code>x</code>. In simple words, The value of <code>x</code> is incremented by <code>10</code>.</p>
<blockquote>
<p>Note: in JavaScript, the "equal to" operator is written like <code>==</code>.</p>
</blockquote>
<p>Also, the <strong>Javascript variable declaration</strong> and initialization can be combined. that means variable initialization can be done in the declaration:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> greetings = <span class="hljs-string">"Hello"</span>;
<span class="hljs-keyword">let</span> name = <span class="hljs-string">"Robiul"</span>

<span class="hljs-comment">// or,</span>
<span class="hljs-keyword">var</span> greetings = <span class="hljs-string">"Hello"</span>, name = <span class="hljs-string">"Robiul"</span>;

<span class="hljs-comment">//The same declaration can even span across multiple lines using comma(,):</span>

<span class="hljs-keyword">var</span> greetings = <span class="hljs-string">"Hello"</span>, 
      name = <span class="hljs-string">"Robiul"</span>;
</code></pre>
<blockquote>
<p>Note: we can do <strong>Variable Assignment</strong> from user input</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Gets user input</span>
<span class="hljs-keyword">var</span> name = prompt(<span class="hljs-string">"What is your name?"</span>);
<span class="hljs-keyword">var</span> age = prompt(<span class="hljs-string">"What is your favorite age? "</span>);
<span class="hljs-built_in">console</span>.log(name)  
<span class="hljs-built_in">console</span>.log(age)
</code></pre>
</blockquote>
<h2 id="heading-changing-variable">Changing Variable</h2>
<p>The meaning of the word ‘variable’ is anything that can vary. That means once the initialization is finished we can change or update the value of the variable later on in the program if required.</p>
<p>It is similar to re-initializing the variable. We can do Updating or Re-assigning or <strong>Changing Variable</strong> by just typing the name of the variable followed by an equals sign(<code>=</code>) and then followed by the new value we want it to store.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> greetings = <span class="hljs-string">"Hello"</span>;
<span class="hljs-keyword">let</span> myHobby = <span class="hljs-string">"Drawing"</span>;
<span class="hljs-built_in">console</span>.log(greetings);   <span class="hljs-comment">// Hello</span>
<span class="hljs-built_in">console</span>.log(myHobby);   <span class="hljs-comment">// Drawing</span>

<span class="hljs-comment">// changing the value </span>
greetings = <span class="hljs-string">"Hi"</span>;
myHobby = <span class="hljs-string">"Programming"</span>
<span class="hljs-built_in">console</span>.log(greetings);   <span class="hljs-comment">// Hi</span>
<span class="hljs-built_in">console</span>.log(myHobby);   <span class="hljs-comment">// Programming</span>

<span class="hljs-comment">//   also, we can change the value as many times as we want:</span>

<span class="hljs-keyword">let</span> message;
message = <span class="hljs-string">"Hello"</span>;
<span class="hljs-built_in">console</span>.log(message);  <span class="hljs-comment">// Hello</span>
message = <span class="hljs-string">"World"</span>; 
<span class="hljs-built_in">console</span>.log(message);  <span class="hljs-comment">// World</span>
</code></pre>
<p><code>javascript variable doesn't contain the history of the variable, which means when we change the value of a variable it removes the old data and stores the new one.</code></p>
<blockquote>
<p>Note: There are a few functional programming languages, like Scala or Erlang that don't allow changing variable values.<br />In such languages, once the value is assigned in a variable, it’s there forever. If we want to reassign the variable or want to change the value of the variable, the language forces us to create a new variable (declare a new variable). We can’t reuse the old one.</p>
</blockquote>
<h2 id="heading-accessing-javascript-variables">Accessing JavaScript variables</h2>
<p>As a beginner, you might be thinking about what is the procedure to access/use the value that is stored in a specific variable. It's simpler than declaring and assigning the variable. You just need to write the name of the variable that contains the value you want to access and you are done. This things also called “referencing a variable”.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Declare and initialize the variable</span>
<span class="hljs-keyword">var</span> myNumVariable = <span class="hljs-number">85</span>
<span class="hljs-keyword">let</span> myTextVariable = <span class="hljs-string">'This is text.'</span>

<span class="hljs-comment">// Access the values in myNumVariable and myTextVariable</span>
myNumVariable
<span class="hljs-comment">// 85</span>
myTextVariable
<span class="hljs-comment">//  'This is text.'</span>


<span class="hljs-comment">// Re-assign myNumVariable and myTextVariable</span>
myNumVariable = <span class="hljs-number">50</span>
myTextVariable = <span class="hljs-string">'This is a updated Text'</span>


<span class="hljs-comment">// Access the values in myNumVariable and myTextVariable again</span>
myNumVariable
<span class="hljs-comment">// 50</span>
myTextVariable
<span class="hljs-comment">// 'This is a updated Text'</span>
</code></pre>
<h2 id="heading-basic-usage-of-variables">Basic usage of variables</h2>
<ul>
<li>Once you declare a variable and initialize it, you can reference this variable by name anywhere elsewhere in your code.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> x = <span class="hljs-number">10</span>;
x + <span class="hljs-number">2</span>;
<span class="hljs-built_in">console</span>.log(x)   <span class="hljs-comment">// 12</span>
</code></pre>
<ul>
<li>You can use an already declared variable when declaring a new variable.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> x = <span class="hljs-number">100</span>;
<span class="hljs-keyword">var</span> y = x + <span class="hljs-number">102</span>;
<span class="hljs-built_in">console</span>.log(y)  <span class="hljs-comment">// 202</span>
</code></pre>
<ul>
<li>you can do all kinds of arithmetic operations with <strong>JavaScript variables</strong>, using operators like <code>=</code>, <code>+</code>, <code>*</code>, and more. :</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> x = <span class="hljs-number">5</span> + <span class="hljs-number">2</span> + <span class="hljs-number">3</span>;
<span class="hljs-built_in">console</span>.log(x)  <span class="hljs-comment">// 10</span>
</code></pre>
<ul>
<li>You can also add a string to another string, but strings will be concatenated:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> x = <span class="hljs-string">"John"</span> + <span class="hljs-string">" "</span> + <span class="hljs-string">"Doe"</span>;
<span class="hljs-built_in">console</span>.log(x)   <span class="hljs-comment">// John Doe</span>
</code></pre>
<blockquote>
<p>Note: During arithmetic operations If you put a number in quotes, the rest of the numbers will be treated as strings, and all of them will be concatenated. Now try this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> y = <span class="hljs-string">"5"</span> + <span class="hljs-number">2</span> + <span class="hljs-number">3</span>;
<span class="hljs-built_in">console</span>.log(y)   <span class="hljs-comment">// 523</span>
</code></pre>
<p>This is called coercion in javascript</p>
</blockquote>
<h2 id="heading-why-should-we-use-variable">Why should we use variable</h2>
<p>So far we have discussed what is variable, how to create it, and how it works in our program. But haven't discussed why this is so important and why should we use the variable.</p>
<p>Let's have a look at this too. we will discuss some point on how variable helps programmers to write optimized and efficient code :</p>
<p>To Understand these points let's see a program of a pretty simple and state-forward game called guess my number. This game logic is very simple, we will use a number in our code and the user will have to guess the number if the user guesses the correct number our program will show a successful message and if the user is wrong the program will show a failed message.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span>(userInput==<span class="hljs-number">20</span>){
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hurrah, You guess the correct number."</span>);
}<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(userInput&lt;<span class="hljs-number">20</span>){
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sorry, Your guessed number is small. Please try a bigger one."</span>)
}<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(useInput&gt;<span class="hljs-number">20</span>){
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sorry, Your guessed number is Big. Please try a bigger one."</span>)
}
</code></pre>
<p>Here in this program, we have used the number <code>20</code> to make our program logic. This program will perform fine but this program is not well coded.</p>
<p>let's see what's wrong with this program and why this is not well coded and how variable makes our life easy and help us to make our code more efficient and optimized:</p>
<ul>
<li><p>The first problem with this program is we have to memorize the number <code>20</code> or have to check the number again and again whenever we will use it in our program. Maybe it doesn't seem a big problem for a small program and simple value like this but imagines a program that has a thousand lines of code and maybe hundreds of value like this number or maybe some huge numbers like <code>204025021</code>, <code>12242250221</code> and we can't memorize all of them.</p>
<p>  Here variable helps us by giving a simple solution to deal with this kind of problem. we can simply store the value on a variable and just use a simple and descriptive name rather than using scary and ugly numbers every time when we need. so, Now we don't have to remember the number or any kind of value we can just remember the name we have given to the variable and use it anywhere in our program.</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myNum = <span class="hljs-number">20</span>;
<span class="hljs-keyword">if</span>(userInput==myNum){
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hurrah, You guess the correct number."</span>);
}<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(userInput&lt;myNum){
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sorry, Your guessed number is small. Please try a bigger one."</span>)
}<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(useInput&gt;myNum){
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sorry, Your guessed number is Big. Please try a bigger one."</span>)
}
</code></pre>
<ul>
<li><p>Now here comes the second problem with this code. that is when we will try to change the number we have to change the number from every place where we have used the number. and imagine when we will work on a big project we have to use a variable in several places. if we would need to change the value from all the places how painful and time-consuming it would be.</p>
<p>  Here variable gives us an opportunity to change the variable in all places by changing it in one place. we can store our value in a variable and use it anywhere in our program. whenever we need to change it we can just simply change it from one place and it will change everywhere.</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myNum = <span class="hljs-number">20</span>;
<span class="hljs-built_in">console</span>.log(myNumber) <span class="hljs-comment">// 20</span>
<span class="hljs-keyword">if</span>(userInput==myNum){
<span class="hljs-built_in">console</span>.log(myNumber) <span class="hljs-comment">// 20</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hurrah, You guess the correct number."</span>);
}<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(userInput&lt;myNum){
  <span class="hljs-built_in">console</span>.log(myNumber) <span class="hljs-comment">// 20</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sorry, Your guessed number is small. Please try a bigger one."</span>)
}<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(useInput&gt;myNum){
  <span class="hljs-built_in">console</span>.log(myNumber) <span class="hljs-comment">// 20</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sorry, Your guessed number is Big. Please try a bigger one."</span>)
}
<span class="hljs-comment">// change the value</span>
myNum = <span class="hljs-number">30</span>;
<span class="hljs-built_in">console</span>.log(myNumber) <span class="hljs-comment">// 30</span>
<span class="hljs-keyword">if</span>(userInput==myNum){
  <span class="hljs-built_in">console</span>.log(myNumber) <span class="hljs-comment">// 30</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hurrah, You guess the correct number."</span>);
}<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(userInput&lt;myNum){
  <span class="hljs-built_in">console</span>.log(myNumber) <span class="hljs-comment">// 30</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sorry, Your guessed number is small. Please try a bigger one."</span>)
}<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(useInput&gt;myNum){
  <span class="hljs-built_in">console</span>.log(myNumber) <span class="hljs-comment">// 30</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sorry, Your guessed number is Big. Please try a bigger one."</span>)
}
</code></pre>
<p>how simple it is! right?</p>
<ul>
<li><p>Another program with this program is we are using the number in a statical way. That means our program is not dynamic now. If we need any changed value we have to edit the source code which is very bad. To write a modern program we should have a feature to change the value dynamically.</p>
<p>  Here Variable gives us the best and simplest way to do that. we can simply create a variable and assign the value of the variable from a user input rather than assigning it statically.</p>
</li>
</ul>
<pre><code class="lang-javascript">  <span class="hljs-keyword">let</span> myNum =  prompt(<span class="hljs-string">"enter a number?"</span>);
<span class="hljs-keyword">if</span>(userInput==myNum){
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hurrah, You guess the correct number."</span>);
}<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(userInput&lt;myNum){
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sorry, Your guessed number is small. Please try a bigger one."</span>)
}<span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(useInput&gt;myNum){
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sorry, Your guessed number is Big. Please try a bigger one."</span>)
}
</code></pre>
<p>Now our code is dynamic we can change the value whenever we want without changing or editing the source code.</p>
<p>Thus, variable helps us to write optimized, developer-friendly, and easy-to-understand code.</p>
<blockquote>
<p>Note: Though variable helps us in many ways. but too many variables can harm the code performance very badly and it's can increase the server cost. so, we should be careful when we are declaring a variable.</p>
</blockquote>
<h2 id="heading-recap">Recap</h2>
<ul>
<li><p>A variable is a computer memory location paired with an associated symbolic name, which contains some information or data referred to as a value.</p>
</li>
<li><p>We can simply think of <strong>Javascript variables</strong> as named containers that hold information and can be referred to the data simply by naming the container.</p>
</li>
<li><p>We can Declare a JavaScript Variable using <code>var</code> or <code>let</code>.</p>
</li>
<li><p>All <strong>JavaScript variables</strong> must be identified with unique names. These unique names are called identifiers.</p>
</li>
<li><p>There are some general rules to follow when we are constructing a name (unique identifiers) for the variable.</p>
</li>
<li><p>A variable declared without a value will have the value undefined.</p>
</li>
<li><p>A variable that has not been declared yet is called an undeclared.</p>
</li>
<li><p>After the declaration, we can use the equal(<code>=</code>) sign to assign value to the variable</p>
</li>
<li><p>You can combine <strong>variable declaration</strong> with variable initialization. that means initialization can be done in the declaration.</p>
</li>
<li><p>Once a variable has been initialized with a value, you can change (or update) that value anytime and anywhere within its scope by giving it a different value.</p>
</li>
<li><p>We can access a value of a variable simply by using the name of the variable. This is also called “referencing a variable”.</p>
</li>
<li><p>You can reference a variable by name elsewhere in your code.</p>
</li>
<li><p>You can use a variable when declaring other variables.</p>
</li>
<li><p>You can do arithmetic with <strong>JavaScript variables</strong>, using operators like <code>=</code> and <code>+</code>.</p>
</li>
<li><p>You can also add strings, but strings will be concatenated.</p>
</li>
<li><p>variable helps us to write optimized and efficient code. Though it is helpful in many ways, too many variables can be harmful. so, we should be careful of it.</p>
</li>
</ul>
<h2 id="heading-resources">Resources</h2>
<ul>
<li><p><a target="_blank" href="https://www.w3schools.com/js/js_variables.asp">JavaScript Variables</a></p>
</li>
<li><p><a target="_blank" href="https://javascript.info/variables">Variables</a></p>
</li>
<li><p><a target="_blank" href="https://www.javascripttutorial.net/javascript-variables">JavaScript Variables</a></p>
</li>
<li><p><a target="_blank" href="https://www.freecodecamp.org/news/javascript-variables-beginners-guide">JavaScript Variables – A Beginner's Guide to var, const, and let</a></p>
</li>
<li><p><a target="_blank" href="https://www.scaler.com/topics/javascript/javascript-variables/">Javascript variables</a></p>
</li>
<li><p><a target="_blank" href="https://blog.alexdevero.com/javascript-variables-introduction/">Introduction to JavaScript Variables – What You Should to Know</a></p>
</li>
<li><p><a target="_blank" href="https://medium.com/@avishaa27/what-are-variables-in-javascript-3aa9a3324a1e">What are Variables in JavaScript ?</a></p>
</li>
<li><p><a target="_blank" href="https://www.javascript.com/learn/variables">VARIABLES</a></p>
</li>
<li><p><a target="_blank" href="https://www.toolsqa.com/javascript/javascript-variables">JavaScript Variables</a></p>
</li>
<li><p><a target="_blank" href="https://data-flair.training/blogs/javascript-variable-tutorial/">JavaScript Variables – A to Z Guide for a Newbie in JavaScript!</a></p>
</li>
<li><p><a target="_blank" href="https://medium.com/@shreyanshshah242/variables-in-javascript-13099376b279">Variables in JavaScript</a></p>
</li>
</ul>
]]></content:encoded></item></channel></rss>