<?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[ Niladri S. Jyoti - 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[ Niladri S. Jyoti - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 16:29:52 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/codenil/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Refresher for React Beginners – Key JS Concepts to Know ]]>
                </title>
                <description>
                    <![CDATA[ The Back Story A few years ago, I was introduced to React and immediately fell in love with its component-based, state-driven approach to building web applications. But as I delved deeper into its ecosystem, I encountered not just React, but a range ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-refresher-for-react-beginners/</link>
                <guid isPermaLink="false">67054d002fc10cc07ef1dc4f</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Frontend Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Beginner Developers ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Learning Journey ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Niladri S. Jyoti ]]>
                </dc:creator>
                <pubDate>Tue, 08 Oct 2024 15:17:20 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1727978962525/ee0aad46-7497-4c91-9354-dd8b0f9b4ea6.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-the-back-story">The Back Story</h2>
<p>A few years ago, I was introduced to React and immediately fell in love with its component-based, state-driven approach to building web applications.</p>
<p>But as I delved deeper into its ecosystem, I encountered not just React, but a range of supporting libraries like Material UI, React Router, Reactstrap, Redux, and more. While exciting, these new concepts and libraries could also feel overwhelming.</p>
<p>I soon realized that mastering React requires a solid understanding of modern JavaScript, especially the ES6+ features. This realization encouraged me to revisit some fundamental JavaScript topics, which helped me become more comfortable with React and write cleaner, more efficient code.</p>
<p>In this guide, I will share my notes as a concise and practical reference. These key JavaScript concepts will give you a strong foundation before you dive deep into React. Whether you’re a beginner or revisiting the language, this guide should give you a boost as you tackle the React ecosystem.</p>
<h2 id="heading-lets-get-back-to-work">Let’s Get Back to Work</h2>
<p>Since React is based on JavaScript, it’s essential to have a good grasp of the language before you start learning React.</p>
<p>I recommend a comprehensive resource like <a target="_blank" href="https://javascript.info/">The Modern JavaScript Tutor</a><a target="_blank" href="https://javascript.info/">ial</a> for an in-depth review. But if you feel confident about most of JavaScript and just need a brush-up, here’s my recommended list of crucial topics:</p>
<ol>
<li><p><a class="post-section-overview" href="#heading-1-template-literals">Template Literals</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-arrow-functions">Arrow Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-default-parameters-or-values">Default Parameters (or Values)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-destructuring-objects-and-arrays">Destructuring Objects and Arrays</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-rest-and-spread-operators">Rest and Spread Operators</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-6-map-filter-and-reduce-methods">Map, Filter, and Reduce Methods</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-7-mutability-issues-with-methods-like-array-sort">Mutability Issues with Methods like Array Sort</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-8-ternary-operator">Ternary Operator</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-9-short-circuiting-and-logical-operators">Short-Circuiting and Logical Operators</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-10-optional-chaining">Optional Chaining</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-11-asynchronous-js-callbacks-promises-asyncawait">Asynchronous JS (Callbacks, Promises, Async/Await)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-12-closures">Closures</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-13-modules-importexport">Modules (import/export)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-14-event-handling-and-bubbling">Event Handling and Bubbling</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-15-classes-and-prototypes">Classes and Prototypes</a></p>
</li>
</ol>
<h2 id="heading-1-template-literals">1. Template Literals</h2>
<p>Template literals simplify string interpolation and multiline text formatting. By using backticks (<code>`___` </code>), you can embed expressions into strings with <code>${}</code>. This makes concatenating variables and expressions with text easy, eliminating the need for cumbersome string concatenation.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> numEggs = <span class="hljs-number">4</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`In breakfast, I eat <span class="hljs-subst">${numEggs}</span> eggs.`</span>);
<span class="hljs-comment">//Output: In breakfast, I eat 4 eggs.</span>

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Today, I ate only half of it, I ate just <span class="hljs-subst">${numEggs/<span class="hljs-number">2</span>}</span> eggs.`</span>);
<span class="hljs-comment">//Output: Today I ate only half of it, I ate just 2 eggs.</span>
</code></pre>
<p>Additionally, template literals support multiline strings (without needing the newline character, that is <code>\n</code>, and also you can add spaces). This lets developers create more readable and organized code.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Today I had:
- Breakfast
- Lunch
- Dinner`</span>);
<span class="hljs-comment">/* Output (now shows multiline text as shown below): 
Today I had:
- Breakfast
- Lunch
- Dinner
*/</span>
</code></pre>
<p>With their flexibility and clarity, template literals have become a preferred method for handling strings and dynamic content in modern JavaScript.</p>
<h2 id="heading-2-arrow-functions">2. Arrow Functions</h2>
<p>Arrow functions provide a more concise syntax for writing functions and automatically bind <code>this</code> to the context in which they're declared. They are a staple of React development, as they simplify event handlers, lifecycle methods, and other functional logic. Let’s explore different variations of arrow functions.</p>
<p><strong>Arrow Function with a Single Argument:</strong> When an arrow function has a single argument, you can omit the parentheses. Here’s an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> greet = <span class="hljs-function"><span class="hljs-params">name</span> =&gt;</span> <span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>;
<span class="hljs-built_in">console</span>.log(greet(<span class="hljs-string">'John'</span>)); <span class="hljs-comment">// Hello, John!</span>
</code></pre>
<p><strong>Arrow Function without Arguments:</strong> If there are no arguments, you still need to use parentheses.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sayHello = <span class="hljs-function">() =&gt;</span> <span class="hljs-string">'Hello, world!'</span>;
<span class="hljs-built_in">console</span>.log(sayHello()); <span class="hljs-comment">// Hello, world!</span>
</code></pre>
<p><strong>Arrow Function with Multiple Arguments:</strong> For multiple arguments, parentheses are mandatory.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> add = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b;
<span class="hljs-built_in">console</span>.log(add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// 5</span>
</code></pre>
<p><strong>Single-Line Function Body (Implicit Return):</strong> When the function body is a single expression, you can omit the <code>return</code> keyword and curly braces. This is known as an implicit return.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> multiply = <span class="hljs-function">(<span class="hljs-params">x, y</span>) =&gt;</span> x * y;
<span class="hljs-built_in">console</span>.log(multiply(<span class="hljs-number">4</span>, <span class="hljs-number">5</span>)); <span class="hljs-comment">// 20</span>
</code></pre>
<p><strong>Multi-Line Function Body:</strong> For more complex logic or multiple statements, you need curly braces, and an explicit <code>return</code> is required if the function returns a value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> getFullName = <span class="hljs-function">(<span class="hljs-params">firstName, lastName</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> fullName = <span class="hljs-string">`<span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>`</span>;
  <span class="hljs-keyword">return</span> fullName;
};
<span class="hljs-built_in">console</span>.log(getFullName(<span class="hljs-string">'John'</span>, <span class="hljs-string">'Doe'</span>)); <span class="hljs-comment">// John Doe</span>
</code></pre>
<p><strong>Returning an Object:</strong> To return an object directly, wrap the object in parentheses to avoid confusion with the function body.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> createUser = <span class="hljs-function">(<span class="hljs-params">name, age</span>) =&gt;</span> ({ name, age });
<span class="hljs-built_in">console</span>.log(createUser(<span class="hljs-string">'Alice'</span>, <span class="hljs-number">30</span>)); <span class="hljs-comment">// { name: 'Alice', age: 30 }</span>
</code></pre>
<p><strong>Arrow Functions in Callbacks:</strong> Arrow functions are often used as callbacks for array methods like <code>map</code>, <code>filter</code>, and <code>reduce</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
<span class="hljs-keyword">const</span> squares = numbers.map(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num * num);
<span class="hljs-built_in">console</span>.log(squares); <span class="hljs-comment">// [1, 4, 9, 16]</span>
</code></pre>
<p>To learn more about how arrow functions compare with other ways to define functions, you may read this blog on <a target="_blank" href="https://medium.com/stackademic/3-common-ways-of-writing-functions-1fc62f478fe3">ways to write JS functions</a>.</p>
<h2 id="heading-3-default-parameters-or-values">3. Default Parameters (or Values)</h2>
<p>Default parameters allow functions to have pre-set values if no arguments are passed, or when an argument is <code>undefined</code>. This feature is helpful when writing flexible components in React, where you may not always pass every prop or argument.</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 class="hljs-string">'Stranger'</span></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${name}</span>!`</span>);
}
greet(); <span class="hljs-comment">// Hello, Stranger!</span>
greet(<span class="hljs-string">'Alice'</span>); <span class="hljs-comment">// Hello, Alice!</span>
</code></pre>
<p>It is relevant to mention here that there’s another commonly used approach in JavaScript, which is leveraging logical operators like <code>||</code> to set a default value when the given value is falsy (that is, values like <code>0</code>, <code>null</code>, <code>undefined</code>, <code>false</code>, or <code>""</code>).</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-keyword">const</span> finalName = name || <span class="hljs-string">'Stranger'</span>;
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, <span class="hljs-subst">${finalName}</span>!`</span>);
}

greet(); <span class="hljs-comment">// Hello, Stranger!</span>
greet(<span class="hljs-string">''</span>); <span class="hljs-comment">// Hello, Stranger!</span>
greet(<span class="hljs-string">'John'</span>); <span class="hljs-comment">// Hello, John!</span>
</code></pre>
<p>The above process uses a concept called short-circuiting of logical operators, which is discussed in Section 9 below.</p>
<h2 id="heading-4-destructuring-objects-and-arrays">4. Destructuring Objects and Arrays</h2>
<p>Destructuring allows you to extract values from arrays and properties from objects into variables. This concise syntax makes your code cleaner and more readable.</p>
<p>To extract specific values from an array or object, use destructuring by enclosing the desired variables within curly braces for objects or square brackets for arrays.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example of Array Destructuring</span>
<span class="hljs-keyword">const</span> [first, second] = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>];
<span class="hljs-built_in">console</span>.log(first); <span class="hljs-comment">// 10</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example of Object Destructuring</span>
<span class="hljs-keyword">const</span> user = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> };
<span class="hljs-keyword">const</span> { name, age } = user;
<span class="hljs-built_in">console</span>.log(name); <span class="hljs-comment">// Alice</span>
</code></pre>
<p>Destructuring is commonly used in React for handling props and state. To see more specific use cases of destructuring with code examples, read this <a target="_blank" href="https://medium.com/@codenil/destructuring-a-quick-reference-a7b2fa09c88a">quick reference on destructuring</a>.   </p>
<h2 id="heading-5-rest-and-spread-operators">5. Rest and Spread Operators</h2>
<p>The rest and spread operators are incredibly versatile and widely used in JavaScript. Both are represented by three dots (<code>...</code>), but their meanings differ depending on the context in which they are used.</p>
<h3 id="heading-spread-operator-expands-elements-of-an-array-or-object">Spread Operator: Expands elements of an array or object.</h3>
<p>The spread operator is primarily used to unpack arrays or objects into individual elements. This is especially useful for creating shallow copies or merging arrays (and objects) without mutating the original.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr1 = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> arr2 = [...arr1, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-built_in">console</span>.log(arr2); <span class="hljs-comment">// [1, 2, 3, 4, 5]</span>

<span class="hljs-comment">/* arr2 is created by spreading the elements of arr1 
 and then adding additional values */</span>
</code></pre>
<p>The spread operator can also be used to copy objects or combine objects:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj1 = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> };
<span class="hljs-keyword">const</span> obj2 = { ...obj1, <span class="hljs-attr">job</span>: <span class="hljs-string">'Engineer'</span> };
<span class="hljs-built_in">console</span>.log(obj2); <span class="hljs-comment">// { name: 'Alice', age: 25, job: 'Engineer' }</span>

<span class="hljs-comment">/* obj2 is created by spreading the properties of obj1
 and adding a new property */</span>
</code></pre>
<p>This is a common pattern when updating the state in React applications.</p>
<h3 id="heading-rest-operator-collects-multiple-elements-into-an-array">Rest Operator: Collects multiple elements into an array.</h3>
<p>The rest operator does the reverse: it collects multiple arguments or elements into a single array. It’s especially useful when working with variadic functions (functions that accept a variable number of arguments).</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">...args</span>) </span>{
  <span class="hljs-keyword">return</span> args.reduce(<span class="hljs-function">(<span class="hljs-params">total, num</span>) =&gt;</span> total + num, <span class="hljs-number">0</span>);
}
<span class="hljs-built_in">console</span>.log(sum(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// 6</span>
</code></pre>
<p>In this example, <code>...args</code> gathers all arguments passed to the function into an array. This allows the function to handle any number of arguments dynamically.</p>
<p>You can also use the rest operator to collect remaining properties of an object or elements of an array:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [first, ...rest] = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>];
<span class="hljs-built_in">console</span>.log(first); <span class="hljs-comment">// 10</span>
<span class="hljs-built_in">console</span>.log(rest);  <span class="hljs-comment">// [20, 30, 40]</span>
</code></pre>
<p>This technique is particularly useful in React when working with props, where you might want to extract specific properties and pass the rest down to child components.</p>
<h2 id="heading-6-map-filter-and-reduce-methods">6. Map, Filter, and Reduce Methods</h2>
<p>The <code>map()</code>, <code>filter()</code>, and <code>reduce()</code> methods are incredibly powerful for array manipulation in JavaScript, and they play a crucial role in React for tasks like rendering lists, filtering data, and summarizing information.</p>
<ul>
<li><p><strong>Map</strong>: Transforms elements of an array </p>
</li>
<li><p><strong>Filter</strong>: Creates a new array with elements that pass a condition </p>
</li>
<li><p><strong>Reduce</strong>: Accumulates values into a single result </p>
</li>
</ul>
<h3 id="heading-1-map-method">1. Map Method</h3>
<p>The <code>map()</code> method creates a new array by transforming each element of the original array according to the function provided. This method is essential in React for dynamically rendering lists of components from arrays of data.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example (Basic Usage):</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
<span class="hljs-keyword">const</span> doubled = numbers.map(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num * <span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(doubled); <span class="hljs-comment">// [2, 4, 6, 8]</span>
</code></pre>
<p>In React, <code>map()</code> is commonly used to render lists of components. Here's how you might use it in a React component:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example (Rendering a List in React):</span>
<span class="hljs-keyword">const</span> users = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Bob'</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Charlie'</span> }
];

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

<span class="hljs-comment">/* Note that each &lt;li&gt; element in the list has a unique 'key' prop.
It is required by React when rendering lists like this */</span>
</code></pre>
<h3 id="heading-2-filter-method">2. Filter Method</h3>
<p>The <code>filter()</code> method creates a new array with all elements that pass the condition specified in the callback function. It's frequently used in React when you want to display only certain items based on user input or a specific condition.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example (Basic Usage):</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];
<span class="hljs-keyword">const</span> evenNumbers = numbers.filter(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num % <span class="hljs-number">2</span> === <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(evenNumbers); <span class="hljs-comment">// [2, 4]</span>
</code></pre>
<p>For a use case, imagine you have a list where some tasks are completed while some are not. So, you can use <code>filter()</code> to display (render) only the tasks that are not yet completed. </p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example (Filtering Data in React):</span>
<span class="hljs-keyword">const</span> todos = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">task</span>: <span class="hljs-string">'Learn JavaScript'</span>, <span class="hljs-attr">completed</span>: <span class="hljs-literal">true</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">task</span>: <span class="hljs-string">'Learn React'</span>, <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">task</span>: <span class="hljs-string">'Build a project'</span>, <span class="hljs-attr">completed</span>: <span class="hljs-literal">false</span> }
];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">TodoList</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> incompleteTodos = todos.filter(<span class="hljs-function"><span class="hljs-params">todo</span> =&gt;</span> !todo.completed);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      {incompleteTodos.map(todo =&gt; (
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{todo.id}</span>&gt;</span>{todo.task}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
      ))}
    <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>
  );
}
</code></pre>
<h3 id="heading-3-reduce-method">3. Reduce Method</h3>
<p>The <code>reduce()</code> method executes a reducer function on each element of the array, resulting in a single output value. It's used when you need to accumulate data, such as summing values or combining objects.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example (Basic Usage):</span>
<span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
<span class="hljs-keyword">const</span> sum = numbers.reduce(<span class="hljs-function">(<span class="hljs-params">total, num</span>) =&gt;</span> total + num, <span class="hljs-number">0</span>);
<span class="hljs-built_in">console</span>.log(sum); <span class="hljs-comment">// 10</span>
</code></pre>
<p>You might use <code>reduce()</code> in React to calculate a summary of some data, like the total price of items in a shopping cart — considering the items’ individual price and quantities:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example (Using reduce() in React):</span>
<span class="hljs-keyword">const</span> cart = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Apple'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">1.5</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">3</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Banana'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">2</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Orange'</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">quantity</span>: <span class="hljs-number">1</span> }
];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CartSummary</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> total=cart.reduce(<span class="hljs-function">(<span class="hljs-params">sum, item</span>)=&gt;</span>sum + item.price * item.quantity, <span class="hljs-number">0</span>);
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>Total: ${total}<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>These array methods are invaluable in React for manipulating and displaying data dynamically. They allow for clean, readable, and declarative logic within your components.</p>
<p>You can also combine these methods to create powerful data transformations. For example, you can filter an array and then map the results: <code>filter()</code> is used to extract only the adult users, and <code>map()</code> is then used to create a list of their names.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example: combined use of filter and map methods</span>
<span class="hljs-keyword">const</span> users = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Bob'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">17</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">'Charlie'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> }
];

<span class="hljs-keyword">const</span> adultNames = users
  .filter(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.age &gt;= <span class="hljs-number">18</span>)
  .map(<span class="hljs-function"><span class="hljs-params">user</span> =&gt;</span> user.name);
<span class="hljs-built_in">console</span>.log(adultNames); <span class="hljs-comment">// ['Alice', 'Charlie']</span>
</code></pre>
<p>The <code>map()</code> and <code>filter()</code> methods are easier to grasp because they follow a simple "one-to-one" or "one-to-zero-or-more" relationship: <code>map()</code> transforms each element into a new one, while <code>filter()</code> includes or excludes elements based on a condition, returning a similarly structured array.</p>
<p>In contrast, <code>reduce()</code> is more complex, as it accumulates values into a single result rather than maintaining a one-to-one relationship. It requires managing both the current value and an accumulator, making it conceptually different and harder to interpret than <code>map()</code> or <code>filter()</code>.</p>
<p>The optional initial value in <code>reduce()</code> adds to the complexity, as it sets the starting point for the accumulation. Without it, the first array element is used as the accumulator, which can cause unexpected results with empty arrays or non-numeric data. To get consistent results for your use of the <code>reduce()</code> method, you may read about <a target="_blank" href="https://medium.com/@codenil/the-importance-of-initial-value-in-array-reduce-method-86284878d1e4">the importance of an initial value</a>.</p>
<h2 id="heading-7-mutability-issues-with-methods-like-array-sort">7. Mutability Issues with Methods like Array Sort</h2>
<p>The <code>Array.sort()</code> method sorts the elements of an array in place, meaning it <strong>mutates</strong> the original array. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">4</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>];
numbers.sort();
<span class="hljs-built_in">console</span>.log(numbers); <span class="hljs-comment">// [1, 2, 3, 4]</span>
</code></pre>
<p>While this works in plain JavaScript, it’s problematic in React, where <strong>immutability</strong> is crucial for correctly managing state.</p>
<p>React detects state changes by comparing previous and new states and triggers re-renders based on those changes. But when an array is mutated in place (like with <code>sort()</code>), React may fail to recognize the change, leading to stale UI updates or unpredictable behavior.</p>
<p>To avoid this, it’s best to create a copy using the spread operator (<code>...</code>) or <code>slice()</code> before sorting, ensuring that the original state remains unchanged:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">4</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>];
<span class="hljs-keyword">const</span> sortedNumbers = [...numbers].sort();
<span class="hljs-built_in">console</span>.log(sortedNumbers); <span class="hljs-comment">// [1, 2, 3, 4]</span>
</code></pre>
<p>Methods like <code>map()</code>, <code>filter()</code>, <code>reduce()</code>, or copying arrays/objects before modifying them is essential for preserving immutability and ensuring reliable state management in React.</p>
<h2 id="heading-8-ternary-operator">8. Ternary Operator</h2>
<p>The ternary operator is a shorthand for conditional statements. It has the syntax <code>condition ? expressionIfTrue : expressionIfFalse</code>. If the condition evaluates to true, it executes the <code>expressionIfTrue</code>. If it’s false, it executes the <code>expressionIfFalse</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> isUserRegistered = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">let</span> message = isUserRegistered ? <span class="hljs-string">'Please login'</span> : <span class="hljs-string">'Please Sign-up'</span>;
<span class="hljs-built_in">console</span>.log(message);
<span class="hljs-comment">//Output: Please login</span>
</code></pre>
<p>In React, it is an efficient replacement for the if-else statements in certain scenarios — like <a target="_blank" href="https://blog.stackademic.com/conditional-rendering-in-react-four-different-approaches-f25faddf0161">conditional rendering</a>, which delivers elements and components based on certain conditions or values of state or props data.</p>
<h2 id="heading-9-short-circuiting-and-logical-operators">9. Short-Circuiting and Logical Operators</h2>
<p>Logical operators like <code>&amp;&amp;</code> (AND) and <code>||</code> (OR) can be used to create clean and concise conditional logic in JavaScript. In React, these operators often determine whether a component or JSX element should render.</p>
<h3 id="heading-1-logical-and-ampamp">1. Logical AND (<code>&amp;&amp;</code>)</h3>
<p>The <code>&amp;&amp;</code> operator evaluates the expression on the left side first. If it's <code>true</code>, the right-hand expression is evaluated and returned. If the left side is <code>false</code>, the entire expression short-circuits, meaning the right-hand expression is ignored.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> isLoggedIn = <span class="hljs-literal">true</span>;
<span class="hljs-built_in">console</span>.log(isLoggedIn &amp;&amp; <span class="hljs-string">'Welcome back!'</span>); <span class="hljs-comment">// Welcome back!</span>
</code></pre>
<p>This behavior is often used in React for conditional rendering, like so:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserGreeting</span>(<span class="hljs-params">{ isLoggedIn }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      {isLoggedIn &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Welcome back!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>This is a common pattern in React for rendering UI based on certain conditions without needing an explicit <code>if</code> statement.</p>
<h3 id="heading-2-logical-or">2. Logical OR (<code>||</code>)</h3>
<p>The <code>||</code> operator works in the opposite way. It evaluates the left-hand expression first, and if it's <code>true</code> (or any truthy value), it returns that value. If the left-hand expression is <code>false</code> (or any falsy value), it evaluates and returns the right-hand expression. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> username = <span class="hljs-string">''</span>;
<span class="hljs-built_in">console</span>.log(username || <span class="hljs-string">'Guest'</span>); <span class="hljs-comment">// Output: Guest</span>
</code></pre>
<p>In React, this is useful for providing default values, like so:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserProfile</span>(<span class="hljs-params">{ username }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Hello, {username || 'Guest'}!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>Note that the <strong>nullish coalescing operator (</strong><code>??</code><strong>)</strong> is similar to the logical OR operator (<code>||</code>), but with a key difference in how they treat <strong>falsy</strong> values.</p>
<p>The nullish coalescing operator (<code>??</code>) specifically checks if the left-hand side is either <code>null</code> <strong>or</strong> <code>undefined</code>. If the value is <code>null</code> or <code>undefined</code>, it returns the right-hand side. This allows <code>0</code>, <code>false</code>, and <code>''</code> to be treated as valid values and not overridden. You can read about this and more such <a target="_blank" href="https://medium.com/@codenil/javascript-operators-some-nuances-57300eb2c354">nuances associated with JavaScript Operators</a>.</p>
<h3 id="heading-3-combining-ampamp-and-for-complex-logic">3. Combining <code>&amp;&amp;</code> and <code>||</code> for Complex Logic</h3>
<p>You can also combine <code>&amp;&amp;</code> and <code>||</code> to create more complex conditional logic or nested logic.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> isAdmin = <span class="hljs-literal">false</span>;
<span class="hljs-keyword">let</span> isLoggedIn = <span class="hljs-literal">true</span>;
<span class="hljs-built_in">console</span>.log(isAdmin &amp;&amp; <span class="hljs-string">'Admin Panel'</span> || isLoggedIn &amp;&amp; <span class="hljs-string">'User Dashboard'</span>); 
<span class="hljs-comment">// Output: User Dashboard</span>
</code></pre>
<p>This can be useful in React for deciding what to render based on multiple conditions having an interplay.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Dashboard</span>(<span class="hljs-params">{ isAdmin, isLoggedIn }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      {isAdmin &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Welcome to the Admin Panel<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
      {!isAdmin &amp;&amp; isLoggedIn &amp;&amp; <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Welcome to the User Dashboard<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-10-optional-chaining">10. Optional Chaining</h2>
<p><strong>Optional chaining (</strong><code>?.</code><strong>)</strong> is a powerful feature introduced in JavaScript (ES2020) that allows you to safely access deeply nested properties of an object without worrying about encountering <code>undefined</code> or <code>null</code> errors.</p>
<p>In traditional JavaScript, accessing nested properties of objects could result in errors if any part of the chain was <code>undefined</code> or <code>null</code>, causing your code to break. Optional chaining provides a cleaner and safer way to handle these scenarios.</p>
<p>The optional chaining operator short-circuits and returns <code>undefined</code> if the value before it is <code>null</code> or <code>undefined</code>. This prevents the code from throwing an error when trying to access the properties of a <code>null</code> or <code>undefined</code> value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> user = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>, <span class="hljs-attr">address</span>: { <span class="hljs-attr">city</span>: <span class="hljs-string">'Wonderland'</span> } };
<span class="hljs-built_in">console</span>.log(user?.address?.city); 
<span class="hljs-comment">// Output: Wonderland</span>

<span class="hljs-comment">// Without optional chaining</span>
<span class="hljs-keyword">let</span> user1 = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Bill'</span> };
<span class="hljs-built_in">console</span>.log(user1.address.city); 
<span class="hljs-comment">// Output: Error: Cannot read property 'city' of undefined</span>

<span class="hljs-comment">// With Optional Chaining:</span>
<span class="hljs-keyword">let</span> user2 = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Caleb'</span> };
<span class="hljs-built_in">console</span>.log(user2?.address?.city); <span class="hljs-comment">// undefined</span>
</code></pre>
<p>Optional chaining can also be used in different scenarios, such as   with function calls (to check if a function exists before invoking it), while accessing elements in arrays (especially when you’re unsure whether the array exists or whether it has enough elements), or while accessing dynamic properties, as shown below:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Optional Chaining with Functions:</span>
<span class="hljs-keyword">let</span> user1 = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span>,
  <span class="hljs-attr">greet</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-string">'Hello!'</span>
};

<span class="hljs-built_in">console</span>.log(user1.greet?.()); <span class="hljs-comment">// Hello!</span>
<span class="hljs-built_in">console</span>.log(user1.sayGoodbye?.()); <span class="hljs-comment">// undefined</span>

<span class="hljs-comment">// Optional Chaining with Arrays:</span>
<span class="hljs-keyword">let</span> users = [{ <span class="hljs-attr">name</span>: <span class="hljs-string">'Alice'</span> }, { <span class="hljs-attr">name</span>: <span class="hljs-string">'Bob'</span> }];
<span class="hljs-built_in">console</span>.log(users[<span class="hljs-number">0</span>]?.name); <span class="hljs-comment">// Alice</span>
<span class="hljs-built_in">console</span>.log(users[<span class="hljs-number">2</span>]?.name); <span class="hljs-comment">// undefined</span>

<span class="hljs-comment">// Optional Chaining with Dynamic Properties:</span>
<span class="hljs-keyword">let</span> user2 = { <span class="hljs-attr">name</span>: <span class="hljs-string">'Bill'</span>, <span class="hljs-attr">preferences</span>: { <span class="hljs-attr">theme</span>: <span class="hljs-string">'dark'</span> } };
<span class="hljs-keyword">let</span> property = <span class="hljs-string">'preferences'</span>;
<span class="hljs-built_in">console</span>.log(user2?.[property]?.theme); <span class="hljs-comment">// dark</span>

property = <span class="hljs-string">'settings'</span>;
<span class="hljs-built_in">console</span>.log(user2?.[property]?.theme); <span class="hljs-comment">// undefined</span>
</code></pre>
<p>When working with deeply nested objects, optional chaining can save you from having to write repetitive null checks at every level.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> user = { <span class="hljs-attr">profile</span>: { <span class="hljs-attr">address</span>: { <span class="hljs-attr">city</span>: <span class="hljs-string">'Wonderland'</span> } } };

<span class="hljs-comment">// usage without optional chaining (using short-circuiting):</span>
<span class="hljs-keyword">if</span> (user &amp;&amp; user.profile &amp;&amp; user.profile.address &amp;&amp; user.profile.address.city) {
  <span class="hljs-built_in">console</span>.log(user.profile.address.city);
}

<span class="hljs-comment">// usage with optional chaining (saving repititive null checks):</span>
<span class="hljs-built_in">console</span>.log(user?.profile?.address?.city); <span class="hljs-comment">// Wonderland</span>
</code></pre>
<p>In React, optional chaining is particularly useful when dealing with props, API responses, or any data that may not always be available. It helps prevent errors when rendering components based on dynamic or incomplete data.</p>
<p>Optional chaining significantly reduces the complexity of your code, making it cleaner and more readable, especially when dealing with deeply nested structures.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example usage of Optional Chaining in React</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">UserProfile</span>(<span class="hljs-params">{ user }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Name: {user?.name}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>City: {user?.address?.city ?? 'Unknown'}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<h2 id="heading-11-asynchronous-js-callbacks-promises-asyncawait">11. Asynchronous JS: Callbacks, Promises, Async/Await</h2>
<p>JavaScript is a single-threaded language,  meaning  it can execute one task at a time. But handling asynchronous operations is crucial, especially for tasks like fetching data in React. <code>Callback</code> functions are one of the earliest patterns used to handle asynchronous behavior, like so:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchData</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Data fetched"</span>);
    callback({ <span class="hljs-attr">user</span>: <span class="hljs-string">"John"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span> });
  }, <span class="hljs-number">2000</span>);
}

fetchData(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"User:"</span>, data.user);
});

<span class="hljs-comment">/* Output:
Data fetched
User: John
*/</span>
</code></pre>
<p>So, as you can see, callbacks are effective for handling simple operations that depend on asynchronous tasks, like the example above.</p>
<p>But when multiple asynchronous tasks rely on each other, callbacks can lead to deeply nested code, commonly referred to as <strong>callback hell</strong>.</p>
<p>To solve this problem, <code>promise</code>s were introduced. A <strong>promise</strong> is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Instead of nesting multiple callbacks, promises allow chaining, leading to more structured and readable code.</p>
<p>Similarly, the Fetch API, which is commonly used for handling network requests in React applications, returns a promise which you can handle like so:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchUserDetails</span>(<span class="hljs-params">userId</span>) </span>{
  <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">`https://api.example.com/users/<span class="hljs-subst">${userId}</span>`</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (!response.ok) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Failed to fetch user details'</span>);
      }
      <span class="hljs-keyword">return</span> response.json();
    })
    .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Fetched user details"</span>);
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">id</span>: userId, <span class="hljs-attr">name</span>: data.name };
    });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">fetchPostsByUser</span>(<span class="hljs-params">user</span>) </span>{
  <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">`https://api.example.com/users/<span class="hljs-subst">${user.id}</span>/posts`</span>)
    .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (!response.ok) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Failed to fetch posts'</span>);
      }
      <span class="hljs-keyword">return</span> response.json();
    })
    .then(<span class="hljs-function">(<span class="hljs-params">posts</span>) =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Fetched posts for <span class="hljs-subst">${user.name}</span>`</span>);
      <span class="hljs-keyword">return</span> posts;
    });
}

<span class="hljs-comment">// Chain promises</span>
fetchUserDetails(<span class="hljs-number">1</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> fetchPostsByUser(user))
  .then(<span class="hljs-function">(<span class="hljs-params">posts</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(posts))
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error:"</span>, error));
</code></pre>
<p>Promises provide a more readable way to handle sequential asynchronous tasks. They also simplify error handling using <code>.catch()</code>. But, while promises eliminate the deep nesting of callbacks, chaining too many <code>.then()</code> calls can still become verbose and hard to follow.</p>
<p>Introduced in ES2017, <code>async/await</code> makes working with promises even simpler. With <strong>async/await</strong>, asynchronous code looks and behaves more like synchronous code, which greatly improves readability. Here’s how it works:</p>
<ul>
<li><p><strong>async function:</strong> An <code>async</code> function returns a promise. The <code>async</code> keyword allows the function to return a resolved promise implicitly.</p>
</li>
<li><p><strong>await expression:</strong> Inside an <code>async</code> function, <code>await</code> pauses the execution of the function until the promise resolves. It simplifies promise handling, as we can directly assign the resolved value to a variable.</p>
</li>
</ul>
<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">getUserAndPosts</span>(<span class="hljs-params">userId</span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchUserDetails(userId); <span class="hljs-comment">// Waits for user details</span>
    <span class="hljs-keyword">const</span> posts = <span class="hljs-keyword">await</span> fetchPostsByUser(user);  <span class="hljs-comment">// Waits for posts</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Posts:"</span>, posts);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error:"</span>, error);
  }
}

getUserAndPosts(<span class="hljs-number">1</span>);

<span class="hljs-comment">/* Output:
Fetched user details
Fetched posts for John
Posts: ["Post 1", "Post 2"]
*/</span>
</code></pre>
<p><code>Async/await</code> makes asynchronous code appear synchronous, which greatly improves readability and maintainability. The <code>try/catch</code> block also simplifies error handling, making it consistent with how errors are caught in synchronous code.</p>
<h3 id="heading-error-handling-in-async-code"><strong>Error Handling in Async Code</strong></h3>
<p>Error handling in asynchronous code can be tricky. Callbacks require error-first handling, while promises and <code>async/await</code> offer more structured approaches, as shown below:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Handling Errors with Promises</span>
fetchUserDetails(<span class="hljs-number">1</span>)
  .then(<span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> fetchPostsByUser(user))
  .then(<span class="hljs-function">(<span class="hljs-params">posts</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(posts))
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error fetching data:"</span>, error));
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// Handling Errors with Async/Await</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getUserAndPosts</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">const</span> user = <span class="hljs-keyword">await</span> fetchUserDetails(<span class="hljs-number">1</span>);
    <span class="hljs-keyword">const</span> posts = <span class="hljs-keyword">await</span> fetchPostsByUser(user);
    <span class="hljs-built_in">console</span>.log(posts);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error fetching data:"</span>, error);
  }
}
</code></pre>
<p>Understanding the evolution of asynchronous JavaScript helps you write efficient, non-blocking code. For more details, you can read this article on <a target="_blank" href="https://medium.com/stackademic/mastering-asynchronous-javascript-from-callbacks-to-async-await-8449e1f5f9c0">the evolutionary progress of Asynchronous JavaScript</a>.</p>
<h2 id="heading-12-closures">12. Closures</h2>
<p>A <strong>closure</strong> in JavaScript is created when a function “remembers” the variables from its outer scope, even after the outer function has finished executing. This means that a function retains access to the environment it was created in, making closures essential for managing data across different contexts.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">outerFunction</span>(<span class="hljs-params">outerVar</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">innerFunction</span>(<span class="hljs-params">innerVar</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Outer: <span class="hljs-subst">${outerVar}</span>, Inner: <span class="hljs-subst">${innerVar}</span>`</span>);
  };
}

<span class="hljs-keyword">const</span> newFunction = outerFunction(<span class="hljs-string">'React'</span>);
newFunction(<span class="hljs-string">'JavaScript'</span>); <span class="hljs-comment">// Outer: React, Inner: JavaScript</span>
</code></pre>
<p>In React, closures are crucial for handling state and props within functional components. They allow functions like event handlers or asynchronous callbacks to access the latest state values even after re-renders.</p>
<p>For example, the <code>useState</code> and <code>useEffect</code> hooks rely on closures to "remember" and manage state across renders.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);
  <span class="hljs-keyword">const</span> increment = <span class="hljs-function">() =&gt;</span> setCount(count + <span class="hljs-number">1</span>); <span class="hljs-comment">// Closure keeps track of count</span>
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{increment}</span>&gt;</span>Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>;
}
</code></pre>
<p>Understanding closures ensures that you can effectively manage state and handle events in React, keeping your components consistent and predictable.</p>
<h2 id="heading-13-modules-importexport"><strong>13. Modules (import/export)</strong></h2>
<p>React projects are highly modular, meaning that the code is split into multiple files or components, each handling a specific responsibility. This modularity is enabled by <strong>ES6 modules</strong>, which allow you to <strong>export</strong> values, functions, or components from one file and <strong>import</strong> them into another.</p>
<p>Understanding how to use <code>import</code> and <code>export</code> is essential for organizing React applications and making code reusable and maintainable.</p>
<p>In the following example, the <code>greet</code> function is <strong>exported</strong> from <code>module.js</code>, making it accessible to other files.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// module.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> greet = <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello'</span>);
</code></pre>
<p>In <code>anotherFile.js</code>, we <strong>import</strong> the <code>greet</code> function from <code>module.js</code> and can now use it as if it were defined locally, like so:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// anotherFile.js</span>
<span class="hljs-keyword">import</span> { greet } <span class="hljs-keyword">from</span> <span class="hljs-string">'./module'</span>;
greet(); <span class="hljs-comment">// Hello</span>
</code></pre>
<p>React components are often exported from their own files and then imported into a central component (like <code>App.js</code>), allowing you to break down your UI into smaller, reusable pieces.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Button.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">Button</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>;
}

<span class="hljs-comment">// App.js</span>
<span class="hljs-keyword">import</span> Button <span class="hljs-keyword">from</span> <span class="hljs-string">'./Button'</span>;
</code></pre>
<p>Understanding this import/export structure is fundamental in React for managing components, reusing logic, and keeping code clean and modular.</p>
<p>Here, you may note that CommonJS was a popular module system for Node.js (server-side JavaScript) before ES6. It allowed you to export values from a file using <code>module.exports</code> and import them using <code>require()</code>.</p>
<p>While it worked well in Node.js, it wasn't natively supported by browsers. With the rise of <strong>React</strong> and other frontend libraries, the need for a <strong>native, browser-supported</strong> and <strong>standardized</strong> module system became essential and ES6 provided that.</p>
<h2 id="heading-14-event-handling-and-bubbling"><strong>14. Event Handling and Bubbling</strong></h2>
<p>React relies heavily on event handling to respond to user interactions. Events in React are managed through <strong>Synthetic Events</strong>, which provide cross-browser consistency and performance optimization. Understanding <strong>event bubbling</strong>, a process where events propagate from the target element up through its parents, is crucial for controlling component behavior.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example in vanilla JavaScript:</span>
<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"button"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked"</span>);
});
</code></pre>
<p>In the above example, clicking the button triggers the event listener, and the event “bubbles” up through parent elements unless stopped. React handles this similarly with its <code>onClick</code> events:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example in React:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>;
}
</code></pre>
<p>In React, event bubbling can lead to multiple event handlers being triggered in nested elements. For example, a parent’s <code>onClick</code> can be triggered when its child button is clicked unless it is prevented by calling <code>event.stopPropagation()</code> inside the child button’s handler method — which then prevents the click event from reaching the parent <code>div</code>. This ensures that only the desired event is handled.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example of How to Stop Event Bubbling:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleButtonClick</span>(<span class="hljs-params">event</span>) </span>{
  event.stopPropagation(); <span class="hljs-comment">// Prevents bubbling</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleDivClick</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Div clicked"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleDivClick}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleButtonClick}</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre>
<p>React’s architecture, with its component-based structure and Synthetic Event System, reduces the need for <code>stopPropagation()</code> in most cases—for example, in simpler apps where both a parent and child component are not handling the same event like a <code>click</code>.</p>
<p>But in more <strong>complex UI structures</strong>, where multiple elements handle the same event (for example, <code>onClick</code>), and you want to prevent the parent element from reacting to the child’s event, <code>stopPropagation()</code> becomes crucial for controlling event flow. This is especially important in scenarios like <strong>nested modals, dropdowns, or accordions</strong>, where a click inside the modal should not trigger a click handler on the outer container.</p>
<h2 id="heading-15-classes-and-prototypes"><strong>15. Classes and Prototypes</strong></h2>
<p>While <strong>functional components</strong> are now dominant in React, understanding <strong>JavaScript classes</strong> and <strong>prototypes</strong> is still valuable, especially when working with <strong>class-based components</strong> or maintaining <strong>legacy code</strong>. JavaScript classes provide a blueprint for creating objects, and they work by leveraging prototypes under the hood.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }  

  greet() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello, I'm <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>);
  }
}

<span class="hljs-keyword">const</span> person = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">'Alice'</span>);
person.greet(); <span class="hljs-comment">// Hello, I'm Alice</span>
</code></pre>
<p>In this example, the <code>Person</code> class defines a constructor to initialize the <code>name</code> property, and a <code>greet()</code> method that prints a message. When you create a new instance of <code>Person</code>, the method is available through JavaScript’s <strong>prototype chain</strong>.</p>
<p>Though React moved towards functional components with hooks, class-based components were the standard prior to React 16.8. Understanding classes is useful when dealing with codebases that use class components or when you need to understand features like lifecycle methods (<code>componentDidMount</code>, <code>componentDidUpdate</code>, and so on) and <code>this</code> binding, which are more prevalent in class components.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>Mastering the key JavaScript concepts outlined in this tutorial will give you a solid foundation as you dive into React development.</p>
<p>React heavily relies on modern JavaScript features like <code>map()</code>, <code>filter()</code>, destructuring, and the spread operator, all of which streamline how data is manipulated and components are rendered. And concepts like immutability, optional chaining, and the nullish coalescing operator are critical for writing clean, bug-free code that interacts effectively with dynamic data.</p>
<p>By understanding how these JavaScript features work together, you'll be well-equipped to write more efficient, maintainable React applications.</p>
<p>So, as you begin your React journey, make sure your JavaScript fundamentals are rock-solid—you'll find that it pays off as you tackle more complex challenges in your React projects. Also, if you find I missed any important concept here, please let me know. I will add it back to the article for an updated version.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Practice Your Coding Skills by Building a Program in Different Ways ]]>
                </title>
                <description>
                    <![CDATA[ While we have 365 days in other years, this year (2024) is special because it has one ‘extra’ day.  So in the spirit of Leap Day, let's practice some coding to understand various aspects of programming. We'll focus on the same program but from differ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/practice-coding-skills-by-building-a-program-different-ways/</link>
                <guid isPermaLink="false">66c37466159a4cde589f8ce0</guid>
                
                    <category>
                        <![CDATA[ learning to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Niladri S. Jyoti ]]>
                </dc:creator>
                <pubDate>Mon, 04 Mar 2024 15:39:55 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/Build-A-Leap-Year-Program-in-Many-Different-Ways-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>While we have 365 days in other years, this year (2024) is special because it has one ‘extra’ day. </p>
<p>So in the spirit of Leap Day, let's practice some coding to understand various aspects of programming. We'll focus on the same program but from different perspectives. </p>
<p>Our example program will explore different ways you can code a program that determines whether a given year is a leap year. On other days, we code. But today, let’s decode what we do and get some extra knowledge out of that process.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ul>
    <li><a href="#program-requirements">Program Requirements &amp; Prerequisites</a></li>
    <li><a href="#logical-approaches">Logical Approaches to Solving the Problem</a></li>
    <ul>
        <li><a href="#naive-approach">My Naïve Approach</a></li>
        <li><a href="#single-return">Reassignments and a Single Return Statement</a></li>
        <li><a href="#switch-case">Switching to Switch-Case from If-Else</a></li>
        <li><a href="#logical-deduction">Logical Deduction &amp; Subsets for Better Structure</a></li>
        <li><a href="#combine-conditions">Logical Operators Combining All True Conditions</a></li>
        <li><a href="#ternary-operator">Applying Nitro with the Ternary Operator</a></li>
        <li><a href="#arrow-function">Making it a Single Line Arrow Function</a></li>
    </ul>
    <li><a href="#programming-paradigm">Paradigm Shift: Declarative Programming</a></li>
    <ul>
        <li><a href="#side-effects">Functions with Side Effects</a></li>
        <li><a href="#functional-programming">More About Functional Programming</a></li>
        <li><a href="#short-circuiting">Side-Tracking: Short-Circuiting!</a></li>
        <li><a href="#declarative-programming">Encapsulation and Declarative Programming</a></li>
    </ul>
    <li><a href="#code-quality">Going Above &amp; Beyond with Code Quality</a></li>
    <ul>
        <li><a href="#validations">Validations: Beyond the Basic Specifications</a></li>
        <li><a href="#unit-testing">Testing it Out From the Outside</a></li>
    </ul>
    <li><a href="#end-note">End Note</a></li>
</ul>

<h2 id="program-requirements">Program Requirements &amp; Prerequisites</h2>

First, let’s discuss the requirements and set the specifications. The program should be able to get a year (expects a number, an integer to be specific) as an argument and returns either true or false (a boolean) depending on if it is a leap year or not. 

Through the examples, we will focus on the program logic (semantics) rather than the language (syntax). 

Over the years, I have used JavaScript most frequently so we'll use this language for the project. If you use a different language, no worries because many concepts are common between programming languages. For example, in this article, we would use arrow function which is similar to lambda function used in some other programming languages, such as Python.

So, as prerequisites, you should have a basic knowledge of programming and should be comfortable with the concepts of functions (different ways to define and call functions, return values, and so on) and conditional logic (if-else, switch-case, and so on). That would be enough to follow along, for the most part, if you want to read and try the code for yourself.

Just in the last bit, we also do unit testing of our code. If you aren't familiar with unit testing, here is a good refresher on <a target="_blank" href="https://dev.to/dstrekelj/how-to-write-unit-tests-in-javascript-with-jest-2e83">how to write unit tests in JavaScript with Jest</a>. 

<h2 id="logical-approaches">Logical Approaches to Solving the Problem</h2>

<h3 id="naive-approach">My Naïve Approach</h3>

<p>This is based on the pedagogical style of determining a leap year that I learned as a kid who knew how to divide numbers. If a year ( the number representing it) is divisible by 4, it is generally a leap year. But not always. When that year ends with two zeroes (meaning when the number is divisible by 100), it must also be divisible by 400 to be a leap year.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/FlowChart-LeapYear.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>How to determine if a year is a leap year - as described above</em></p>
<p>As a beginner programmer, my thoughts flowed like you can see in the above flowchart. As a result, I converted that logic into my program like so:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
  <span class="hljs-keyword">if</span> (year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">if</span> (year % <span class="hljs-number">100</span> == <span class="hljs-number">0</span>) {
          <span class="hljs-keyword">if</span> (year % <span class="hljs-number">400</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-keyword">else</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-comment">// Example usage:</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2024</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2023</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">1900</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2000</span>)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>This makes the program easily understandable. But with time, as I have moved farther in my programming journey, this type of code looks ugly because of so many nested conditional checks. It's not bad, but because of the nested levels, my brain has to work extra hard to get the logic from the code snapshot quickly.</p>
<h3 id="single-return">Reassignments and a Single Return Statement</h3>

<p>To avoid nested loops, many programmers follow the strategy of consecutive if conditions, avoiding the else conditions (like how Kyle Cook of Web Dev Simplified shows in this <a target="_blank" href="https://www.youtube.com/watch?v=EumXak7TyQ0">video with examples</a>). It definitely improves readability. </p>
<p>Also, it lets us use only one return statement at the end while reassigning the returnable value. Let's not discuss it too much more when you can better see the code itself:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
  <span class="hljs-keyword">let</span> isLeap = <span class="hljs-literal">false</span>;
  <span class="hljs-keyword">if</span> (year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span>) {
      isLeap = <span class="hljs-literal">true</span>;
  }
  <span class="hljs-keyword">if</span> (year % <span class="hljs-number">100</span> == <span class="hljs-number">0</span>) {
      isLeap = <span class="hljs-literal">false</span>;
  }
  <span class="hljs-keyword">if</span> (year % <span class="hljs-number">400</span> == <span class="hljs-number">0</span>) {
      isLeap = <span class="hljs-literal">true</span>;
  }
  <span class="hljs-keyword">return</span> isLeap;
}

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2024</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2023</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">1900</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2000</span>)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>The above code looks shorter and quicker to interpret. But it does affect the efficiency of the code, as now you have to go through all of the if conditions in all cases. </p>
<p>In contrast, in our previous naïve approach, due to the if-else construct, if a year is not divisible by 4 (like the year 2023), it would just be checked against one if condition. It’s true, of course, that for small programs such as this one, you don’t have to be overly concerned with efficiency.</p>
<p>The pitfall in this approach, though, is that you need to be cautious to apply all the if conditions one after another — using ‘else if’ would create trouble, as that would skip some if condition checks if the previous if condition test passed.</p>
<p>Another important fact is that the order matters. Since you started with the more generic cases of years not being a leap year (that is, let isLeap = false;), you have to go from relatively generic to relatively more specific cases. </p>
<p>So if, out of your three condition checks, the check of divisibility by 4 comes at the end, it would make ‘isLeap’ true even for years that are divisible by 100 but not divisible by 400 (like years 1700, 1800, 1900, and so on). </p>
<p>The same logical error would occur if you interchange the order of divisibility checks involving 100 and 400.</p>
<p>One last point I must mention is that some beginner programmers may think that you can not use multiple return statements and you must return only once in a program (and that you can do reassignments until that point). But experienced programmers can only call that notion a beginners’ myth!</p>
<h3 id="switch-case">Switching to Switch-Case from If-Else</h3>

<p>While the if-else structure is used to choose between two options, you can also use switch-case to choose one from multiple options. You can compare it to nested if-else blocks (as in the first approach) or a series of if blocks (as in the second approach). </p>
<p>The benefit of the switch-case structure is that it is more efficient because it can find the matching success criteria in one go. </p>
<p>Note that there is one quirky thing with switch-case. When using switch-case, once a case is matched, all subsequent cases will also execute unless you are using break statements. So, the following program will not be correct even if it looks very similar to our previous version of the code.</p>
<p><strong>Incorrect code: to show problems with missing break statements </strong></p>
<p>```js example-bad
function isLeapYear(year) {
  let isLeap = false;
  switch (true) {
    case year % 4 == 0:
      isLeap = true;
    case year % 100 == 0:
      isLeap = false;
    case year % 400 == 0:
      isLeap = true;
  }
  return isLeap;
}</p>
<pre><code>
If we must use a <span class="hljs-keyword">switch</span>-<span class="hljs-keyword">case</span> structure, we need to use <span class="hljs-keyword">break</span> statements. We also need to go <span class="hljs-keyword">from</span> specific cases first to generic cases next. While not all <span class="hljs-keyword">if</span>-<span class="hljs-keyword">else</span> logic can be converted into a <span class="hljs-keyword">switch</span>-<span class="hljs-keyword">case</span> logic, we can successfully convert the previous <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">like</span> <span class="hljs-title">so</span>:

```<span class="hljs-title">js</span>
<span class="hljs-title">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
  <span class="hljs-keyword">let</span> isLeap = <span class="hljs-literal">false</span>;
  <span class="hljs-keyword">switch</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">case</span> year % <span class="hljs-number">400</span> == <span class="hljs-number">0</span>:
      isLeap = <span class="hljs-literal">true</span>;
      <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> year % <span class="hljs-number">100</span> == <span class="hljs-number">0</span>:
      isLeap = <span class="hljs-literal">false</span>;
      <span class="hljs-keyword">break</span>;
    <span class="hljs-keyword">case</span> year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span>:
      isLeap = <span class="hljs-literal">true</span>;
      <span class="hljs-keyword">break</span>;
  }
  <span class="hljs-keyword">return</span> isLeap;
}

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2024</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2023</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">1900</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2000</span>)); <span class="hljs-comment">// Output: true</span>
</code></pre><p>Notice that in the above, we don't have a 'default' case. And this is because we have initialized the isLeap variable with false. Had we just declared the variable without initialization with a value, we could've written a default case which would assign the value false to isLeap.</p>
<p>Also, the above version of switch-case code is slightly longer because we wanted to use one return statement in the end and used assignments until then. But if we refactor it, a shorter and more organized code would be this:   </p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
  <span class="hljs-keyword">switch</span> (<span class="hljs-literal">true</span>) {
    <span class="hljs-keyword">case</span> (year % <span class="hljs-number">400</span> === <span class="hljs-number">0</span>):
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    <span class="hljs-keyword">case</span> (year % <span class="hljs-number">100</span> === <span class="hljs-number">0</span>):
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    <span class="hljs-keyword">case</span> (year % <span class="hljs-number">4</span> === <span class="hljs-number">0</span>):
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2024</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2023</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">1900</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2000</span>)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>Notice that since execution of a return statement in a function automatically ends the function call, the program does not read lines that follow that statement. So, in this example, we don't have to use the break statements necessarily. </p>
<h3 id="logical-deduction">Logical Deduction &amp; Subsets for Better Structure</h3>

<p>Switching back from switch-case to if-else logic, let's do some logical deduction. In our previous if-else logic, we went from generic cases to specific cases. What if we go in reverse order? We consider that a given year will be a leap year unless negated. </p>
<p>So, we start with the narrower cases of centenary years — for them, the rule is simple: to be negated, they need to be divisible by 100 but not by 400 (like years such as 1700, 1800, 1900). </p>
<p>In this process, since we've already accepted years like 2000 (or years divisible by 400) to be a leap year, we won’t test them for divisibility by 4 (because a number divisible by 400 would anyway be divisible by 4 as well). </p>
<p>In the next step, as we consider only the non-centenary years, we would simply negate the cases where the year is not divisible by 4 (years like 2023, 1996, and so on). </p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
  <span class="hljs-keyword">let</span> isLeap = <span class="hljs-literal">true</span>;
  <span class="hljs-keyword">if</span> (year % <span class="hljs-number">100</span> == <span class="hljs-number">0</span> &amp;&amp; year % <span class="hljs-number">400</span> != <span class="hljs-number">0</span>) {
      isLeap = <span class="hljs-literal">false</span>;
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (year % <span class="hljs-number">4</span> != <span class="hljs-number">0</span>) {
      isLeap = <span class="hljs-literal">false</span>;
  }
  <span class="hljs-keyword">return</span> isLeap;
}

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2024</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2023</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">1900</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2000</span>)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>Here you see, we first consider the centenary years and then non-centenary years — so they are mutually exclusive — and that’s why we use ‘else-if’ instead of if in the second conditional check. And in that process, we gain some efficiency over consecutive if blocks.</p>
<p>As this approach is about breaking the possible routes of being a leap year (or for that matter, not being a leap year) into subsets of years, depending upon how we break the possible years into subsets, we can construct the program alternatively as shown below:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
  <span class="hljs-keyword">let</span> isLeap = <span class="hljs-literal">false</span>;
  <span class="hljs-keyword">if</span> (year % <span class="hljs-number">400</span> == <span class="hljs-number">0</span>) {
      isLeap = <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (year % <span class="hljs-number">100</span> != <span class="hljs-number">0</span> &amp;&amp; year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span>) {
      isLeap = <span class="hljs-literal">true</span>;
  }
  <span class="hljs-keyword">return</span> isLeap;
}

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2024</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2023</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">1900</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2000</span>)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>So, in brief, our deduction from the leap year rule is that  years divisible by 400 (like 1600, 2000) are leap years, and out of all the other years they must be divisible by 4 but not divisible by 100 to be a leap year.</p>
<p>In taking this approach, we have combined conditions and that’s why we involved logical operators (&amp;&amp;, the logical AND operator). This has helped us reduce the length of the function. Instead of three conditional blocks, we are currently using two blocks — an if block and then an else (where we further check the condition, and thus we call it else-if rather than just else).</p>
<p>But now that we are just using almost a single ‘if-else’ construct and we are also delving into logical operators, let's unleash more power from the logical operators in the following approach.</p>
<h3 id="combine-conditions">Logical Operators Combining All True Conditions</h3>

<p>This time let's just reorganize the logic from the previous approach (two subsets) to group all positive conditions together and then accept a year as a leap year. If that’s not met, then call it a non-leap year. </p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
    <span class="hljs-keyword">if</span> ((year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span> &amp;&amp; year % <span class="hljs-number">100</span> != <span class="hljs-number">0</span>) || year % <span class="hljs-number">400</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-comment">// Example usage:</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2024</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2023</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">1900</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2000</span>)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>This one looks good because it increases readability by organizing the positive conditions together. The only cost we incur here is that the condition in the if block is longer. </p>
<p>But with logical operators, it looks visually shorter and not complex (at least to programmers habituated to combining logical operators like this).</p>
<p>Dissecting further, since in the previous approach we said we could break the subsets in two different ways, we can have two corresponding two versions for this approach as well. The second one is the following:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
  <span class="hljs-keyword">if</span> ((year % <span class="hljs-number">100</span> == <span class="hljs-number">0</span> &amp;&amp; year % <span class="hljs-number">400</span> != <span class="hljs-number">0</span>) || year % <span class="hljs-number">4</span> != <span class="hljs-number">0</span>) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  }
}

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2024</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2023</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">1900</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2000</span>)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<h3 id="ternary-operator">Applying Nitro with the Ternary Operator</h3>

<p>As you progress in your programming-learning journey, at some point or other, you must have been elated to discover the possibility of writing ultra-short programs. </p>
<p>While logical operators help us do that, to activate the ‘Nitro’ mode, we must use a Ternary Operator — which basically makes our if-else blocks a single line.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
  <span class="hljs-keyword">return</span> ((year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span> &amp;&amp; year % <span class="hljs-number">100</span> != <span class="hljs-number">0</span>) || year % <span class="hljs-number">400</span> == <span class="hljs-number">0</span>) ? <span class="hljs-literal">true</span> : <span class="hljs-literal">false</span>;
}

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2024</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2023</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">1900</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2000</span>)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>By now, as a pro programmer, you must be pitying your rookie self. You think of those times when you used to declare and initialize a variable with a default value first and then reassign it with the value you wanted to return, and finally return the value held by that variable. </p>
<p>It has been a long time since you shunned that practice, and you now return what you need to return, and don’t consume unnecessary memory space for useless variables.</p>
<h3 id="arrow-function">Making it a Single Line Arrow Function</h3>

<p>Now that you have been boosted with Nitro, your programming technique is advancing like an arrow, on a mission to tear away the remnants of ES5 and boldly fly into the post-ES6 world. So you welcome arrow functions with open arms.  </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> isLeapYear = <span class="hljs-function"><span class="hljs-params">year</span> =&gt;</span> (year % <span class="hljs-number">4</span> === <span class="hljs-number">0</span> &amp;&amp; (year % <span class="hljs-number">100</span> !== <span class="hljs-number">0</span> || year % <span class="hljs-number">400</span> === <span class="hljs-number">0</span>));

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2024</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2023</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">1900</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2000</span>)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>Previously, you skipped variables, and you skipped ‘if-else’ blocks. And now, you can even skip the return statement thanks to the arrow function having a single statement in its body. You also skip the parentheses around your argument as it is a single argument.</p>
<p>While singing the saga of shorter code, a point must be made that the shorter code is not necessarily the better code. It all depends on your users of the code (people who might read it and possibly collaborate/improve upon it). </p>
<p>If you are working with experienced programmers, this level of concision is fine. Just make sure you don’t exceed the line width beyond a certain number of spaces (80 characters recommended) so you don't trouble your coworkers with the need to handle horizontal scrollbars. </p>
<p>But if you are working with team members with varying levels of experience, or you are a teacher working with learners, then you must be conscious of the readability of your code for everyone.</p>
<h2 id="programming-paradigm">Paradigm Shift: Declarative Programming</h2>

<p>Anyway, we have discussed the logic of determining the leap year in the above examples. But let’s now dissect further to find more nuances of programming. And in that process let's move from imperative programming (as we have used so far) towards declarative programming (which is the end goal in this section).</p>
<h3 id="side-effects">Functions with Side Effects</h3>

<p>Functions are said to have side effects when they modify non-local variables. In addition, a function that prints (logs) in the console is also considered a function with some side effects. That is because if a function does not have a side effect, a call to it can be replaced by its return value. </p>
<p>Functional Programming is a paradigm which dictates that our program should be like a pure function without side effects. A pure function means a function which always returns the same output given the same input. So, in its body, it depends on only the input parameter given from outside and no other global variable. Additionally, it should just return the output value without side effects or trying to modify anything outside its scope.</p>
<p>But consider the following variation of the program which does not specifically return any value representing the result. Instead, it logs the result as a statement (string) in the console. This is an example of a side effect. </p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
  <span class="hljs-keyword">if</span> ((year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span> &amp;&amp; year % <span class="hljs-number">100</span> != <span class="hljs-number">0</span>) || year % <span class="hljs-number">400</span> == <span class="hljs-number">0</span>) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"leap year."</span>);
  } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"not leap year."</span>);
  }
}

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-keyword">let</span> someValue = isLeapYear(<span class="hljs-number">2024</span>); <span class="hljs-comment">// Output: leap year.</span>
<span class="hljs-built_in">console</span>.log(someValue); <span class="hljs-comment">// Output: undefined</span>
</code></pre>
<p>Evidently, it does not follow the specification, as it needs to return a value of boolean type. A function can, of course, do both — printing and returning, like an alternative form of the above function. </p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
  <span class="hljs-keyword">if</span> ((year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span> &amp;&amp; year % <span class="hljs-number">100</span> != <span class="hljs-number">0</span>) || year % <span class="hljs-number">400</span> == <span class="hljs-number">0</span>) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"leap year."</span>);
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"not leap year."</span>);
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-keyword">let</span> someValue = isLeapYear(<span class="hljs-number">2024</span>); <span class="hljs-comment">// Output: leap year.</span>
<span class="hljs-built_in">console</span>.log(someValue); <span class="hljs-comment">// Output: true</span>
</code></pre>
<p>But the mere fact that it is doing two things — returning a value and printing in the console —  is the problem. A function should be made to do one thing for proper reusability. The ‘isLeapYear’ function should just determine if a year is a leap year. If we need to print anything about it, let that onus of doing the side effects lie with some other logger function(s).</p>
<pre><code class="lang-js"><span class="hljs-comment">// pure function</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
    <span class="hljs-keyword">if</span> ((year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span> &amp;&amp; year % <span class="hljs-number">100</span> != <span class="hljs-number">0</span>) || year % <span class="hljs-number">400</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-comment">// functions with side effect</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">simpleLeapYearLogger</span>(<span class="hljs-params">isLeap</span>) </span>{
    <span class="hljs-keyword">if</span> (isLeap) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Yes, a leap year!"</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Sorry, not a leap year."</span>);
    }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">advancedLeapYearLogger</span>(<span class="hljs-params">year, isLeap</span>) </span>{
    <span class="hljs-keyword">if</span> (isLeap) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The year <span class="hljs-subst">${year}</span> is a leap year!`</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The year <span class="hljs-subst">${year}</span> is not a leap year!`</span>);
    }
}

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-keyword">let</span> currYear = <span class="hljs-number">2024</span>;
<span class="hljs-keyword">let</span> check2024 = isLeapYear(currYear); <span class="hljs-comment">// No Output/Side Effect, just retuned value.</span>
simpleLeapYearLogger(check2024); <span class="hljs-comment">// Output: Yes, a leap year!</span>
advancedLeapYearLogger(currYear, check2024); <span class="hljs-comment">// Output: The year 2024 is a leap year!</span>
</code></pre>
<p>As you can see above, the function ‘isLeapYear’ is more reusable — with two different use cases in two separate logger functions. Also, had there been any mistake in the logic for the ‘isLeapYear’ function, it would have been easier to fix without touching the logger functions’ code. </p>
<p>Similarly, if you need to display the string logged in the console differently, you could modify the respective logger function without touching the leap year’s logic function. Thus, a function doing just one thing that it was supposed to do increases the reusability and maintainability of that function.</p>
<h3 id="functional-programming">More About Functional Programming</h3>

<p>In the above section, you have already ventured into the space of functional programming. And now is the time to delve deeper. </p>
<p>If I search the term ‘Functional Programming’ in Wikipedia, the first line states</p>
<blockquote>
<p>“functional programming is a programming paradigm where programs are constructed by applying and <a target="_blank" href="https://en.wikipedia.org/wiki/Function_composition_%28computer_science%29">composing</a> <a target="_blank" href="https://en.wikipedia.org/wiki/Function_%28computer_science%29">functions</a>.”</p>
</blockquote>
<p>The phrase ‘composing function’ means building complex functions from simple ones. In our example, the leap year function is quite simple already. But to showcase the mechanism of function composition, let's create it out of component functions.</p>
<pre><code class="lang-js"><span class="hljs-comment">// component function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">divisible</span>(<span class="hljs-params">dividend, divisor</span>) </span>{
    <span class="hljs-keyword">return</span> dividend % divisor == <span class="hljs-number">0</span>
}

<span class="hljs-comment">// composed function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
    <span class="hljs-keyword">let</span> isLeap = <span class="hljs-literal">false</span>;
    divisible(year, <span class="hljs-number">4</span>) &amp;&amp; (isLeap = <span class="hljs-literal">true</span>);
    divisible(year, <span class="hljs-number">100</span>) &amp;&amp; (isLeap = <span class="hljs-literal">false</span>);
    divisible(year, <span class="hljs-number">400</span>) &amp;&amp; (isLeap = <span class="hljs-literal">true</span>);
    <span class="hljs-keyword">return</span> isLeap;
}

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2024</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2023</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">1900</span>)); <span class="hljs-comment">// Output: false</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2000</span>)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<h3 id="short-circuiting">Side-Tracking: Short-Circuiting!</h3>

<p>Above, you are using a function to build another function — a component-based approach that you also follow in the React JavaScript-based front-end library.</p>
<p>But wait, before we go further into React, what is that ‘&amp;&amp;’ doing in those three lines in the 'isLeapYear' function when we are not using any if-else statements there? </p>
<p>Welcome to the short-circuit evaluation of logical operators. In that process, an expression stops being evaluated as soon as its outcome is determined. So if two sides contain a logical AND (&amp;&amp;) in between, if the first side is false, this makes the whole expression false – so it does not read (not execute) the second side. </p>
<p>But if the first side is evaluated to be true, it further reads (executes) the second side for evaluation. And in that process, it does that assignment on the right-hand side of &amp;&amp; in our example.</p>
<p>Similarly, the process when logical OR (||) is involved is such that if the left-hand side is evaluated as true, the whole expression is true (it needs one condition evaluated as true for || for the whole expression to be true). Then, the second side is ignored. The second side is read or executed only when the first side is evaluated as false.</p>
<p>You can use this kind of evaluation logic as a replacement for the ‘if’ condition checks. For more examples of how it works in different scenarios, read the section ‘Short-Circuiting of Logical Operators (&amp;&amp; and ||)’ in my blog post where I have discussed <a target="_blank" href="https://codenil.medium.com/javascript-operators-some-nuances-57300eb2c354">some nuances of JavaScript Operators</a>.</p>
<h3 id="declarative-programming">Encapsulation and Declarative Programming</h3>

<p>Returning to REACT and components, the idea of building composing functions or components is rooted in the need for encapsulation. With encapsulation, you can hide the complex details, like in a capsule, and use it repeatedly without bothering much about its underlying complexity. </p>
<p>Essentially, you just proclaim (declare) what you need rather than straining yourself with the workload and headache of how you can make it happen step-by-step with ‘do-this’ and ‘do-that’ type statements (imperatives). </p>
<p>That, briefly, is declarative programming for you.</p>
<h2 id="code-quality">Going Above &amp; Beyond with Code Quality </h2>

<p>So far, we have covered the logical structures and the programming paradigms, but now, let’s look at the third aspect: code quality.</p>
<h3 id="validations">Validations: Beyond the Basic Specifications</h3>

<p>The requirements that we laid out at first just considered valid inputs. What if the function is called with arguments that are not the ideal ones — like a non-number, or even if a number but a non-integer? </p>
<p>To address that, we can build validation logic. To build validation logic, you need to think about all the different ways in which the input value (the argument passed to your function) may not be workable for you. </p>
<p>If one of those non-workable ways does come along, you need to return something that makes more sense — you can not give a verdict like true or false in that case. You may return something more neutral (like undefined or null) to indicate that the function encountered an invalid entry.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> year!=<span class="hljs-string">"number"</span> || year % <span class="hljs-number">1</span> != <span class="hljs-number">0</span> || year &lt;= <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-literal">undefined</span>;
  <span class="hljs-keyword">return</span> ((year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span> &amp;&amp; year % <span class="hljs-number">100</span> != <span class="hljs-number">0</span>) || year % <span class="hljs-number">400</span> == <span class="hljs-number">0</span>) ? <span class="hljs-literal">true</span> : <span class="hljs-literal">false</span>;
}

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2024</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-string">"TwentyTwentyFour"</span>)); <span class="hljs-comment">// Output: undefined</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2023.99</span>)); <span class="hljs-comment">// Output: undefined</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">0</span>)); <span class="hljs-comment">// Output: undefined</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">-1</span>)); <span class="hljs-comment">// Output: undefined</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-string">"2024"</span>)); <span class="hljs-comment">// Output: undefined</span>
</code></pre>
<p>But if you noticed carefully, in our leap year logic check, we have evaluated just ordinary equality (==) instead of strict equality (===). We can't reap the benefit of that for a string format entry for a year like "2024". </p>
<p>If our intention is to strictly accept a number, the kind of validation we wrote is fine, and it would then be even more proper to use ===. </p>
<p>But if, on the other hand, we want to accept values like "2024", we must enhance our validation logic like so:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">isNaN</span>(<span class="hljs-built_in">Number</span>(year)) || year % <span class="hljs-number">1</span> != <span class="hljs-number">0</span> || year &lt;= <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-literal">undefined</span>;
  <span class="hljs-keyword">return</span> ((year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span> &amp;&amp; year % <span class="hljs-number">100</span> != <span class="hljs-number">0</span>) || year % <span class="hljs-number">400</span> == <span class="hljs-number">0</span>) ? <span class="hljs-literal">true</span> : <span class="hljs-literal">false</span>;
}

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2024</span>)); <span class="hljs-comment">// Output: true</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-string">"TwentyTwentyFour"</span>)); <span class="hljs-comment">// Output: undefined</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">2023.99</span>)); <span class="hljs-comment">// Output: undefined</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">0</span>)); <span class="hljs-comment">// Output: undefined</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-number">-1</span>)); <span class="hljs-comment">// Output: undefined</span>
<span class="hljs-built_in">console</span>.log(isLeapYear(<span class="hljs-string">"2024"</span>)); <span class="hljs-comment">// Output: true</span>
</code></pre>
<h3 id="unit-testing">Testing it Out From the Outside</h3>

<p>In the above two code blocks, we write our code and test it in the same place. But the code that goes into production will not have the opportunity to include such console logs that we have used extensively for demonstrating 'example usage' in the above code blocks. </p>
<p>This is where unit testing comes in. In unit testing, we first export the function for use in other places (files), then import that function in a test file. In that test file is where we run the test, build our cases, and finally run that test file to execute those tests.</p>
<p>I have used the Jest package to do this unit testing, and here is the code from my index file and test script file:</p>
<p><strong>index.js</strong></p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLeapYear</span>(<span class="hljs-params">year</span>) </span>{
  <span class="hljs-keyword">if</span> (<span class="hljs-built_in">isNaN</span>(<span class="hljs-built_in">Number</span>(year)) || year % <span class="hljs-number">1</span> != <span class="hljs-number">0</span> || year &lt;= <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-literal">undefined</span>;
  <span class="hljs-keyword">return</span> ((year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span> &amp;&amp; year % <span class="hljs-number">100</span> != <span class="hljs-number">0</span>) || year % <span class="hljs-number">400</span> == <span class="hljs-number">0</span>) ? <span class="hljs-literal">true</span> : <span class="hljs-literal">false</span>;
}

<span class="hljs-built_in">module</span>.exports = isLeapYear;
</code></pre>
<p><strong>index.test.js</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> isLeapYear = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./index.js'</span>);

describe(<span class="hljs-string">'Test isLeapYear'</span>, <span class="hljs-function">() =&gt;</span> {
  it(<span class="hljs-string">'should return true for leap year'</span>, <span class="hljs-function">() =&gt;</span> {
    expect(isLeapYear(<span class="hljs-number">2020</span>)).toBe(<span class="hljs-literal">true</span>);
  });
  it(<span class="hljs-string">'should return false for non-leap year'</span>, <span class="hljs-function">() =&gt;</span> {
    expect(isLeapYear(<span class="hljs-number">2023</span>)).toBe(<span class="hljs-literal">false</span>);
  });
  it(<span class="hljs-string">'should return undefined for invalid input'</span>, <span class="hljs-function">() =&gt;</span> {
    expect(isLeapYear(<span class="hljs-string">'TwentyTwentyFour'</span>)).toBe(<span class="hljs-literal">undefined</span>);
    expect(isLeapYear(<span class="hljs-string">'2023.99'</span>)).toBe(<span class="hljs-literal">undefined</span>);
    expect(isLeapYear(<span class="hljs-string">'0'</span>)).toBe(<span class="hljs-literal">undefined</span>);
    expect(isLeapYear(<span class="hljs-string">'-1'</span>)).toBe(<span class="hljs-literal">undefined</span>);
  });
  it(<span class="hljs-string">'should return true for a leap year in string format'</span>, <span class="hljs-function">() =&gt;</span> {
    expect(isLeapYear(<span class="hljs-string">"2024"</span>)).toBe(<span class="hljs-literal">true</span>);
  });
});
</code></pre>
<p>I installed Jest using the command <code>npm i jest</code>. Then, I added <code>jest</code> as a value for <code>test</code> in the <code>scripts</code> object inside my package.json file. Then, as I ran <code>npm test</code>, it passed all my test cases, like so:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/Screenshot-2024-02-29-05.25.03.png" alt="Image" width="600" height="400" loading="lazy">
<em>testing output</em></p>
<p>If you want to tweak and try this unit testing code, you can use and fork this <a target="_blank" href="https://replit.com/@nil-sj/UnitTestingExample">replit project</a>.</p>
<h2 id="end-note">End Note</h2>

<p>We've reviewed many programming concepts in the above exercise. And one key takeaway is that a program can be written in multiple ways. </p>
<p>There are typically many correct solutions to a programming problem. So beginner programmers should, therefore, think of the logic part of it (the algorithm) more than the exact execution steps when starting to solve a problem.</p>
<p>And by the way, if you're wondering why we have leap years, then this is for you: the time Earth takes to complete one revolution around the sun is not exactly 365 days (or 365 x 24 hours) but approximately one-quarter of a day extra. </p>
<p>This process may remind you of the modulus operator, represented by the symbol %, which returns the remainder of a division operation. Here, the approximate time (in hours) taken for one revolution of earth is being divided by 24 hours (that is, a day). It gives a remainder of about 6 hours. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> approxTimeHrsRev = <span class="hljs-number">8766</span>;
<span class="hljs-keyword">const</span> hrsPerDay = <span class="hljs-number">24</span>;
<span class="hljs-keyword">let</span> completedDaysEachYear;

<span class="hljs-keyword">let</span> remainderHrsPerYear = <span class="hljs-number">8766</span> % hrsPerDay;
completedDaysEachYear = (approxTimeHrsRev - remainderHrsPerYear) / hrsPerDay;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`After <span class="hljs-subst">${completedDaysEachYear}</span> complete days, there is still about <span class="hljs-subst">${remainderHrsPerYear}</span> hours left out each year.`</span>);
<span class="hljs-comment">// Output: After 365 complete days, there is still about 6 hours left out each year.</span>
</code></pre>
<p>To account for those missed hours, we must adjust our calendars once every four years when those left-out portions add up to make — again approximately — a day. </p>
<p>Finally, because it is not exactly 6 hours, and a tiny bit more than that, we have to adjust every 100 and 400 years further.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
