<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Musab Habeeb - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Musab Habeeb - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 20 May 2026 20:47:03 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/Musab19/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ A Guide to the Node.js Event Loop ]]>
                </title>
                <description>
                    <![CDATA[ Node.js is an open-source JavaScript runtime environment that allows you to run JavaScript outside the browser. Although Node.js is single-threaded, it has an event loop that makes it multi-threaded. The Node.js event loop is a crucial mechanism in N... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-guide-to-the-node-js-event-loop/</link>
                <guid isPermaLink="false">66d46040c7632f8bfbf1e445</guid>
                
                    <category>
                        <![CDATA[ node js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Musab Habeeb ]]>
                </dc:creator>
                <pubDate>Tue, 28 May 2024 07:00:35 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/Node.js-event-loop.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Node.js is an open-source JavaScript runtime environment that allows you to run JavaScript outside the browser. Although Node.js is single-threaded, it has an event loop that makes it multi-threaded.</p>
<p>The Node.js event loop is a crucial mechanism in Node.js that makes Node.js programs run concurrently and asynchronously. Mastering the Node.js event loop helps a Node.js developer understand how Node.js programs run under the hood.</p>
<p>In this article, you will learn the basics of the event loop, starting with threads and processes, then how the JavaScript event loop works, and finally, how the Node.js event loop works.</p>
<h2 id="heading-what-are-threads-and-process">What are Threads and Process?</h2>
<p>To master the Node.js event loop, you must understand processes and threads.</p>
<p>A programmer can write programs that perform different tasks with different programming languages. While some programming languages can run just one task at a time, other programming languages can run several tasks simultaneously.</p>
<p>A process involves several tasks running in a program from start to finish, while a thread is the running of an individual task.</p>
<p>A process consists of all the steps a program takes to run till completion. It is a currently executing program. A program may have one or more independent processes, each having its own memory space or address. A process may have one or more threads in it.</p>
<p>A thread is a single unit of execution that is part of a process, like a task in a program. A thread has a thread ID, a register set, and a stack. A thread also shares its code section, data section, operating system resources, and memory space with other threads in a process.</p>
<p>The code below contains an <code>isNumberEven</code> function that checks if a number is even and an <code>isNumberOdd</code> function that checks if a number is odd. A process involves running this code from start to finish, while a thread involves running individual functions.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isNumberEven</span>(<span class="hljs-params">number</span>) </span>{
  <span class="hljs-keyword">if</span> (number % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isNumberOdd</span>(<span class="hljs-params">number</span>) </span>{
  <span class="hljs-keyword">if</span> (number % <span class="hljs-number">2</span> !== <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}

isNumberEven(<span class="hljs-number">6</span>);
isNumberOdd(<span class="hljs-number">1</span>);
</code></pre>
<h3 id="heading-what-are-single-threads-and-multi-threads">What are Single-threads and Multi-threads?</h3>
<p>All programming languages have a runtime engine that runs their code. Some runtime engines are single-threaded (which means they can only run one thread at a time), while some are multi-threaded (which means they can run more than one thread at a time).</p>
<p>The diagram below shows a single-threaded process and a multi-threaded process:</p>
<p><img src="https://hackmd.io/_uploads/SJkCXfQTa.jpg" alt="Single threads and Multi threads" width="600" height="400" loading="lazy"></p>
<p><em>Single-threaded and Multi-threaded Processes</em></p>
<p>A single-threaded programming language has a single-threaded runtime engine that runs tasks in a program sequentially. A multi-threaded programming language has a multi-threaded runtime engine that runs tasks in a program simultaneously. A multi-threaded runtime engine is more performant than a single-threaded runtime engine.</p>
<p>Programming languages like Java, C#, and so on are multi-threaded, while languages like JavaScript, Python, and so on are single-threaded.</p>
<p>Single-threaded programming languages are synchronous, which means they run the task in their programs sequentially. JavaScript is synchronous, but its event loop makes it asynchronous.</p>
<p>In the upcoming sections, you will learn how the JavaScript event loop works and then master the Node.js event loop.</p>
<h2 id="heading-how-the-javascript-event-loop-works">How the JavaScript Event Loop Works</h2>
<p>You must understand how the JavaScript runtime engine runs JavaScript code for you to understand the JavaScript event loop.</p>
<p>The JavaScript runtime engine consists primarily of the:</p>
<ul>
<li><p>Memory heap and</p>
</li>
<li><p>Call stack</p>
</li>
</ul>
<p>The memory heap is where variables declared in the program are allocated memory space, and the call stack is where the runtime engine stores functions in the program for execution.</p>
<p>The JavaScript runtime engine runs the code below synchronously and in this step-by-step process:</p>
<ul>
<li><p>It allocates memory space for all the variables in the code.</p>
</li>
<li><p>It executes the <code>exponentiation</code> function after pushing onto the call stack.</p>
</li>
<li><p>It executes the <code>validatePassword</code> function after pushing it onto the call stack.</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">exponentiation</span>(<span class="hljs-params">base, exponent</span>) </span>{
  <span class="hljs-keyword">let</span> result = <span class="hljs-number">1</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; exponent; i++) {
    result *= base;
  }
  <span class="hljs-keyword">return</span> result;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">validatePassword</span>(<span class="hljs-params">password</span>) </span>{
  <span class="hljs-keyword">const</span> hasUppercase = <span class="hljs-regexp">/[A-Z]/</span>.test(password);
  <span class="hljs-keyword">const</span> hasLowercase = <span class="hljs-regexp">/[a-z]/</span>.test(password);
  <span class="hljs-keyword">const</span> hasNumber = <span class="hljs-regexp">/[0-9]/</span>.test(password);
  <span class="hljs-keyword">const</span> isValidLength = password.length &gt;= <span class="hljs-number">8</span>;

  <span class="hljs-keyword">if</span> (hasUppercase &amp;&amp; hasLowercase &amp;&amp; hasNumber &amp;&amp; isValidLength) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"password is valid"</span>;
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"password is invalid"</span>;
  }
}

exponentiation(<span class="hljs-number">5</span>, <span class="hljs-number">3</span>);
validatePassword(<span class="hljs-string">"Ab01234"</span>);
</code></pre>
<p>If your code contains a blocking function, which is a function that takes a lot of time to run, the function will block other functions from running until it completes. Users can’t interact with a website that has a blocking function as part of its code while the function runs.</p>
<p>The code below contains the <code>fibonacci</code> function, which takes time to run. The runtime engine starts running the <code>factorial</code> function first, then the <code>fibonacci</code> function, during which the <code>findMin</code> function can’t run.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">factorial</span>(<span class="hljs-params">n</span>) </span>{
  <span class="hljs-keyword">if</span> (n === <span class="hljs-number">0</span> || n === <span class="hljs-number">1</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
  }
  <span class="hljs-keyword">let</span> result = <span class="hljs-number">1</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">2</span>; i &lt;= n; i++) {
    result *= i;
  }
  <span class="hljs-keyword">return</span> result;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fibonacci</span>(<span class="hljs-params">num</span>) </span>{
  <span class="hljs-keyword">if</span> (num &lt;= <span class="hljs-number">1</span>) {
    <span class="hljs-keyword">return</span> num;
  }
  <span class="hljs-keyword">return</span> fibonacci(num - <span class="hljs-number">1</span>) + fibonacci(num - <span class="hljs-number">2</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findMin</span>(<span class="hljs-params">numbers</span>) </span>{
  <span class="hljs-keyword">if</span> (!numbers || numbers.length === <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Empty array provided"</span>);
  }

  <span class="hljs-keyword">let</span> min = numbers[<span class="hljs-number">0</span>];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt; numbers.length; i++) {
    <span class="hljs-keyword">if</span> (numbers[i] &lt; min) {
      min = numbers[i];
    }
  }
  <span class="hljs-keyword">return</span> min;
}

<span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">4</span>, <span class="hljs-number">2</span>, <span class="hljs-number">8</span>, <span class="hljs-number">1</span>, <span class="hljs-number">6</span>];

factorial(<span class="hljs-number">5</span>);

fibonacci(<span class="hljs-number">45</span>);

findMin(numbers);
</code></pre>
<p>To make the program in the example above run asynchronously, you should make the <code>fibonacci</code> function non-blocking with JavaScript web APIs.</p>
<p>JavaScript web APIs do not run on the main thread but instead create their threads, which enables them to run concurrently and not block the execution of other functions in your code.</p>
<p>You can use these JavaScript web APIs to make your functions non-blocking:</p>
<ul>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/setTimeout">setTimeout</a></p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/AJAX">AJAX</a> and</p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction">DOM</a></p>
</li>
</ul>
<p>So, if you add a <code>setTimeout</code> to your code like this:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">factorial</span>(<span class="hljs-params">n</span>) </span>{
  <span class="hljs-keyword">if</span> (n === <span class="hljs-number">0</span> || n === <span class="hljs-number">1</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
  }
  <span class="hljs-keyword">let</span> result = <span class="hljs-number">1</span>;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">2</span>; i &lt;= n; i++) {
    result *= i;
  }
  <span class="hljs-keyword">return</span> result;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fibonacci</span>(<span class="hljs-params">num</span>) </span>{
  <span class="hljs-keyword">if</span> (num &lt;= <span class="hljs-number">1</span>) {
    <span class="hljs-keyword">return</span> num;
  }
  <span class="hljs-keyword">return</span> fibonacci(num - <span class="hljs-number">1</span>) + fibonacci(num - <span class="hljs-number">2</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">findMin</span>(<span class="hljs-params">numbers</span>) </span>{
  <span class="hljs-keyword">if</span> (!numbers || numbers.length === <span class="hljs-number">0</span>) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Empty array provided"</span>);
  }

  <span class="hljs-keyword">let</span> min = numbers[<span class="hljs-number">0</span>];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt; numbers.length; i++) {
    <span class="hljs-keyword">if</span> (numbers[i] &lt; min) {
      min = numbers[i];
    }
  }
  <span class="hljs-keyword">return</span> min;
}

<span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">4</span>, <span class="hljs-number">2</span>, <span class="hljs-number">8</span>, <span class="hljs-number">1</span>, <span class="hljs-number">6</span>];

factorial(<span class="hljs-number">5</span>);

<span class="hljs-built_in">setTimeout</span>(fibonacci(<span class="hljs-number">45</span>), <span class="hljs-number">3000</span>);

findMin(numbers);
</code></pre>
<p>The <code>factorial</code> and <code>findMin</code> functions will run on the main thread, while the <code>fibonacci</code> function runs concurrently on a separate thread.</p>
<p>To properly understand how the program above runs, you must understand how the JavaScript event loop works. The JavaScript event loop is a mechanism by which tasks in a JavaScript program run asynchronously.</p>
<p>The JavaScript event loop has a callback queue that stores functions that take time to execute.</p>
<p>The event loop sends functions that execute immediately to the callback queue for execution and sends blocking functions to web API threads for execution.</p>
<p>Then, the event loop sends the blocking function back to the callback queue when the set time elapses. The event loop then checks if the call stack is empty before pushing the function in the callback queue to the call stack for execution.</p>
<p>The diagram below explains how the event loop in JavaScript works:</p>
<p><img src="https://hackmd.io/_uploads/B1AMVMQpa.jpg" alt="JavaScript event loop" width="600" height="400" loading="lazy"></p>
<p><em>The JavaScript event loop</em></p>
<p>The code above that contains <code>factorial</code>, <code>fibonacci</code>, and <code>findMin</code> functions is executed like this after adding a <code>setTimeout</code> function.</p>
<p>The event loop pushes the <code>factorial</code> function onto the call stack for execution. Then, the event loop pushes the <code>fibonacci</code> function onto the call stack, but the <code>fibonacci</code> function has a <code>setTimeout</code> function that prevents it from executing immediately. So, the event loop pushes the <code>fibonacci</code> function to a separate thread for web APIs to run concurrently.</p>
<p>Then, the event loop pushes the <code>findMin</code> function onto the call stack for execution. When the time set in the <code>setTimeout</code> elapses, the event loop pushes the <code>fibonacci</code> function to the call stack for execution.</p>
<h2 id="heading-how-the-nodejs-event-loop-works">How The Node.js Event Loop Works</h2>
<p>Node.js is a JavaScript runtime environment that enables JavaScript to run outside the browser, like on the command line interface, servers, and hardware.</p>
<p>Node.js has an event loop that is similar to the JavaScript event loop. The Node.js event loop and the JavaScript event loop have a call stack and a callback queue. The Node.js event loop is implemented and managed by a library named <a target="_blank" href="https://libuv.org/">libuv</a> written in C.</p>
<p>The Node.js event loop has six phases, which are:</p>
<ul>
<li><p>Timer phase</p>
</li>
<li><p>Pending Callbacks Phase</p>
</li>
<li><p>Idle Phase</p>
</li>
<li><p>Poll Phase</p>
</li>
<li><p>Check Phase</p>
</li>
<li><p>Close Callbacks Phase</p>
</li>
</ul>
<p>The diagram below shows how the Node.js event loop works:</p>
<p><img src="https://hackmd.io/_uploads/SkiVEMXTp.jpg" alt="Node.js event loop" width="600" height="400" loading="lazy"></p>
<p><em>The Node.js event loop</em></p>
<p>There is a microtask queue that exists outside of the Node.js event loop. The microtask queue consists of the <code>nextTick queue</code> and the <code>Promise queue</code>. The <code>nextTick queue</code> runs the <code>process.nextTick</code> function, while the <code>Promise queue</code> runs <code>.then</code>, <code>.catch</code>, and other promises.</p>
<p>In the upcoming sections, you will learn about each phase of the Node.js event loop.</p>
<h3 id="heading-timer-phase">Timer Phase</h3>
<p>There are three timers in Node.js: <code>setTimeout</code>, <code>setInterval</code>, and <code>setImmediate</code>. <code>setTimeout</code> and <code>setInterval</code> run in the timer phase. The code sample below runs during the timer phase:</p>
<pre><code class="lang-javascript"><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">"setTimeout callback executed"</span>);
}, <span class="hljs-number">1000</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">"setInterval callback executed"</span>);
}, <span class="hljs-number">2000</span>);
</code></pre>
<h3 id="heading-pending-callbacks-phase">Pending Callbacks Phase</h3>
<p>I/O operations execute in the poll phase of the event loop. During the poll phase, some specific I/O operations callbacks defer to the pending phase of the next iteration of the event loop. I/O operations callbacks deferred from the previous iteration run in the pending callbacks phase.</p>
<p>The code sample below runs during the ‘pending callbacks’ phase:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">"fs"</span>);

fs.readFile(__filename, <span class="hljs-function">(<span class="hljs-params">err, data</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (err) <span class="hljs-keyword">throw</span> err;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"File data:"</span>, data);
});
</code></pre>
<h3 id="heading-idle-phase">Idle Phase</h3>
<p>The idle phase is not a normal phase of the Node.js event loop. It is a period whereby the event loop has nothing to do but perform background tasks like checking for low-priority results or running garbage collection.</p>
<p>To skip the idle phase and not perform background tasks, you can call the <code>idle.ignore()</code> method from the <a target="_blank" href="https://www.npmjs.com/package/idle-gc">idle-gc</a> package in your code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { idle } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"idle-gc"</span>);

idle.ignore();
</code></pre>
<p>The <code>idle.ignore()</code> method ensures that the code continues to run without any idle period till completion. However, due to the performance issues it causes, the <code>idle.ignore()</code> method should be used sparingly.</p>
<h3 id="heading-poll-phase">Poll Phase</h3>
<p>The poll phase is where I/O operations execute. I/O operations transfer data to or from a computer. The event loop checks for new I/O operations and executes them in the poll queue.</p>
<p>The code sample below runs during the poll phase:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">"http"</span>);

http.get(<span class="hljs-string">"http://jsonplaceholder.typicode.com/posts/1"</span>, <span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"HTTP request response received"</span>);
  res.on(<span class="hljs-string">"data"</span>, <span class="hljs-function">(<span class="hljs-params">chunk</span>) =&gt;</span> {
    <span class="hljs-comment">// Do something with the data</span>
  });
});
</code></pre>
<h3 id="heading-check-phase">Check Phase</h3>
<p>The check phase is where the <code>setImmediate</code> timer runs. The Node.js event loop goes to the check phase when there is a <code>setImmediate</code> in the program, and the poll phase becomes idle or when the poll phase completes.</p>
<p>The code sample below runs during the check phase:</p>
<pre><code class="lang-javascript">setImmediate(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"setImmediate callback executed"</span>);
});
</code></pre>
<h3 id="heading-close-callbacks-phase">Close Callbacks Phase</h3>
<p>The close callbacks phase is the last phase of the Node.js event loop. The close callback phase is where callbacks from the close event of a socket and the closing of an <code>HTTP</code> server run.</p>
<p>The code sample below runs during the check phase:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">"http"</span>);

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

server.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 listening on port 3000'</span>);
  server.close(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server closed'</span>);
  });
});
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The Node.js event loop is the mechanism that enables asynchronous programming in Node.js.</p>
<p>As a Node.js developer, you can understand how your Node.js code runs under the hood if you master the Node.js event loop.</p>
<p>This article explained processes and threads, the JavaScript event loop, and the Node.js event loop.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Asynchronous Programming in JavaScript – Callbacks, Promises, & Async/Await Examples ]]>
                </title>
                <description>
                    <![CDATA[ All programming languages have runtime engines that execute their code. In JavaScript, the runtime engine is single-threaded, which means that it runs code line by line or sequentially. The JavaScript runtime engine makes it a synchronous programming... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/asynchronous-programming-in-javascript-examples/</link>
                <guid isPermaLink="false">66d46042b3016bf139028d63</guid>
                
                    <category>
                        <![CDATA[ async/await ]]>
                    </category>
                
                    <category>
                        <![CDATA[ asynchronous programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ callbacks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ promises ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Musab Habeeb ]]>
                </dc:creator>
                <pubDate>Fri, 02 Feb 2024 16:04:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Await-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>All programming languages have runtime engines that execute their code. In JavaScript, the runtime engine is single-threaded, which means that it runs code line by line or sequentially.</p>
<p>The JavaScript runtime engine makes it a synchronous programming language where programs run sequentially. Programming languages that are not synchronous are called asynchronous programming languages, which are programming languages where programs run concurrently.</p>
<p>Although JavaScript is synchronous, you can perform asynchronous programming with it. In this article, you will learn about asynchronous programming in JavaScript and how to use it.</p>
<h2 id="heading-what-is-asynchronous-programming">What is Asynchronous Programming?</h2>
<p>Asynchronous programming is a technique that allows your program to run its tasks concurrently. You can compare asynchronous programming to a chef with multiple cookers, pots, and kitchen utensils. This chef will be able to cook various dishes at a time.</p>
<p>Asynchronous programming makes your JavaScript programs run faster, and you can perform asynchronous programming with any of these:</p>
<ul>
<li><p>Callbacks</p>
</li>
<li><p>Promises</p>
</li>
<li><p>Async/Await</p>
</li>
</ul>
<p>In the upcoming sections, you will learn about these techniques and how to use them.</p>
<h2 id="heading-callbacks">Callbacks</h2>
<p>A callback is a function used as an argument in another function. Callbacks allow you to create asynchronous programs in JavaScript by passing the result of a function into another function.</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">`Hi <span class="hljs-subst">${name}</span>, how do you do?`</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayGreeting</span>(<span class="hljs-params">callback</span>) </span>{
    <span class="hljs-keyword">let</span> name = prompt(<span class="hljs-string">"Please enter your name"</span>);
    callback(name);
};

displayGreeting(greet);
</code></pre>
<p>In the code above, the <code>greet</code> function is used to log a greeting to the console, and it needs the name of the person to be greeted.</p>
<p>The <code>displayGreeting</code> function gets the person's name and has a callback that passes the name as an argument to the <code>greet</code> function while calling it. Then the <code>displayGreeting</code> function is called with the greet function passed to it as an argument.</p>
<h3 id="heading-callback-hell">Callback hell</h3>
<p>Although callbacks make it easy to control and make your program asynchronous, you'll eventually run into a problem called callback hell while using them.</p>
<p>This problem arises when you perform multiple asynchronous tasks with callbacks, which might result in nesting callbacks in callbacks.</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">greet</span>(<span class="hljs-params">callback</span>) </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">"Hi Musab"</span>);
        callback();
    }, <span class="hljs-number">1000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">introduce</span>(<span class="hljs-params">callback</span>) </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">"I am your academic advisor"</span>);
        callback();
    }, <span class="hljs-number">1000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">question</span>(<span class="hljs-params">callback</span>) </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">"Are you currently facing any challenge in your academics"</span>);;
        callback();
    }, <span class="hljs-number">1000</span>);
}

<span class="hljs-comment">// callback hell</span>
greet(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    introduce(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        question(<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">"Done"</span>);
        });
    });
});
</code></pre>
<p>In the code above, the <code>greet</code>, <code>introduce</code>, and <code>question</code> functions are nested to create a callback hell, which makes error handling difficult. You should change your asynchronous programming technique from callbacks to <code>Promise</code> to avoid the callback hell.</p>
<h2 id="heading-promise">Promise</h2>
<p>Most programs consist of a producing code that performs a time-consuming task and a consuming code that needs the result of the producing code.</p>
<p>A <code>Promise</code> links the producing and the consuming code together. In the example below, the <code>displayGreeting</code> function is the producing code while the <code>greet</code> function is the consuming code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name;

<span class="hljs-comment">// producing code</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayGreeting</span>(<span class="hljs-params">callback</span>) </span>{
    name = prompt(<span class="hljs-string">"Please enter your name"</span>);
}

<span class="hljs-comment">// consuming code</span>
<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">`Hi <span class="hljs-subst">${name}</span>, how do you do?`</span>);
}
</code></pre>
<p>In the example below, the <code>new Promise</code> syntax creates a new <code>Promise</code>, which takes a function that executes the producing code. The function either resolves or rejects its task and assigns the <code>Promise</code> to a variable named <code>promise</code>.</p>
<p>If the producing code resolves, its result will be passed to the consuming code through the <code>.then</code> handler.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayGreeting</span>(<span class="hljs-params"></span>) </span>{
    name = prompt(<span class="hljs-string">"Please enter your name"</span>);
}

<span class="hljs-keyword">let</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">resolve, reject</span>) </span>{
    <span class="hljs-comment">// the producing code</span>
    displayGreeting();
    resolve(name)
});

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">result</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi <span class="hljs-subst">${result}</span>, how do you do?`</span>);
}

promise.then(
    <span class="hljs-comment">// the consuming code</span>
    <span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> greet(result),
    <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> alert(error)
);
</code></pre>
<p>You can convert the previous callback hell's example to a promise by returning a promise from each function and chaining the function calls together with the <code>.then</code> handler.</p>
<p>You can also use the <code>.catch</code> handler to catch any error thrown during the function execution.</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"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</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">"Hi Musab"</span>);
            resolve();
        }, <span class="hljs-number">1000</span>);
    });  
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">introduce</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</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">"I am your academic advisor"</span>);
            resolve();
        }, <span class="hljs-number">1000</span>);
    });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">question</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</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">"Are you currently facing any challenge in your academics"</span>);;
            resolve();
        }, <span class="hljs-number">1000</span>);
    });
}

greet()
    .then(<span class="hljs-function">() =&gt;</span> introduce())
    .then(<span class="hljs-function">() =&gt;</span> question())
    .then(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Done"</span>))
    .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"An error occured: "</span>, error));
</code></pre>
<h3 id="heading-what-are-the-states-of-a-promise-in-javascript">What are the States of a Promise in JavaScript?</h3>
<p>A promise can be in any of these three states:</p>
<ul>
<li><p>Pending: This is the initial state of the promise and its state while it's still running.</p>
</li>
<li><p>Fulfilled: This is the state of the promise when it resolves successfully.</p>
</li>
<li><p>Rejected: This is the state of the promise when errors make it not to be resolved.</p>
</li>
</ul>
<h2 id="heading-asyncawait">Async/Await</h2>
<p><code>async</code>/<code>await</code> is syntactic sugar for creating a <code>Promise</code> — it makes creating promises easier.</p>
<p>To make a function asynchronous using <code>async</code>/<code>await</code>, you have to write the <code>async</code> keyword before the function declaration. Then, you can write the <code>await</code> keyword before the producing code's execution call.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayGreeting</span>(<span class="hljs-params"></span>) </span>{
    name = prompt(<span class="hljs-string">"Please enter your name"</span>);
    <span class="hljs-keyword">return</span> name;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">result</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi <span class="hljs-subst">${result}</span>, how do you do?`</span>);
}

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greeting</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// the producing code</span>
    <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">await</span> displayGreeting();
    <span class="hljs-comment">// the consuming code</span>
    greet(result);
};

greeting();
</code></pre>
<p>In the example above, the producing code is the <code>displayGreeting</code> function, and the consuming code is the <code>greet</code> function. The <code>greeting</code> function is the <code>Promise</code> that connects the producing and the consuming code. It waits for the result returned from the <code>displayGreeting</code> function and passes that result to the greet function.</p>
<h3 id="heading-error-handling-in-asyncawait">Error Handling in Async/Await</h3>
<p>You can easily handle errors that arise when you perform asynchronous operations with <code>async</code>/<code>await</code> using the <code>try...catch</code> statement. The asynchronous operation executes in the <code>try</code> block, and you can handle errors in the <code>catch</code> block.</p>
<p>That is:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greeting</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">let</span> result = <span class="hljs-keyword">await</span> displayGreeting();
        greet(result);
    } <span class="hljs-keyword">catch</span>(err) {
        <span class="hljs-built_in">console</span>.error(err)
    }
};
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Asynchronous programming in JavaScript is used to make tasks in a program run concurrently and uses techniques such as callbacks, <code>Promise</code>, or <code>async</code>/<code>await</code>.</p>
<p>This article explains how to use these asynchronous programming techniques and how to handle errors with them.</p>
<p>You can check the <a target="_blank" href="https://javascript.info/async">promises and async/await section on the JavaScript.info website</a> to learn more about asynchronous programming in JavaScript.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create Dynamic API Routes in Next.js ]]>
                </title>
                <description>
                    <![CDATA[ Next.js is a React-based framework that enables developers to create full-stack web applications by extending the latest React features. Next helps you add additional features and optimizations to your React apps like static site generation (SSG), se... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/next-js-dynamic-api-routes/</link>
                <guid isPermaLink="false">66d46048264384a65d5a95aa</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Musab Habeeb ]]>
                </dc:creator>
                <pubDate>Tue, 14 Nov 2023 18:30:04 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/11/Next.js-Dynamic-API-Routes.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Next.js is a React-based framework that enables developers to create full-stack web applications by extending the latest React features.</p>
<p>Next helps you add additional features and optimizations to your React apps like static site generation (SSG), server-side rendering (SSR), automatic code splitting and bundling, and dynamic API routes.</p>
<p>In this article, you will learn about dynamic API routes in Next.js: what they are, how to create them, and how to extend their functionalities.</p>
<h2 id="heading-what-are-api-routes">What are API routes?</h2>
<p>Before you know what an API route is, you should know what a route is and what an API is.</p>
<p>A route is a single path of nested folders. Next.js uses a page router to navigate to the various pages in a web application. Each file in the pages directory of a Next.js application's code represents a page on the web application.</p>
<p>For example, if you create a checkout.js file in your pages folder and you visit the URL: "your-app's-domain-name/checkout" on your browser, you will see the content of the checkout.js file rendered.</p>
<p>An API (short for application programming interface) serves as a means of communication between two computers or pieces of software. In a web application, an API facilitates communication between the client and the server.</p>
<p>An API route is a URL that directs incoming requests from the client to the appropriate server resource that will handle the requests.</p>
<p>API routes in Next.js enable you to create API endpoints as Node.js serverless functions. These endpoints allow you to make HTTPS requests and also communicate with a database.</p>
<h2 id="heading-how-to-create-an-api-route">How to Create an API Route</h2>
<p>To create an API route you will create a folder named API in your pages folder. Any file inside the /pages/api directory will be treated as an API route instead of a page.</p>
<p>For instance, you can create a folder named API in your pages folder and then create a file named start.js inside it with the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// pages/api/start.js</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">handler</span>(<span class="hljs-params">req, res</span>) </span>{
  res.status(<span class="hljs-number">200</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Request successful'</span> });
}
</code></pre>
<p>You have now created an API route. You can access this API route through this URL: /api/start. You can use it to handle an HTTP request and send back the response to the client.</p>
<p>The request argument is an instance of an HTTP incoming message plus some prebuilt middlewares. The response argument is an instance of an HTTP server response plus some helper functions.</p>
<p>You can create an API route to handle just one HTTP method. To do so you will need to create a new file named get.js. Then you can add this code to the file:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// pages/api/get.js</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">handler</span>(<span class="hljs-params">req, res</span>) </span>{
  <span class="hljs-keyword">if</span> (req.method === <span class="hljs-string">'GET'</span>) {
      res.status(<span class="hljs-number">200</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'This is a GET request'</span> });
  } <span class="hljs-keyword">else</span> {
      res.status(<span class="hljs-number">405</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Method Not Allowed'</span> });
  }
}
</code></pre>
<p>This API route can be accessed through this URL: /api/get and it will only handle HTTP get requests.</p>
<p>You can also create an API route to handle more than one HTTP method. To do so, create a new file named all.js and put this code in it:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// pages/api/all.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handler</span>(<span class="hljs-params">req, res</span>) </span>{
  <span class="hljs-keyword">if</span> (req.method === <span class="hljs-string">'GET'</span>) {
      <span class="hljs-comment">// Handle GET request</span>
      res.status(<span class="hljs-number">200</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'This is a GET request'</span> });
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (req.method === <span class="hljs-string">'POST'</span>) {
      <span class="hljs-comment">// Handle POST request</span>
      res.status(<span class="hljs-number">200</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'This is a POST request'</span> });
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (req.method === <span class="hljs-string">'PUT'</span>) {
      <span class="hljs-comment">// Handle PUT request</span>
      res.status(<span class="hljs-number">200</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'This is a PUT request'</span> });
  } <span class="hljs-keyword">else</span> (req.method === <span class="hljs-string">'DELETE'</span>) {
      <span class="hljs-comment">// Handle DELETE request</span>
      res.status(<span class="hljs-number">200</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">'This is a DELETE request'</span> });
  }
}
</code></pre>
<p>This API route can be accessed through this URL: /api/all and can handle four HTTP methods (GET, POST, PUT, and DELETE).</p>
<h2 id="heading-how-to-create-dynamic-api-routes">How to Create Dynamic API Routes</h2>
<p>Next.js allows developers to create dynamic routes. Dynamic routes are routes whose segment names are not known ahead of time. They are created from dynamic data.</p>
<p>A dynamic API route is a form of dynamic route that allows you to create API endpoints with dynamic segments in the route path.</p>
<p>These segments are filled in at request time or pre-rendered at build time. They can also be cached by the browser, which can improve performance for frequently accessed pages. This makes them a good choice for applications that expect a lot of traffic.</p>
<h3 id="heading-dynamic-route-syntax">Dynamic route syntax</h3>
<p>There is a particular syntax for creating dynamic API routes in Next.js. Next.js allows you to create dynamic API routes by wrapping the file name in square brackets.</p>
<p>To create a dynamic API route for a library API that fetches author data with dynamic IDs, you can start by creating a new folder named <code>authors</code> and then create a file named <code>[id].js</code> and add the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// api/authors/[id].js</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">handler</span>(<span class="hljs-params">req, res</span>) </span>{
  <span class="hljs-keyword">const</span> { id } = req.query;

  <span class="hljs-keyword">if</span> (req.method === <span class="hljs-string">'GET'</span>) {
      res.status(<span class="hljs-number">200</span>).json({ id, <span class="hljs-attr">message</span>: <span class="hljs-string">'Author data fetched successfully'</span> });
  }
}
</code></pre>
<p>The API route for the code above will be <code>/author/[id]</code>, and if it is passed this parameter <code>{ id: '234' }</code>, it will match the URL: <code>/author/234</code>.</p>
<p>You can make your dynamic API route handle different HTTP methods. To do so, delete the code in your <code>[id].js</code> folder and put in this code instead:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// api/authors/[id].js</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">handler</span>(<span class="hljs-params">req, res</span>) </span>{
  <span class="hljs-keyword">const</span> { id } = req.query;

  <span class="hljs-keyword">if</span> (req.method === <span class="hljs-string">'GET'</span>) {
      res.status(<span class="hljs-number">200</span>).json({ id, <span class="hljs-attr">message</span>: <span class="hljs-string">'Author data fetched successfully'</span> });
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (req.method === <span class="hljs-string">'POST'</span>) {
      res.status(<span class="hljs-number">200</span>).json({ id, <span class="hljs-attr">message</span>: <span class="hljs-string">'Author data sent successfully'</span> });
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (req.method === <span class="hljs-string">'PUT'</span>) {
      res.status(<span class="hljs-number">200</span>).json({ id, <span class="hljs-attr">message</span>: <span class="hljs-string">'Author data updated successfully'</span> });
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (req.method === <span class="hljs-string">'DELETE'</span>) {
      res.status(<span class="hljs-number">200</span>).json({ id, <span class="hljs-attr">message</span>: <span class="hljs-string">'Author data deleted successfully'</span> });
  }
}
</code></pre>
<h3 id="heading-catch-all-segments">Catch-all segments</h3>
<p>You can also pass sub-parameters to your dynamic API routes. To do this you will extend your dynamic API route to be able to catch all subsequent segments passed to it by adding an ellipsis before the file name in the square brackets. This ensures that the API routes can be passed more than one sub-parameter.</p>
<p>To create a dynamic API route that catches all segments, create a folder named store and create a file in you store folder named <code>[...gadgets].js</code>. Then add the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// api/store/[...gadgets].js</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">handler</span>(<span class="hljs-params">req, res</span>) </span>{
  <span class="hljs-keyword">const</span> { gadget } = req.query;

  <span class="hljs-keyword">if</span> (req.method === <span class="hljs-string">'GET'</span>) {
      res.status(<span class="hljs-number">200</span>).json({ id, <span class="hljs-attr">message</span>: <span class="hljs-string">'Data fetched successfully'</span> });
  }
}
</code></pre>
<p>The API route for the code above will be <code>pages/api/store/[...gadgets].js</code>. If it is passed this parameter <code>{ gadget: ['phones', 'iphones', 'iphone15'] }</code>, it will match the URLs: <code>/store/phones or /store/phones/iphones or /store/phones/iphones/iphone15</code>.</p>
<h3 id="heading-optional-catch-all-segments">Optional catch-all segments</h3>
<p>You can make the catch-all segments dynamic API route optional. When you make it optional it will not only be able to match all subsequent segments of the URL path, but also the main URL path.</p>
<p>To make the catch-all subsequent segments dynamic API route that we saw in the previous section optional, add a square bracket to the file name like this: <code>[[...store]].js]</code>. The optional catch-all segments will not only be able to match the URLs: <code>/store/phones or /store/phones/iphones or /store/phones/iphones/iphone15</code> alone – it will also be able to match <code>/store</code> URLs.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This article has helped you understand dynamic API routes in Next.js, including what they are, their uses, and how to create them.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Concepts to Know Before Learning Node.js ]]>
                </title>
                <description>
                    <![CDATA[ Before Node.js came into existence, JavaScript could only be run on the browser. It could only be used as a scripting language for frontend web development. Then, Node.js came to free JavaScript from this confinement. It made JavaScript ubiquitous (m... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-concepts-to-know-before-learning-node-js/</link>
                <guid isPermaLink="false">66d460443bc3ab877dae2224</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Musab Habeeb ]]>
                </dc:creator>
                <pubDate>Tue, 19 Sep 2023 15:12:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/09/JavaScript-Concepts-to-master-before-Node.js.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Before Node.js came into existence, JavaScript could only be run on the browser. It could only be used as a scripting language for frontend web development.</p>
<p>Then, Node.js came to free JavaScript from this confinement. It made JavaScript ubiquitous (meaning it could now be run everywhere).</p>
<p>Node.js is a JavaScript runtime environment that allows JavaScript developers to write command line tools and server side scripts outside of a browser.</p>
<p>Learning Node.js enables JavaScript developers to write server side code and code for embedded systems. This opens up opportunities in backend development and hardware programming.</p>
<p>But, before diving into Node.js, a JavaScript developer has to learn and understand some JavaScript concepts.</p>
<p>In this article, you are going to learn the JavaScript concepts you need to understand before learning Node.js.</p>
<p>Before you continue with the article, check the prerequisites.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with this article, you should have some basic knowledge of:</p>
<ul>
<li><p>JavaScript</p>
</li>
<li><p>The browser console (this is where you will run your code).</p>
</li>
</ul>
<p>Now that we have those out of our way, let's dive into the article, starting with expressions.</p>
<h2 id="heading-expressions">Expressions</h2>
<p>An expression is a unit or block of code that evaluates to a value.</p>
<p>There are five basic categories of expressions in JavaScript: primary expressions, arithmetic expressions, string expressions, logical expressions, and left-hand side expressions.</p>
<h3 id="heading-primary-expressions">Primary expressions</h3>
<p>Primary expressions consist of basic keywords in JavaScript. A common example is the <code>this</code> keyword:</p>
<pre><code class="lang-js"><span class="hljs-built_in">this</span>[<span class="hljs-string">'item'</span>];

<span class="hljs-built_in">this</span>.item;
</code></pre>
<p>Later on in this article you will learn more about the <code>this</code> keyword.</p>
<h3 id="heading-arithmetic-expressions">Arithmetic expressions</h3>
<p>An arithmetic operator takes numerical values as its operands and returns a numerical value. The operands and the operator make up the arithmetic expression:</p>
<pre><code class="lang-js"><span class="hljs-number">2</span> + <span class="hljs-number">3</span>;

<span class="hljs-number">2</span> * <span class="hljs-number">3</span>;

<span class="hljs-number">2</span> ** <span class="hljs-number">3</span>;
</code></pre>
<h3 id="heading-string-expressions">String expressions</h3>
<p>When strings are concatenated they form string expressions:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'My name is'</span> + <span class="hljs-string">'Peter'</span>);
</code></pre>
<h3 id="heading-logical-expressions">Logical expressions</h3>
<p>Logical expressions are expressions in which various values are compared:</p>
<pre><code class="lang-js"><span class="hljs-number">10</span> &gt; <span class="hljs-number">2</span>;
<span class="hljs-number">2</span> &lt; <span class="hljs-number">10</span>;
c === <span class="hljs-number">2</span> || d === <span class="hljs-number">10</span>;
</code></pre>
<h3 id="heading-left-hand-side-expressions">Left-hand side expressions</h3>
<p>Left-hand side expressions are expressions where values are assigned to a variable:</p>
<pre><code class="lang-js"><span class="hljs-comment">// variables</span>
a = <span class="hljs-number">2</span>;

<span class="hljs-comment">// object properties</span>
obj = {};
obj.name = <span class="hljs-string">'Paul'</span>;
</code></pre>
<h2 id="heading-data-types">Data Types</h2>
<p>There are 8 data types in JavaScript: String, Number, Boolean, Object, Null, Undefined, Symbol, and BigInt.</p>
<h3 id="heading-string">String</h3>
<p>The string type represents textual data. A string is surrounded by a single quote or a double quote.</p>
<p>Each element in a string occupies a certain position in the string. The first element is at index 0, and the second and third are at index 1 and 2 respectively.</p>
<p>Here is an example of a string:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> name = <span class="hljs-string">'Yusuf'</span>;
<span class="hljs-keyword">let</span> newName = <span class="hljs-string">"Joseph"</span>;
</code></pre>
<h3 id="heading-number">Number</h3>
<p>The number types are stored in 64-bit format, also known as double-precision floating point numbers.</p>
<p>They consist of numbers that are within the range of -(2<sup>53</sup> - 1) and (2<sup>53</sup> – 1), with both of these numbers inclusive. These two numbers are known as the <code>MIN_SAFE_INTEGER</code> and the <code>MAX_SAFE_INTEGER</code> respectively.</p>
<p>Numbers that exceed this range, belong to another data type called BigInt.</p>
<p>Here is an example of a positive integer, a float and a negative integer:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> number = <span class="hljs-number">15</span>;
<span class="hljs-keyword">let</span> anotherNumber = <span class="hljs-number">1.5</span>;
<span class="hljs-keyword">let</span> lastNumber = <span class="hljs-number">-3</span>;
</code></pre>
<h3 id="heading-boolean">Boolean</h3>
<p>The boolean type is logical, and it has only two values: true or false. It is commonly used in loops and conditional statements.</p>
<p>In the example below, I declared variables and assigned them a value of true and false respectively.</p>
<p>Then, I created a conditional statement that returns 1 if the <code>bool</code> variable is true or -1 if it is false. It returns zero if it is neither true nor false.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> positive = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">let</span> negative = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">let</span> bool = <span class="hljs-literal">false</span>;

<span class="hljs-comment">// conditional statement</span>
<span class="hljs-keyword">if</span> (bool) {
    <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (bool) {
    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;
} <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<h3 id="heading-object">Object</h3>
<p>An object type allows you to store collections of data. The data are stored in a pair of curly braces and a key-value pair format. Object keys must be textual (for example a string).</p>
<p>An object can store any of the other data types, like string, number, arrays, booleans, and so on.</p>
<p>In the example below I created an object named <code>myObject</code>, and gave it three keys with their corresponding values:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myObject = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Gabriel"</span>,
    <span class="hljs-attr">number</span>: <span class="hljs-number">15</span>,
    <span class="hljs-attr">developer</span>: [<span class="hljs-literal">true</span>, <span class="hljs-string">"Daniel"</span>, <span class="hljs-number">1</span>]
}
</code></pre>
<h3 id="heading-null">Null</h3>
<p>Null data types are special data types. They have the value null which means that the value is unknown or empty:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> unknown = <span class="hljs-literal">null</span>;
</code></pre>
<h3 id="heading-undefined">Undefined</h3>
<p>Unlike null, undefined means that a variable is declared and not assigned a value. A variable can also be assigned undefined specifically:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> name = <span class="hljs-literal">undefined</span>;

<span class="hljs-keyword">let</span> newName;
<span class="hljs-built_in">console</span>.log(newName);
</code></pre>
<h3 id="heading-symbol">Symbol</h3>
<p>Symbols are used to create unique values. They are created by calling the <code>Symbol()</code> function. Every time the <code>Symbol()</code> function is invoked it creates a new unique value.</p>
<p>Symbols are kept hidden or private and they can only be used internally. For instance, they can be used as keys in an object. When you try to get the list of keys in an object where a symbol is part of its keys the symbol key will not be displayed.</p>
<p>You can pass a parameter to the symbol function to serve as a description for the symbol when debugging it in the console:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> firstSymbol = <span class="hljs-built_in">Symbol</span>();

<span class="hljs-keyword">let</span> anotherSymbol = <span class="hljs-built_in">Symbol</span>(anotherSymbol);
</code></pre>
<h3 id="heading-bigint">BigInt</h3>
<p>BigInt is a special type of number that provides support for numbers with a length that a normal number type can not hold (such as numbers that exceed the safe integer limit).</p>
<p>It can be created by appending n to the end of an integer or passing a number into the <code>BigInt</code> function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> bigNumber = <span class="hljs-number">175337823472347884278247898427427427642n</span>;
<span class="hljs-keyword">let</span> newBigNumber = BigInt(<span class="hljs-number">1624743724724724898718247248744774227422n</span>);

<span class="hljs-keyword">let</span> anotherBigNumber = BigInt(<span class="hljs-number">14</span>);
</code></pre>
<h2 id="heading-classes">Classes</h2>
<p>A JavaScript class is a template for creating objects. It contains data and functions that manipulate data.</p>
<p>Classes were introduced to JavaScript in the ECMAScript 2015 (ES6) version of JavaScript.</p>
<p>The functions used in classes are called methods.</p>
<p>There is a basic syntax for declaring classes looks something similar to the following:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TemplateClass</span> </span>{
    <span class="hljs-keyword">constructor</span>() {...};
    method() {...};
    method() {...};
}
</code></pre>
<p>From the syntax you can create a class named <code>Visitor</code>:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Visitor</span> </span>{
    <span class="hljs-keyword">constructor</span>(name) {
        <span class="hljs-built_in">this</span>.name = name;
    }
    introduce() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> and I am a visitor`</span>)
    }
}
</code></pre>
<p>You can create a new class from this class by using the new class syntax. The newly created class can access any method from its parent class:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> visitor = <span class="hljs-keyword">new</span> Visitor(<span class="hljs-string">"Jeff"</span>);

<span class="hljs-comment">// visitor can call the introduce method in its parent class.</span>
visitor.introduce();
</code></pre>
<h2 id="heading-variables">Variables</h2>
<p>A variable is a named storage for JavaScript data. JavaScript variables can be declared in three ways:</p>
<ul>
<li><p>Using the <code>var</code> keyword</p>
</li>
<li><p>Using the <code>let</code> keyword</p>
</li>
<li><p>Using the <code>const</code> keyword</p>
</li>
</ul>
<h3 id="heading-how-to-declare-variables-using-the-var-keyword">How to declare variables using the <code>var</code> keyword</h3>
<p>Variables declared with the <code>var</code> keyword are function scoped and they can be redeclared:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> num = <span class="hljs-number">1</span>;

<span class="hljs-comment">// num can be redeclared</span>
<span class="hljs-keyword">var</span> num = <span class="hljs-number">2</span>;
</code></pre>
<h3 id="heading-how-to-declare-variables-using-the-let-keyword">How to declare variables using the <code>let</code> keyword</h3>
<p>Variables declared with the <code>let</code> keyword are block scoped and they cannot be redeclared – they can only be reassigned:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> fruit = <span class="hljs-string">"banana"</span>;

<span class="hljs-comment">// fruit can only be reassigned</span>
fruit = <span class="hljs-string">"orange"</span>;
</code></pre>
<h3 id="heading-how-to-declare-variables-using-the-const-keyword">How to declare variables using the <code>const</code> keyword</h3>
<p>Variables declared with the const keyword are block scoped and they cannot not be redeclared or reassigned (meaning they are constant):</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> bestStudent = <span class="hljs-string">"Daniel"</span>;
</code></pre>
<h2 id="heading-functions">Functions</h2>
<p>A function is a block of code that performs a specific task. It can be declared using the <code>function</code> keyword:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomething</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Does Something"</span>;
}
</code></pre>
<p>A function takes inputs called arguments and outputs results.</p>
<p>To execute a function you will invoke the function by calling the function name with enclosed brackets:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">return</span> a + b;
}

addNumbers();
</code></pre>
<p>You can assign a function to a variable and call the variable when you want to invoke the function:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span>(<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-keyword">let</span> numberAddition = addNumbers(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
numberAddition();
</code></pre>
<h2 id="heading-arrow-functions">Arrow Functions</h2>
<p>Arrow functions are a concise and compact way to write a function. They have some deliberate limitations in their usage:</p>
<ul>
<li><p>They cannot be used as a method.</p>
</li>
<li><p>They cannot be used as a constructor.</p>
</li>
<li><p>Arrow functions cannot use yield within their own bodies.</p>
</li>
</ul>
<p>Below is the syntax for an arrow function:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> doSomething = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Do something"</span>;
}
</code></pre>
<p>An arrow function can also take an argument.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> multiplyNumbers = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> a * b;
}
</code></pre>
<h2 id="heading-this-keyword"><code>this</code> keyword</h2>
<p>The <code>this</code> keyword in JavaScript refers to an object that is executing a function or a code.</p>
<p>The <code>this</code> keyword can be used in different contexts – the context in which the <code>this</code> keyword is used determines what it refers to.</p>
<p>The <code>this</code> keyword can be used:</p>
<ul>
<li><p>In an object method.</p>
</li>
<li><p>Alone.</p>
</li>
<li><p>In object method bindings.</p>
</li>
</ul>
<h3 id="heading-how-to-use-the-this-keyword-in-an-object-method">How to use the <code>this</code> keyword in an object method</h3>
<p>The <code>this</code> keyword refers to the object whenever it is used as an object method:</p>
<pre><code class="lang-js">intro : <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">"My name is"</span> + <span class="hljs-built_in">this</span>.name <span class="hljs-string">"and, I am a"</span> + <span class="hljs-built_in">this</span>.occupation;
}
</code></pre>
<h3 id="heading-how-to-use-the-this-keyword-alone">How to use the <code>this</code> keyword alone</h3>
<p>When <code>this</code> is used alone it refers to the global object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> wes = <span class="hljs-built_in">this</span>;
</code></pre>
<h3 id="heading-how-to-use-the-this-keyword-in-object-method-bindings">How to use the <code>this</code> keyword in object method bindings</h3>
<p>When <code>this</code> is used in an object method, it refers to the object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> student = {
  <span class="hljs-attr">firstName</span>  : <span class="hljs-string">"Juliana"</span>,
  <span class="hljs-attr">lastName</span>   : <span class="hljs-string">"Carpe"</span>,
  <span class="hljs-attr">myFunction</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-built_in">this</span>;
  }
};
</code></pre>
<h2 id="heading-loops">Loops</h2>
<p>Loops are useful for executing a block of code for a specified number of times based on some specified conditions. There are different types of loops in JavaScript:</p>
<ul>
<li><p><code>for</code> loops</p>
</li>
<li><p><code>for ... in</code> loops</p>
</li>
<li><p><code>for ... of</code> loops</p>
</li>
<li><p><code>while</code> loops</p>
</li>
<li><p><code>do ... while</code> loops</p>
</li>
</ul>
<h3 id="heading-how-to-use-for-loops">How to use <code>for</code> loops</h3>
<p><code>for</code> loops are used to execute a block of code a number of times:</p>
<pre><code class="lang-js"><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">5</span>; i++) {
    <span class="hljs-keyword">return</span> i;
}
</code></pre>
<h3 id="heading-how-to-use-for-in-loops">How to use <code>for ... in</code> loops</h3>
<p><code>for ... in</code> loops are used to loop through the properties of an object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> prop <span class="hljs-keyword">in</span> obj) {
    <span class="hljs-keyword">return</span> obj.prop;
}
</code></pre>
<h3 id="heading-how-to-use-for-of-loops">How to use <code>for ... of</code> loops</h3>
<p><code>for ... of</code> loops are used to loop through the values of iterable objects like arrays, strings, maps, and so on:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> numArr = [<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>]
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> val <span class="hljs-keyword">of</span> numArr) {
    <span class="hljs-keyword">return</span> val ** <span class="hljs-number">2</span>
}
</code></pre>
<h3 id="heading-how-to-use-while-loops">How to use <code>while</code> loops</h3>
<p><code>while</code> loops are used to execute a block of code while a certain condition still holds true:</p>
<pre><code class="lang-js"><span class="hljs-keyword">while</span> (i &lt; <span class="hljs-number">20</span>) {
    <span class="hljs-keyword">return</span> i;
    i++;
}
</code></pre>
<h3 id="heading-how-to-use-do-while-loops">How to use <code>do ... while</code> loops</h3>
<p><code>do ... while</code> loops execute a block of code first without any conditions. For as long as a certain condition still holds true it continues to execute the block of code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> i = <span class="hljs-number">3</span>;
<span class="hljs-keyword">do</span> {
    <span class="hljs-keyword">return</span> i;
    i++;
} 
<span class="hljs-keyword">while</span> (i &lt; <span class="hljs-number">4</span>)
</code></pre>
<h2 id="heading-scopes">Scopes</h2>
<p>The scope is the current context of execution. It is where variables and expressions can be accessed.</p>
<p>There is an hierarchical arrangement of scope in JavaScript. This makes it possible for lower scopes to access higher scopes.</p>
<p>The scopes in JavaScript are:</p>
<ul>
<li><p>Global scope</p>
</li>
<li><p>Module scope</p>
</li>
<li><p>Function scope</p>
</li>
<li><p>Block scope</p>
</li>
</ul>
<p>The global scope is the default scope for all codes running in script mode while the module scope is the default scope for all codes running in module mode.</p>
<p>The function scope is created by functions while the block scope is created by variables.</p>
<p>Here is an example of function and block scope:</p>
<pre><code class="lang-js"><span class="hljs-comment">// function scope</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">introduce</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-keyword">let</span> age = <span class="hljs-number">12</span>;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`My name is <span class="hljs-subst">${name}</span>`</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I am <span class="hljs-subst">${age}</span> years old`</span>);
}

<span class="hljs-keyword">let</span> firstAge = <span class="hljs-number">13</span>

<span class="hljs-comment">// block scope</span>
<span class="hljs-keyword">if</span> (firstAge === <span class="hljs-number">13</span>) {
    <span class="hljs-keyword">let</span> secondAge = <span class="hljs-number">20</span>;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I am <span class="hljs-subst">${secondAge}</span> years old`</span>);
}
</code></pre>
<h2 id="heading-arrays">Arrays</h2>
<p>An array is a special type of an object that stores data in an ordered form.</p>
<p>Arrays can be declared in two ways:</p>
<ul>
<li><p>Using square brackets.</p>
</li>
<li><p>Using the the <code>Array()</code> constructor.</p>
</li>
</ul>
<h3 id="heading-how-to-declare-arrays-using-square-brackets">How to declare arrays using square brackets</h3>
<p>This is the common way of creating an array. It is done by wrapping the array's items in a pair of square brackets:</p>
<pre><code class="lang-js">  <span class="hljs-keyword">let</span> array = [<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-string">"a"</span>, <span class="hljs-string">"c"</span>];
</code></pre>
<h3 id="heading-how-to-declare-arrays-using-the-the-array-constructor">How to declare arrays using the the <code>Array()</code> constructor</h3>
<p>The <code>Array()</code> constructor does the same thing as the bracket notation. It can be called with or without the <code>new</code> keyword:</p>
<pre><code class="lang-js">  <span class="hljs-keyword">let</span> anotherArray = <span class="hljs-built_in">Array</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-string">"go"</span>);
</code></pre>
<h3 id="heading-how-to-access-array-elements">How to access array elements</h3>
<p>Array elements can be accessed in three ways:</p>
<ul>
<li><p>using their index.</p>
</li>
<li><p>using the array's <code>length</code> property.</p>
</li>
<li><p>using a loop</p>
</li>
</ul>
<h4 id="heading-how-to-access-an-array-element-using-its-index">How to access an array element using its index</h4>
<p>You call the name of the array with a square bracket containing the index you want to access:</p>
<pre><code class="lang-js"> <span class="hljs-keyword">let</span> newArray = [<span class="hljs-string">"Idris"</span>, <span class="hljs-string">"Daniel"</span>, <span class="hljs-string">"Joseph"</span>];

  <span class="hljs-comment">// To access first element</span>
  <span class="hljs-keyword">let</span> firstElement = newArray[<span class="hljs-number">0</span>]; 
  <span class="hljs-built_in">console</span>.log(firstElement);  <span class="hljs-comment">// Idris</span>

  <span class="hljs-comment">// To access second element </span>
  <span class="hljs-keyword">let</span> secondElement = newArray[<span class="hljs-number">1</span>];  
  <span class="hljs-built_in">console</span>.log(secondElement);  <span class="hljs-comment">// Joseph</span>
</code></pre>
<h3 id="heading-how-to-access-an-array-element-using-the-arrays-length-property">How to access an array element using the array's <code>length</code> property</h3>
<p>You can get the length of the array using the <code>length</code> property. Then, you will subtract any number from it to get the index of the element you want to access:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> newArray = [<span class="hljs-string">"Idris"</span>, <span class="hljs-string">"Daniel"</span>, <span class="hljs-string">"Joseph"</span>];

  <span class="hljs-keyword">let</span> length = newArray.length;

  <span class="hljs-keyword">let</span> firstElement = newArray[length - <span class="hljs-number">3</span>]; 
  <span class="hljs-built_in">console</span>.log(firstElement);  <span class="hljs-comment">// Idris</span>

  <span class="hljs-keyword">let</span> secondElement = newArray[length - <span class="hljs-number">2</span>];
  <span class="hljs-built_in">console</span>.log(secondElement);  <span class="hljs-comment">// Joseph</span>
</code></pre>
<h4 id="heading-how-to-access-an-array-element-using-a-loop">How to access an array element using a loop</h4>
<p>Array elements can be accessed using loops. You can make use of a <code>for</code> loop, <code>while</code> loop, or a <code>for ... of</code> loop:</p>
<pre><code class="lang-js">  <span class="hljs-keyword">let</span> newArray = [<span class="hljs-string">"Idris"</span>, <span class="hljs-string">"Daniel"</span>, <span class="hljs-string">"Joseph"</span>];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; newArray.length; i++) {
      <span class="hljs-keyword">return</span> newArray[i]
  }
</code></pre>
<h3 id="heading-important-array-methods">Important Array methods</h3>
<p>There are over fifteen array methods in JavaScript. In this article, you will learn the ones that are most useful in Node.js:</p>
<ul>
<li><p><code>push()</code> and <code>pop()</code></p>
</li>
<li><p><code>shift()</code> and <code>unshift()</code></p>
</li>
<li><p><code>map()</code></p>
</li>
<li><p><code>sort()</code></p>
</li>
<li><p><code>forEach()</code></p>
</li>
</ul>
<h4 id="heading-how-to-use-the-push-and-pop-methods">How to use the <code>push()</code> and <code>pop()</code> methods</h4>
<p>The <code>push()</code> method is used to add an item to the end of an array, while the <code>pop()</code> method is used to remove an item from the end of an array:</p>
<pre><code class="lang-js"><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">9</span>]

arr.push(<span class="hljs-number">21</span>);

<span class="hljs-built_in">console</span>.log(arr)    <span class="hljs-comment">// [1, 2, 3, 9, 21]</span>

arr.pop()

<span class="hljs-built_in">console</span>.log(arr)    <span class="hljs-comment">// [1, 2, 3, 9]</span>
</code></pre>
<h4 id="heading-how-to-use-the-unshift-and-shift-methods">How to use the <code>unshift()</code> and <code>shift()</code> methods</h4>
<p>The <code>unshift()</code> method is used to add an item to the beginning of an array, while the <code>shift()</code> method is used to remove an item from the beginning of an array:</p>
<pre><code class="lang-js"><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>];

arr.unshift(<span class="hljs-number">0</span>);

<span class="hljs-built_in">console</span>.log(arr);    <span class="hljs-comment">// [0, 1, 2, 3]</span>

arr.shift();

connsole.log(arr);    <span class="hljs-comment">// [1, 2, 3]</span>
</code></pre>
<h4 id="heading-how-to-use-the-map-method">How to use the <code>map()</code> method</h4>
<p>The <code>map()</code> method iterates through the elements of an array and calls a function on each element of the array. It returns a new array that contains the result of each function call:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> fruits = [<span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Grape"</span>, <span class="hljs-string">"Cashew"</span>];

<span class="hljs-keyword">let</span> mappedFruits = fruits.map(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> item + <span class="hljs-string">"s"</span>);
<span class="hljs-built_in">console</span>.log(mappedFruits); <span class="hljs-comment">// ["Apples", "Grapes", "Cashews"]</span>
</code></pre>
<h4 id="heading-how-to-use-the-sort-method">How to use the <code>sort()</code> method</h4>
<p>The <code>sort()</code> method sorts an array in place and returns the same array in a sorted form.</p>
<p>The default order of the <code>sort()</code> method is ascending order. Strings are sorted in alphabetical order:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> numbers = [<span class="hljs-number">8</span>, <span class="hljs-number">7</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">let</span> fruits = [<span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Grape"</span>, <span class="hljs-string">"Cashew"</span>];

<span class="hljs-keyword">let</span> sortedNumbers = numbers.sort();
<span class="hljs-keyword">let</span> sortedFruits = fruits.sort()

<span class="hljs-built_in">console</span>.log(sortedNumbers);  <span class="hljs-comment">// [5, 7, 8]</span>
<span class="hljs-built_in">console</span>.log(sortedFruits);  <span class="hljs-comment">// ["Apple", "Cashew", "Grape"]</span>
</code></pre>
<h4 id="heading-how-to-use-the-foreach-method">How to use the forEach() method</h4>
<p>The <code>forEach()</code> method loops through the array and calls a function for every element of the array:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> fruits = [<span class="hljs-string">"Apple"</span>, <span class="hljs-string">"Grape"</span>, <span class="hljs-string">"Cashew"</span>];

fruits.forEach(<span class="hljs-function"><span class="hljs-params">fruit</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(fruit));
<span class="hljs-comment">//  "Apple"</span>
<span class="hljs-comment">//  "Grape"</span>
<span class="hljs-comment">//  "Cashew"</span>
</code></pre>
<h2 id="heading-template-literals">Template Literals</h2>
<p>Template literals are enclosed in backticks, just like strings are enclosed in quotes. They allow you to store multiline strings and also interpolate strings with embedded expressions.</p>
<p>The example below shows a basic template literal:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> basic = <span class="hljs-string">`I write codes`</span>
</code></pre>
<p>You can write a template literal that stores multiline strings like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> multiLine = <span class="hljs-string">`I write codes                     
        I debug codes`</span>;
</code></pre>
<p>You can use the dollar sign and curly braces to embed expressions in template literals.</p>
<p>In the example below, the function <code>myName</code> is embedded in the display variable with a template literal:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myName</span>(<span class="hljs-params">Musab, Habeeb</span>) </span>{        
    alert(<span class="hljs-string">"Musab Habeeb"</span>);    
}    

<span class="hljs-keyword">let</span> display = <span class="hljs-string">`This displays my name <span class="hljs-subst">${myName()}</span>`</span>
</code></pre>
<h2 id="heading-strict-mode">Strict mode</h2>
<p>JavaScript is a sloppy language in the sense that it allows you to write code that is not allowed in other languages. Some of the code you write in JavaScript has errors but, JavaScript does not throw an error.</p>
<p>Strict mode does the following:</p>
<ul>
<li><p>It throws errors for JavaScript silent errors.</p>
</li>
<li><p>It fixes mistakes that makes it difficult for JavaScript engines to perform optimizations.</p>
</li>
<li><p>It prohibits some syntax likely to be defined in future versions of the ECMAScript.</p>
</li>
</ul>
<p>Strict mode works in an entire script file and functions, but it does not work in block scopes.</p>
<p>To invoke script mode you will add the <code>"use strict";</code> syntax to the top of the code you want to apply it to. You can apply strict mode to a script like this:</p>
<pre><code class="lang-js"><span class="hljs-meta">"use strict"</span>;

<span class="hljs-keyword">let</span> name = <span class="hljs-string">"Musab"</span>;

<span class="hljs-built_in">console</span>.log(name);
</code></pre>
<p>Also, you can apply strict mode to a function like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHi</span>(<span class="hljs-params">name</span>) </span>{
<span class="hljs-meta">    "use strict"</span>;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi <span class="hljs-subst">${name}</span>`</span>);
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Finally, you are done with learning the JavaScript concepts you need to understand before learning Node.js.</p>
<p>All these concepts are important concepts that a JavaScript Developer aspiring to learn Node.js should understand. Understanding these concepts will make learning Node.js easier.</p>
<p>But, to understand these concepts in depth, you can do more research on each of them and read other articles. Keep learning, keep building.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Concepts to Know Before Learning React ]]>
                </title>
                <description>
                    <![CDATA[ A lot of web developers use React as their go-to library for building UI components for their websites. React is one of the most popular frameworks for web development and it is written entirely in JavaScript. Since React was written in JavaScript, i... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-concepts-to-know-before-learning-react/</link>
                <guid isPermaLink="false">66d460463a8352b6c5a2aab0</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Musab Habeeb ]]>
                </dc:creator>
                <pubDate>Thu, 20 Apr 2023 00:30:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/Seven-JavaScript-Concepts-to-master-before-React--2-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A lot of web developers use React as their go-to library for building UI components for their websites. React is one of the most popular frameworks for web development and it is written entirely in JavaScript.</p>
<p>Since React was written in JavaScript, it uses a lot of the JavaScript concepts that were introduced before and in the ES6 version of JavaScript. It is important for anyone who wants to learn React to understand these concepts.</p>
<p>In this article, I will be explaining with detailed examples the seven most important JavaScript concepts that a developer must know before learning React.</p>
<p>Before you start reading this article, check the pre-requisites</p>
<h2 id="heading-pre-requisites">Pre-requisites</h2>
<p>To follow along with this article you should have some basic knowledge of:</p>
<ul>
<li><p>JavaScript, and</p>
</li>
<li><p>The browser console (because this is where you will run your code)</p>
</li>
</ul>
<h2 id="heading-how-to-use-if-statements-and-ternary-operators-in-javascript">How to Use If Statements and Ternary Operators in JavaScript</h2>
<p>In JavaScript, you use conditional statements to specify that a block of code should be executed if certain conditions are true.</p>
<p>Conditional statements are useful in the conditional rendering of UI components in React. They allow you to render your UI based on certain conditions.</p>
<h3 id="heading-if-else-statement">If ... Else Statement</h3>
<p>The first thing to know regarding conditional statements is how to use the if ... else statement.</p>
<p>You can write code that will add two numbers if the second one is greater than the first, and subtract them if that's not the case. Here's what that would look like using an if ... else statement:</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (a &lt; b) {            
    <span class="hljs-keyword">let</span> output = a + b;        
} <span class="hljs-keyword">else</span> {            
    <span class="hljs-keyword">let</span> output = a - b;        
}
</code></pre>
<p>In an if ... else statement, you can use an else ... if instead of writing multiple if's.</p>
<p>The else if makes it possible for you to write multiple conditions together. It specifies a new condition to test, if the first condition is false.</p>
<pre><code class="lang-js"><span class="hljs-keyword">if</span> (a &lt; b)  {        
    <span class="hljs-keyword">let</span> output = a + b;    
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (a &gt; b) {
    <span class="hljs-keyword">let</span> output = a - b;    
} <span class="hljs-keyword">else</span> {        
    <span class="hljs-keyword">let</span> output = a * b;    
}
</code></pre>
<p>The code above writes an else if statement to the previous example. The else if tests for the condition a is greater than b, if the previous condition is false.</p>
<h3 id="heading-ternary-operator">Ternary Operator</h3>
<p>A ternary operator is a more concise way of writing an if ... else statement.</p>
<p>It takes three operands: a condition followed by a question mark (<code>?</code>), then an expression to execute if the condition is truthy followed by a colon (<code>:</code>), and finally the expression to execute if the condition is falsy.</p>
<p>If you want to rewrite the above if ... else example using a ternary operator, it should look like this:</p>
<pre><code class="lang-js">(a &lt; b) ? a + b : a - b;
</code></pre>
<p>The (a &lt; b) is the condition, the ? evaluates the condition, and if it is true it returns a + b, while if it is false it returns a - b.</p>
<p>That's five lines of code from the previous example written in just one line. But, if you want to include else if in your ternary operator code, you would need to write this:</p>
<pre><code class="lang-js">(a &lt; b) ? a + b : (a &gt; b) ? a - b : a * b;
</code></pre>
<p>In the code above, the ? evaluates the condition (a &lt; b) and if it is true it returns a + b. But, if it is false it evaluates the second condition (a &gt; b) and if that is true it returns a - b else it returns a * b.</p>
<p>Just, one line too. But, to prevent it from becoming too cumbersome you can split it into multiple lines. This will make your code more readable.</p>
<p>In the example below, you'll see how you can split your code by making the condition and the return statement be on the same line.</p>
<pre><code class="lang-js">(a &lt; b) ? a + b         
: (a &gt; b) ? a - b         
: a * b;
</code></pre>
<h2 id="heading-how-destructuring-works-in-javascript">How Destructuring Works in JavaScript</h2>
<p>Destructuring in JavaScript is when we unpack values from arrays or properties from objects and assign them to a variable.</p>
<p>It makes it easy to extract data from arrays and objects, and it's applicable in React concepts like useState.</p>
<h3 id="heading-array-destructuring">Array Destructuring</h3>
<p>Array destructuring is used to extract data from an array.</p>
<p>In the example below, we destructure the <code>newArray</code> array in two ways. One way is to declare an array that contains the variables we want to assign to our array values and assign it to the newArray variable. The other way is to assign the array of variables to the array that contains the values we want to destructure.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> newArray = [<span class="hljs-string">"Musab"</span>, <span class="hljs-string">"I"</span>, <span class="hljs-string">"Handsome"</span>];    
<span class="hljs-keyword">let</span> [noun, pronoun, adjective] = newArray; 

<span class="hljs-comment">// The above can also be rewritten as this:  </span>

<span class="hljs-keyword">let</span> [noun, pronoun, adjective] = [<span class="hljs-string">"Musab"</span>, <span class="hljs-string">"I"</span>, <span class="hljs-string">"Handsome"</span>];    

<span class="hljs-built_in">console</span>.log(noun);    
<span class="hljs-built_in">console</span>.log(pronoun);
</code></pre>
<p>You can skip one or more values by putting commas in their place.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> newArray = [a, b, c, d, e];

<span class="hljs-keyword">let</span> [firstLetter, , , ,lastLetter] = [a, b, c, d, e];
</code></pre>
<h3 id="heading-object-destructuring">Object Destructuring</h3>
<p>Object destructuring is similar to array destructuring, but in objects we only destructure the keys/properties.</p>
<p>In the example below, the "personObject" was destructured by declaring an object containing the properties of the personObject and assigning it to the personObject.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> personObject = {        
    <span class="hljs-attr">name</span>: <span class="hljs-string">"David"</span>,        
    <span class="hljs-attr">age</span>: <span class="hljs-number">18</span>,        
    <span class="hljs-attr">height</span>: <span class="hljs-string">"6ft 5in"</span>,        
    <span class="hljs-attr">gender</span>: <span class="hljs-string">"male"</span>,    
}    

<span class="hljs-keyword">let</span> {name, age, height, gender} = personObject   
<span class="hljs-built_in">console</span>.log(name, age, height, gender);
</code></pre>
<p>Now, you can access the values of each of the keys without calling the object.</p>
<p>You can also assign each of the destructured keys to new variables.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> personObject = {        
    <span class="hljs-attr">name</span>: <span class="hljs-string">"David"</span>,        
    <span class="hljs-attr">age</span>: <span class="hljs-number">18</span>,        
    <span class="hljs-attr">height</span>: <span class="hljs-string">"6ft 5in"</span>,        
    <span class="hljs-attr">gender</span>: <span class="hljs-string">"male"</span>,    
}    

<span class="hljs-keyword">let</span> {<span class="hljs-attr">name</span>: personName, <span class="hljs-attr">age</span>: personAge, <span class="hljs-attr">height</span>: personHeight, <span class="hljs-attr">gender</span>: personGender} = personObject;

<span class="hljs-built_in">console</span>.log(personName, personAge, personHeight, personGender);
</code></pre>
<h2 id="heading-how-to-use-template-literals-in-javascript">How to Use Template Literals in JavaScript</h2>
<p>Template literals are enclosed in backticks just like strings are enclosed in quotes. They allow you to store multiline strings and also interpolate strings with embedded expressions.</p>
<p>The example below shows a basic template literal.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> basic = <span class="hljs-string">`I write codes`</span>
</code></pre>
<p>You can write a template literal that stores multiline strings like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> multiLine = <span class="hljs-string">`I write codes                     
        I debug codes`</span>;
</code></pre>
<p>You can use the dollar sign and curly braces to embed expressions in template literals. In the example below, the function myName is embedded in the display variable with a template literal.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myName</span>(<span class="hljs-params">Musab, Habeeb</span>) </span>{        
    alert(<span class="hljs-string">"Musab Habeeb"</span>);    
}    

<span class="hljs-keyword">let</span> display = <span class="hljs-string">`This displays my name <span class="hljs-subst">${myName()}</span>`</span>
</code></pre>
<h2 id="heading-how-to-use-objects-in-javascript">How to Use Objects in JavaScript</h2>
<p>An object allows you to store collections of data. The data are stored in a pair of curly braces in a key-value pair format.</p>
<p>In the example below, we create an object named "myObject" and we give it three keys with their corresponding values.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myObject = {        
    <span class="hljs-attr">name</span>: Musab,        
    <span class="hljs-attr">number</span>: <span class="hljs-number">12</span>,        
    <span class="hljs-attr">developer</span>: [<span class="hljs-literal">true</span>, <span class="hljs-string">"David"</span>, <span class="hljs-number">1</span>]    
}
</code></pre>
<p>You can access the values that belong to each key in an object in two ways:</p>
<ul>
<li><p>by using dot notation (this is the most commonly used) or</p>
</li>
<li><p>by using bracket notation</p>
</li>
</ul>
<p>In the example below we access the name property using bracket notation and the number property using dot notation.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myObject = {        
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Musab"</span>,        
    <span class="hljs-attr">number</span>: <span class="hljs-number">12</span>,        
    <span class="hljs-attr">developer</span>: [<span class="hljs-literal">true</span>, <span class="hljs-string">"David"</span>, <span class="hljs-number">1</span>]    
}

<span class="hljs-built_in">console</span>.log(myObject[<span class="hljs-string">"name"</span>]);
<span class="hljs-built_in">console</span>.log(myObject.number);
</code></pre>
<p>Object keys must be in string form. If they aren't, they will be inaccesible using dot notation.</p>
<p>In the example below, by accessing the property 3 you will get a syntax error.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> numbers = {
    <span class="hljs-attr">one</span>: David,
    <span class="hljs-attr">two</span>: George,
    <span class="hljs-number">3</span>: Peter
}

<span class="hljs-built_in">console</span>.log(numbers.two);
<span class="hljs-built_in">console</span>.log(numbers<span class="hljs-number">.3</span>);
</code></pre>
<p>You must always put a comma at the end of every value in an object except the last value in the object.</p>
<h2 id="heading-how-to-use-arrays-and-array-methods-in-javascript">How to Use Arrays and Array Methods in JavaScript</h2>
<p>Arrays are special types of objects that store data in an ordered form. Array methods are built-in functions that can be called on an array to do something on or with the array.</p>
<p>There are a lot of array methods, but the ones you will be using the most in React are the map, filter, and reduce methods.</p>
<h3 id="heading-map-method">Map method</h3>
<p>This method iterates through the elements of an array and calls a function on each element of the array. This returns a new array that contains the result of each function call.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> fruits = [<span class="hljs-string">"pawpaw"</span>, <span class="hljs-string">"orange"</span>, <span class="hljs-string">"banana"</span>];   

<span class="hljs-keyword">let</span> mappedFruits = fruits.map(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> item + <span class="hljs-string">"s"</span>);    

<span class="hljs-built_in">console</span>.log(mappedFruits); <span class="hljs-comment">// ["pawpaws", "oranges", "bananas"]</span>
</code></pre>
<h3 id="heading-filter-method">Filter method</h3>
<p>This method returns all items of an array that match a specific condition.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> fruits = [<span class="hljs-string">"pawpaw"</span>, <span class="hljs-string">"orange"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"grape"</span>];

<span class="hljs-keyword">let</span> filteredFruits = fruits.filter(<span class="hljs-function"><span class="hljs-params">fruit</span> =&gt;</span> fruit.length &gt; <span class="hljs-number">5</span>);

<span class="hljs-built_in">console</span>.log(filteredFruits);  <span class="hljs-comment">// ["pawpaw", "orange", "banana"]</span>
</code></pre>
<h3 id="heading-reduce-method">Reduce Method</h3>
<p>The reduce method iterates over all the elements of an array and takes an action on each iteration. The result of that action is carried on to the next iteration to be used in the next action until the final iteration. Then, the final result will be returned.</p>
<p>It takes two arguments, which are:</p>
<ul>
<li><p>a function and,</p>
</li>
<li><p>an optional argument that denotes the value the function will start from.</p>
</li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> evenNumbers = [<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>, <span class="hljs-number">10</span>]; 

evenNumbers.reduce(<span class="hljs-function">(<span class="hljs-params">sum, current</span>) =&gt;</span> sum += current, <span class="hljs-number">0</span>);
</code></pre>
<h2 id="heading-how-to-use-functions-and-arrow-functions-in-javascript">How to Use Functions and Arrow Functions in JavaScript</h2>
<h3 id="heading-functions">Functions</h3>
<p>A function is a block of code that performs a particular task. A function takes an argument, performs a task using the argument, and returns a result.</p>
<p>Functions are used to create functional components in React.</p>
<p>To declare a function you will use the keyword "function" and the function's name like this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">plusFour</span>(<span class="hljs-params">a</span>)  </span>{        
    <span class="hljs-keyword">return</span> a + <span class="hljs-number">4</span>;    
}
</code></pre>
<p>The function in the code above is named "plusFour" which takes an argument "a", adds four to "a" and returns the result.</p>
<p>To execute a function you will call the function by writing the function's name with brackets</p>
<pre><code class="lang-js"><span class="hljs-comment">// We will call the plusFour function in the earlier example    </span>

plusFour();
</code></pre>
<h3 id="heading-arrow-functions">Arrow functions</h3>
<p>Arrow functions are an alternative way of writing functions. They are more compact and also, they contain deliberate limitations. You can rewrite the plusFour function above as an arrow function like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> plusFour = <span class="hljs-function">(<span class="hljs-params">a</span>) =&gt;</span> {        
    <span class="hljs-keyword">return</span> a + <span class="hljs-number">4</span>;    
}
</code></pre>
<p>Since the return statement is just one line, we can make the arrow function one line:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> plusFour = <span class="hljs-function">(<span class="hljs-params">a</span>) =&gt;</span> a + <span class="hljs-number">4</span>;
</code></pre>
<p>Arrow functions cannot be used as methods, generators, or constructors while a regular function can.</p>
<h2 id="heading-es-modules">ES Modules</h2>
<p>Before 2015, JavaScript variables, arrays, objects, and functions created in a file could only be accessed in that file.</p>
<p>But, with the introduction of ES6 in 2015 came modules. Modules allow you to carry out objects, arrays, functions, and so on in one file and use them in another file.</p>
<p>This helps you to maintain the size of your file while your application continues to grow larger.</p>
<p>Modules are what make React work as a single page application framework. All other files are in the form of components and are imported when and where they are needed.</p>
<p>There are two keywords we use when we work with modules:</p>
<ul>
<li><p>export keyword</p>
</li>
<li><p>import keyword</p>
</li>
</ul>
<p>The export keyword allows you to make the content of the module available to all other JavaScript files, while the import keyword allows you to bring in available content from one JavaScript file into another JavaScript file.</p>
<p>In the example below, the cook function is exported from its file.</p>
<pre><code class="lang-js"><span class="hljs-comment">// file name: cook.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cook</span>(<span class="hljs-params">ingredients, water, heat</span>) </span>{        
    <span class="hljs-keyword">let</span> food = ingredients + water + heat;        
    <span class="hljs-keyword">return</span> food;     
}    

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> cook;
</code></pre>
<p>Then, in the example below, the cook function is imported into the kitchen.js file and called.</p>
<pre><code class="lang-js"><span class="hljs-comment">// file name: kitchen.js</span>

<span class="hljs-keyword">import</span> cook <span class="hljs-keyword">from</span> <span class="hljs-string">'./cook'</span>;    
cook();
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>These seven JavaScript concepts are the most important ones to know if you're trying to learn React.</p>
<p>By learning these concepts it will be easier for you to learn React because you will start seeing their applications in your React code.</p>
<p>You should read more in-depth about these concepts and also try to formulate code examples involving them so you can better understand them.</p>
<p>Keep on learning, and keep on improving.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
