<?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[ js - 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[ js - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 23 Aug 2026 21:54:28 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/js/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use the "this" Keyword in JavaScript: A Handbook for Devs ]]>
                </title>
                <description>
                    <![CDATA[ The this keyword in JavaScript is like a chameleon – it changes its meaning depending on where and how it's used. Many developers struggle with this because it doesn't behave the same way in JavaScript as it does in other programming languages. Think... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-the-this-keyword-in-javascript-a-handbook-for-devs/</link>
                <guid isPermaLink="false">686fc4a0fb8e16a8295fc149</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ this keyword ]]>
                    </category>
                
                    <category>
                        <![CDATA[ this keyword in javascript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ this in js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Henry Adepegba ]]>
                </dc:creator>
                <pubDate>Thu, 10 Jul 2025 13:48:16 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1752155267760/5e5fc562-e515-4843-ad64-32129c293d67.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The <code>this</code> keyword in JavaScript is like a chameleon – it changes its meaning depending on where and how it's used.</p>
<p>Many developers struggle with <code>this</code> because it doesn't behave the same way in JavaScript as it does in other programming languages. Think of <code>this</code> as a spotlight that points to different objects depending on the context – much like how the word "here" means different locations depending on where you're standing when you say it.</p>
<p>In this handbook, you will learn why <code>this</code> keyword is important in JavaScript and how to work with it effectively.</p>
<p><strong>Before diving into this guide, you should have:</strong></p>
<ul>
<li><p><strong>Basic JavaScript knowledge</strong>: Understanding of variables, functions, and objects</p>
</li>
<li><p><strong>Familiarity with ES6 syntax</strong>: Arrow functions, classes, and template literals</p>
</li>
<li><p><strong>Basic DOM knowledge</strong>: How to select elements and add event listeners</p>
</li>
<li><p><strong>Understanding of scope</strong>: How variables are accessed in different contexts</p>
</li>
<li><p><strong>Object basics</strong>: Creating objects, and accessing properties with dot notation.</p>
</li>
</ul>
<p>If you're comfortable with these concepts, you're ready to master the <code>this</code> keyword!</p>
<h3 id="heading-what-well-cover">What we’ll cover:</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-why-is-this-important">Why is "this" Important?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-four-main-rules-of-this">The Four Main Rules of "this"</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-explicit-binding-call-apply-bind">1. Explicit Binding (call, apply, bind)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-implicit-binding-method-calls">2. Implicit Binding (method calls)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-new-binding-constructor-functions">3. New Binding (constructor functions)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-default-binding-global-object-or-undefined">4. Default Binding (global object or undefined)</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-rule-1-explicit-binding-taking-control">Rule 1: Explicit Binding - Taking Control</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-using-call">Using call()</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-using-apply">Using apply()</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-using-bind">Using bind()</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-partial-application-with-bind">Partial Application with bind()</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-rule-2-implicit-binding-the-natural-way">Rule 2: Implicit Binding - The Natural Way</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-nested-objects">Nested Objects</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-lost-context-problem">The Lost Context Problem</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-rule-3-new-binding-constructor-functions">Rule 3: New Binding - Constructor Functions</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-happens-with-new">What happens with 'new'?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-constructor-function-best-practices">Constructor Function Best Practices</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-rule-4-default-binding-the-fallback">Rule 4: Default Binding - The Fallback</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-global-variables-and-this">Global Variables and 'this'</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-arrow-functions-the-game-changer">Arrow Functions - The Game Changer</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-arrow-functions-in-different-contexts">Arrow Functions in Different Contexts</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-class-context-and-this">Class Context and 'this'</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-common-pitfalls-and-solutions">Common Pitfalls and Solutions</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-event-handlers">1. Event Handlers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-callback-functions">2. Callback Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-asyncawait-and-promises">3. Async/Await and Promises</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-this-practical-guidelines">When to Use 'this' - Practical Guidelines</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-object-oriented-programming">1. Object-Oriented Programming</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-event-handling">2. Event Handling</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-method-chaining">3. Method Chaining</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-pluginlibrary-development">4. Plugin/Library Development</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-when-not-to-use-this">When NOT to Use 'this'</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-utility-functions">1. Utility Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-functional-programming">2. Functional Programming</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-simple-event-handlers">3. Simple Event Handlers</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-best-practices-and-tips">Best Practices and Tips</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-always-be-explicit">1. Always Be Explicit</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-use-arrow-functions-for-callbacks">2. Use Arrow Functions for Callbacks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-avoid-mixing-arrow-functions-and-regular-functions">3. Avoid Mixing Arrow Functions and Regular Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-use-strict-mode">4. Use Strict Mode</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-modern-javascript-and-this">Modern JavaScript and 'this'</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-react-components">1. React Components</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-nodejs-and-this">2. Node.js and 'this'</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-why-is-this-important">Why is "this" Important?</h2>
<p>In JavaScript, <code>this</code> is a special keyword that refers to the object that is currently executing the code. It's a reference to the "owner" of the function that's being called. The value of <code>this</code> is determined by <strong>how a function is called</strong>, not where it's defined.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Think of 'this' as asking "Who is doing this action?"</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">introduce</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-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-comment">// The answer depends on who calls the function</span>
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>function introduce()</code> – This creates a function called <code>introduce</code></p>
</li>
<li><p><a target="_blank" href="http://this.name"><code>this.name</code></a> – The <code>this</code> keyword here will refer to whatever object calls this function</p>
</li>
<li><p><code>${</code><a target="_blank" href="http://this.name"><code>this.name</code></a><code>}</code> – This is template literal syntax that inserts the value of <code>this.name</code> into the string</p>
</li>
<li><p>The function doesn't know what <code>this</code> refers to until it is actually called</p>
</li>
</ul>
<p>Understanding <code>this</code> is crucial for JavaScript development for a few key reasons:</p>
<ol>
<li><p><strong>Object-Oriented Programming</strong>: <code>this</code> enables you to create reusable methods that can work with different objects</p>
</li>
<li><p><strong>Dynamic context</strong>: It allows functions to adapt their behavior based on the calling context</p>
</li>
<li><p><strong>Event handling</strong>: Essential for handling DOM events and user interactions</p>
</li>
<li><p><strong>Understanding frameworks</strong>: Critical for working with React, Vue, Angular, and other frameworks</p>
</li>
<li><p><strong>Code reusability</strong>: Enables writing flexible functions that can be used across different objects</p>
</li>
<li><p><strong>Professional development</strong>: Mastering <code>this</code> distinguishes intermediate developers from beginners</p>
</li>
</ol>
<h2 id="heading-the-four-main-rules-of-this">The Four Main Rules of "this"</h2>
<p>JavaScript determines the value of <code>this</code> using four main rules, applied in order of priority:</p>
<ol>
<li><p>Explicit Binding (call, apply, bind)</p>
</li>
<li><p>Implicit Binding (method calls)</p>
</li>
<li><p>New Binding (constructor functions)</p>
</li>
<li><p>Default Binding (global object or undefined)</p>
</li>
</ol>
<p>Let's explore each rule with detailed examples.</p>
<h2 id="heading-rule-1-explicit-binding-taking-control">Rule 1: Explicit Binding – Taking Control</h2>
<p>Explicit binding is when you explicitly tell JavaScript what <code>this</code> should refer to using <code>call()</code>, <code>apply()</code>, or <code>bind()</code>. This is like directly pointing at someone and saying "YOU do this task."</p>
<h3 id="heading-using-call">Using call()</h3>
<p>The <code>call()</code> method allows you to invoke a function with a specific <code>this</code> value and arguments provided individually.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person1 = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Alice"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>
};

<span class="hljs-keyword">const</span> person2 = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Bob"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">greeting, punctuation</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${greeting}</span>, I'm <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> and I'm <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old<span class="hljs-subst">${punctuation}</span>`</span>);
}

<span class="hljs-comment">// Using call() to explicitly set 'this' to person1</span>
greet.call(person1, <span class="hljs-string">"Hello"</span>, <span class="hljs-string">"!"</span>); 
<span class="hljs-comment">// Output: "Hello, I'm Alice and I'm 30 years old!"</span>

<span class="hljs-comment">// Using call() to explicitly set 'this' to person2</span>
greet.call(person2, <span class="hljs-string">"Hi"</span>, <span class="hljs-string">"."</span>);
<span class="hljs-comment">// Output: "Hi, I'm Bob and I'm 25 years old."</span>
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>const person1 = { name: "Alice", age: 30 };</code> – Creates an object with <code>name</code> and <code>age</code> properties</p>
</li>
<li><p><code>const person2 = { name: "Bob", age: 25 };</code> – Creates another object with different values</p>
</li>
<li><p><code>function greet(greeting, punctuation)</code> – Defines a function that takes two parameters</p>
</li>
<li><p><code>this.name</code> and <code>this.age</code> – These refer to properties of whatever object <code>this</code> points to</p>
</li>
<li><p><code>greet.call(person1, "Hello", "!")</code> – The <code>call()</code> method does three things:</p>
<ol>
<li><p>Sets <code>this</code> inside the <code>greet</code> function to point to <code>person1</code></p>
</li>
<li><p>Passes <code>"Hello"</code> as the first argument (<code>greeting</code>)</p>
</li>
<li><p>Passes <code>"!"</code> as the second argument (<code>punctuation</code>)</p>
</li>
</ol>
</li>
<li><p>When the function runs, <code>this.name</code> becomes <code>person1.name</code> ("Alice") and <code>this.age</code> becomes <code>person1.age</code> (30)</p>
</li>
<li><p><code>greet.call(person2, "Hi", ".")</code> – Same process but now <code>this</code> points to <code>person2</code></p>
</li>
</ul>
<h3 id="heading-using-apply">Using apply()</h3>
<p>The <code>apply()</code> method is similar to <code>call()</code>, but arguments are passed as an array instead of individually.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> student = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Sarah"</span>,
    <span class="hljs-attr">grades</span>: [<span class="hljs-number">85</span>, <span class="hljs-number">92</span>, <span class="hljs-number">78</span>, <span class="hljs-number">96</span>]
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateAverage</span>(<span class="hljs-params">subject, semester</span>) </span>{
    <span class="hljs-keyword">const</span> average = <span class="hljs-built_in">this</span>.grades.reduce(<span class="hljs-function">(<span class="hljs-params">sum, grade</span>) =&gt;</span> sum + grade, <span class="hljs-number">0</span>) / <span class="hljs-built_in">this</span>.grades.length;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>'s average in <span class="hljs-subst">${subject}</span> for <span class="hljs-subst">${semester}</span> is <span class="hljs-subst">${average.toFixed(<span class="hljs-number">1</span>)}</span>`</span>);
    <span class="hljs-keyword">return</span> average;
}

<span class="hljs-comment">// Using apply() with arguments as an array</span>
calculateAverage.apply(student, [<span class="hljs-string">"Mathematics"</span>, <span class="hljs-string">"Fall 2024"</span>]);
<span class="hljs-comment">// Output: "Sarah's average in Mathematics for Fall 2024 is 87.8"</span>

<span class="hljs-comment">// Equivalent using call()</span>
calculateAverage.call(student, <span class="hljs-string">"Mathematics"</span>, <span class="hljs-string">"Fall 2024"</span>);
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>const student = { name: "Sarah", grades: [85, 92, 78, 96] };</code> – Creates an object with a <code>name</code> string and <code>grades</code> array</p>
</li>
<li><p><code>function calculateAverage(subject, semester)</code> – Function that calculates average of grades</p>
</li>
<li><p><code>this.grades.reduce((sum, grade) =&gt; sum + grade, 0)</code> – Uses the <code>reduce</code> method to sum all grades:</p>
<ul>
<li><p><code>(sum, grade) =&gt; sum + grade</code> – Arrow function that adds current grade to running sum</p>
</li>
<li><p><code>0</code> – Starting value for the sum</p>
</li>
</ul>
</li>
<li><p><code>this.grades.length</code> – Gets the number of grades in the array</p>
</li>
<li><p><code>average.toFixed(1)</code> – Rounds the average to 1 decimal place</p>
</li>
<li><p><code>calculateAverage.apply(student, ["Mathematics", "Fall 2024"])</code> – The <code>apply()</code> method:</p>
<ol>
<li><p>Sets <code>this</code> to point to the <code>student</code> object</p>
</li>
<li><p>Takes the array <code>["Mathematics", "Fall 2024"]</code> and spreads it as individual arguments</p>
</li>
<li><p>So <code>subject</code> becomes <code>"Mathematics"</code> and <code>semester</code> becomes <code>"Fall 2024"</code></p>
</li>
</ol>
</li>
<li><p>When function runs, <code>this.grades</code> refers to <code>student.grades</code> and <code>this.name</code> refers to <code>student.name</code></p>
</li>
</ul>
<h3 id="heading-using-bind">Using bind()</h3>
<p>The <code>bind()</code> method creates a new function with a permanently bound <code>this</code> value. It's like creating a customized version of a function that always knows who it belongs to.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> car = {
    <span class="hljs-attr">brand</span>: <span class="hljs-string">"Tesla"</span>,
    <span class="hljs-attr">model</span>: <span class="hljs-string">"Model 3"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2023</span>
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayInfo</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`This is a <span class="hljs-subst">${<span class="hljs-built_in">this</span>.year}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.brand}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.model}</span>`</span>);
}

<span class="hljs-comment">// Create a bound function</span>
<span class="hljs-keyword">const</span> showCarInfo = displayInfo.bind(car);

<span class="hljs-comment">// Now showCarInfo will always use 'car' as 'this'</span>
showCarInfo(); <span class="hljs-comment">// Output: "This is a 2023 Tesla Model 3"</span>

<span class="hljs-comment">// Even if we try to call it differently, 'this' remains bound to 'car'</span>
<span class="hljs-keyword">const</span> anotherCar = { <span class="hljs-attr">brand</span>: <span class="hljs-string">"BMW"</span>, <span class="hljs-attr">model</span>: <span class="hljs-string">"X3"</span>, <span class="hljs-attr">year</span>: <span class="hljs-number">2022</span> };
showCarInfo.call(anotherCar); <span class="hljs-comment">// Still outputs: "This is a 2023 Tesla Model 3"</span>
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>const car = { brand: "Tesla", model: "Model 3", year: 2023 };</code> – Creates a car object with three properties</p>
</li>
<li><p><code>function displayInfo()</code> – A function that uses <code>this.year</code>, <code>this.brand</code>, and <code>this.model</code></p>
</li>
<li><p><code>const showCarInfo = displayInfo.bind(car);</code> – The <code>bind()</code> method:</p>
<ol>
<li><p>Creates a new function based on <code>displayInfo</code></p>
</li>
<li><p>Permanently sets <code>this</code> to point to the <code>car</code> object</p>
</li>
<li><p>Returns this new function and stores it in <code>showCarInfo</code></p>
</li>
</ol>
</li>
<li><p><code>showCarInfo()</code> – When called, this function will always use <code>car</code> as <code>this</code>, regardless of how it's called</p>
</li>
<li><p><code>const anotherCar = { brand: "BMW", model: "X3", year: 2022 };</code> – Creates another car object</p>
</li>
<li><p><code>showCarInfo.call(anotherCar)</code> – Even though we try to use <code>call()</code> to change <code>this</code>, it doesn't work because <code>bind()</code> creates a permanent binding</p>
</li>
</ul>
<h3 id="heading-partial-application-with-bind">Partial Application with bind()</h3>
<p><code>bind()</code> can also be used for partial application, pre-setting some arguments:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">a, b, c</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> calculated: <span class="hljs-subst">${a}</span> × <span class="hljs-subst">${b}</span> × <span class="hljs-subst">${c}</span> = <span class="hljs-subst">${a * b * c}</span>`</span>);
    <span class="hljs-keyword">return</span> a * b * c;
}

<span class="hljs-keyword">const</span> calculator = { <span class="hljs-attr">name</span>: <span class="hljs-string">"SuperCalc"</span> };

<span class="hljs-comment">// Bind 'this' and the first argument</span>
<span class="hljs-keyword">const</span> multiplyByTwo = multiply.bind(calculator, <span class="hljs-number">2</span>);

multiplyByTwo(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>); <span class="hljs-comment">// Output: "SuperCalc calculated: 2 × 3 × 4 = 24"</span>
multiplyByTwo(<span class="hljs-number">5</span>, <span class="hljs-number">6</span>); <span class="hljs-comment">// Output: "SuperCalc calculated: 2 × 5 × 6 = 60"</span>
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>function multiply(a, b, c)</code> – Function that takes three numbers and multiplies them</p>
</li>
<li><p><code>${this.name} calculated: ${a} × ${b} × ${c} = ${a * b * c}</code> – Template literal that shows the calculation</p>
</li>
<li><p><code>const calculator = { name: "SuperCalc" };</code> – Object with a <code>name</code> property</p>
</li>
<li><p><code>const multiplyByTwo = multiply.bind(calculator, 2);</code> – The <code>bind()</code> method here:</p>
<ol>
<li><p>Sets <code>this</code> to point to <code>calculator</code></p>
</li>
<li><p>Sets the first argument (<code>a</code>) to always be <code>2</code></p>
</li>
<li><p>Returns a new function that only needs two more arguments</p>
</li>
</ol>
</li>
<li><p><code>multiplyByTwo(3, 4)</code> – When called:</p>
<ul>
<li><p><code>a</code> is already set to <code>2</code> (from bind)</p>
</li>
<li><p><code>b</code> becomes <code>3</code> (first argument passed)</p>
</li>
<li><p><code>c</code> becomes <code>4</code> (second argument passed)</p>
</li>
<li><p><code>this.name</code> refers to <code>calculator.name</code> ("SuperCalc")</p>
</li>
<li><p>Result: <code>2 × 3 × 4 = 24</code></p>
</li>
</ul>
</li>
</ul>
<h2 id="heading-rule-2-implicit-binding-the-natural-way">Rule 2: Implicit Binding – The Natural Way</h2>
<p>Implicit binding occurs when a function is called as a method of an object. The object to the left of the dot becomes the value of <code>this</code>. This is like saying "the owner of this method is doing the action."</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> restaurant = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Mario's Pizza"</span>,
    <span class="hljs-attr">location</span>: <span class="hljs-string">"New York"</span>,
    <span class="hljs-attr">chef</span>: <span class="hljs-string">"Mario"</span>,

    <span class="hljs-attr">welcomeGuest</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">`Welcome to <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> in <span class="hljs-subst">${<span class="hljs-built_in">this</span>.location}</span>!`</span>);
    },

    <span class="hljs-attr">cookPizza</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">toppings</span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.chef}</span> at <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> is cooking pizza with <span class="hljs-subst">${toppings}</span>`</span>);
    }
};

<span class="hljs-comment">// Implicit binding - 'this' refers to the restaurant object</span>
restaurant.welcomeGuest(); <span class="hljs-comment">// Output: "Welcome to Mario's Pizza in New York!"</span>
restaurant.cookPizza(<span class="hljs-string">"pepperoni and mushrooms"</span>); 
<span class="hljs-comment">// Output: "Mario at Mario's Pizza is cooking pizza with pepperoni and mushrooms"</span>
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>const restaurant = { ... };</code> – Creates an object with four properties: <code>name</code>, <code>location</code>, <code>chef</code>, and two methods</p>
</li>
<li><p><code>welcomeGuest: function() { ... }</code> – A method (function inside an object) that uses <code>this.name</code> and <code>this.location</code></p>
</li>
<li><p><code>cookPizza: function(toppings) { ... }</code> – Another method that takes a <code>toppings</code> parameter</p>
</li>
<li><p><code>restaurant.welcomeGuest()</code> – When called this way:</p>
<ol>
<li><p>JavaScript looks at what's to the left of the dot (<code>restaurant</code>)</p>
</li>
<li><p>Sets <code>this</code> inside <code>welcomeGuest</code> to point to the <code>restaurant</code> object</p>
</li>
<li><p><code>this.name</code> becomes <code>restaurant.name</code> ("Mario's Pizza")</p>
</li>
<li><p><code>this.location</code> becomes <code>restaurant.location</code> ("New York")</p>
</li>
</ol>
</li>
<li><p><code>restaurant.cookPizza("pepperoni and mushrooms")</code> – Similar process:</p>
<ol>
<li><p><code>this</code> points to <code>restaurant</code></p>
</li>
<li><p><code>this.chef</code> becomes <code>restaurant.chef</code> ("Mario")</p>
</li>
<li><p><code>this.name</code> becomes <code>restaurant.name</code> ("Mario's Pizza")</p>
</li>
<li><p><code>toppings</code> parameter receives "pepperoni and mushrooms"</p>
</li>
</ol>
</li>
</ul>
<h3 id="heading-nested-objects">Nested Objects</h3>
<p>When objects are nested, <code>this</code> refers to the immediate parent object:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> company = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"TechCorp"</span>,
    <span class="hljs-attr">departments</span>: {
        <span class="hljs-attr">name</span>: <span class="hljs-string">"Engineering"</span>,
        <span class="hljs-attr">head</span>: <span class="hljs-string">"Jane Smith"</span>,
        <span class="hljs-attr">introduce</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`This is the <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> department, led by <span class="hljs-subst">${<span class="hljs-built_in">this</span>.head}</span>`</span>);
        }
    }
};

<span class="hljs-comment">// 'this' refers to the departments object, not the company object</span>
company.departments.introduce(); 
<span class="hljs-comment">// Output: "This is the Engineering department, led by Jane Smith"</span>
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>const company = { name: "TechCorp", departments: { ... } };</code> – Creates a company object with a nested <code>departments</code> object</p>
</li>
<li><p><code>departments: { name: "Engineering", head: "Jane Smith", introduce: function() { ... } }</code> – The nested object has its own properties and method</p>
</li>
<li><p><code>company.departments.introduce()</code> – When called:</p>
<ol>
<li><p>JavaScript looks at what's immediately to the left of the dot before <code>introduce</code></p>
</li>
<li><p>That's <code>company.departments</code>, so <code>this</code> points to the <code>departments</code> object (not the <code>company</code> object)</p>
</li>
<li><p><code>this.name</code> becomes <code>"Engineering"</code> (from departments.name, not company.name)</p>
</li>
<li><p><code>this.head</code> becomes <code>"Jane Smith"</code> (from departments.head)</p>
</li>
</ol>
</li>
<li><p>The key point: <code>this</code> always refers to the object immediately before the dot, not the entire chain</p>
</li>
</ul>
<h3 id="heading-the-lost-context-problem">The Lost Context Problem</h3>
<p>One of the most common issues developers face with <code>this</code> is <strong>context loss.</strong> This happens when a method is passed as a callback function and loses its original object context. The problem occurs because JavaScript determines <code>this</code> based on <strong>how</strong> a function is called, not <strong>where</strong> it's defined.</p>
<p>When you pass a method as a callback (like to <code>setInterval</code>, <code>setTimeout</code>, or array methods), the function gets called without its original object context. Instead of <code>this</code> referring to your object, it falls back to default binding (undefined in strict mode, or the global object in non-strict mode).</p>
<p>This is why <code>timer.tick</code> works perfectly when called as <code>timer.tick()</code>, but fails when passed as <code>setInterval(this.tick, 1000)</code> – the calling context changes completely.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> timer = {
    <span class="hljs-attr">seconds</span>: <span class="hljs-number">0</span>,

    <span class="hljs-attr">tick</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">this</span>.seconds++;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Timer: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.seconds}</span> seconds`</span>);
    },

    <span class="hljs-attr">start</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-comment">// This will lose context!</span>
        <span class="hljs-built_in">setInterval</span>(<span class="hljs-built_in">this</span>.tick, <span class="hljs-number">1000</span>);
    },

    <span class="hljs-attr">startCorrect</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-comment">// Solution 1: Using bind()</span>
        <span class="hljs-built_in">setInterval</span>(<span class="hljs-built_in">this</span>.tick.bind(<span class="hljs-built_in">this</span>), <span class="hljs-number">1000</span>);

        <span class="hljs-comment">// Solution 2: Using arrow function</span>
        <span class="hljs-comment">// setInterval(() =&gt; this.tick(), 1000);</span>
    }
};

timer.start(); <span class="hljs-comment">// Will log "Timer: NaN seconds" because 'this' is lost</span>
timer.startCorrect(); <span class="hljs-comment">// Will correctly increment and log the timer</span>
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>const timer = { seconds: 0, ... };</code> – Creates a timer object with a <code>seconds</code> property starting at 0</p>
</li>
<li><p><code>tick: function() { this.seconds++; ... }</code> – Method that increments <code>seconds</code> and logs current value</p>
</li>
<li><p><code>start: function() { setInterval(this.tick, 1000); }</code> – <strong>PROBLEMATIC</strong> method:</p>
<ol>
<li><p><code>this.tick</code> refers to the <code>tick</code> method</p>
</li>
<li><p><code>setInterval(this.tick, 1000)</code> passes the <code>tick</code> function to <code>setInterval</code></p>
</li>
<li><p>When <code>setInterval</code> calls <code>tick</code> after 1 second, it calls it as a standalone function (not as <code>timer.tick()</code>)</p>
</li>
<li><p>This means <code>this</code> inside <code>tick</code> becomes <code>undefined</code> (in strict mode) or the global object</p>
</li>
<li><p><code>this.seconds++</code> tries to increment <code>undefined.seconds</code>, resulting in <code>NaN</code></p>
</li>
</ol>
</li>
<li><p><code>startCorrect: function() { setInterval(this.tick.bind(this), 1000); }</code> – <strong>CORRECT</strong> solution:</p>
<ol>
<li><p><code>this.tick.bind(this)</code> creates a new function where <code>this</code> is permanently bound to the <code>timer</code> object</p>
</li>
<li><p>When <code>setInterval</code> calls this bound function, <code>this</code> still refers to <code>timer</code></p>
</li>
<li><p><code>this.seconds++</code> correctly increments <code>timer.seconds</code></p>
</li>
</ol>
</li>
<li><p>Alternative solution <code>setInterval(() =&gt; this.tick(), 1000)</code>:</p>
<ol>
<li><p>The arrow function <code>() =&gt; this.tick()</code> preserves the <code>this</code> from the surrounding context</p>
</li>
<li><p>Inside the arrow function, <code>this</code> still refers to <code>timer</code></p>
</li>
<li><p><code>this.tick()</code> calls the method with proper context</p>
</li>
</ol>
</li>
</ul>
<h2 id="heading-rule-3-new-binding-constructor-functions">Rule 3: New Binding – Constructor Functions</h2>
<p>When a function is called with the <code>new</code> keyword, JavaScript creates a new object and sets <code>this</code> to that new object. This is like creating a new instance of something from a blueprint.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name, age, profession</span>) </span>{
    <span class="hljs-comment">// 'this' refers to the new object being created</span>
    <span class="hljs-built_in">this</span>.name = name;
    <span class="hljs-built_in">this</span>.age = age;
    <span class="hljs-built_in">this</span>.profession = profession;

    <span class="hljs-built_in">this</span>.introduce = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi, I'm <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>, a <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span>-year-old <span class="hljs-subst">${<span class="hljs-built_in">this</span>.profession}</span>`</span>);
    };
}

<span class="hljs-comment">// Creating new instances</span>
<span class="hljs-keyword">const</span> alice = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">28</span>, <span class="hljs-string">"developer"</span>);
<span class="hljs-keyword">const</span> bob = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Bob"</span>, <span class="hljs-number">35</span>, <span class="hljs-string">"designer"</span>);

alice.introduce(); <span class="hljs-comment">// Output: "Hi, I'm Alice, a 28-year-old developer"</span>
bob.introduce(); <span class="hljs-comment">// Output: "Hi, I'm Bob, a 35-year-old designer"</span>

<span class="hljs-built_in">console</span>.log(alice.name); <span class="hljs-comment">// Output: "Alice"</span>
<span class="hljs-built_in">console</span>.log(bob.name); <span class="hljs-comment">// Output: "Bob"</span>
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>function Person(name, age, profession) { ... }</code> – This is a constructor function (note the capital P)</p>
</li>
<li><p><code>this.name = name;</code> – Sets the <code>name</code> property of the new object to the passed <code>name</code> parameter</p>
</li>
<li><p><code>this.age = age;</code> – Sets the <code>age</code> property of the new object to the passed <code>age</code> parameter</p>
</li>
<li><p><code>this.profession = profession;</code> – Sets the <code>profession</code> property of the new object</p>
</li>
<li><p><code>this.introduce = function() { ... }</code> – Adds a method to the new object</p>
</li>
<li><p><code>const alice = new Person("Alice", 28, "developer");</code> – The <code>new</code> keyword:</p>
<ol>
<li><p>Creates a new empty object <code>{}</code></p>
</li>
<li><p>Sets <code>this</code> inside the <code>Person</code> function to point to this new object</p>
</li>
<li><p>Calls <code>Person("Alice", 28, "developer")</code> with the new object as <code>this</code></p>
</li>
<li><p>The function adds properties to this new object</p>
</li>
<li><p>Returns the new object and stores it in <code>alice</code></p>
</li>
</ol>
</li>
<li><p><code>const bob = new Person("Bob", 35, "designer");</code> – Same process, creates a different object</p>
</li>
<li><p><code>alice.introduce()</code> – Calls the <code>introduce</code> method on the <code>alice</code> object:</p>
<ol>
<li><p><code>this</code> inside <code>introduce</code> refers to <code>alice</code></p>
</li>
<li><p><code>this.name</code> becomes <code>alice.name</code> ("Alice")</p>
</li>
<li><p><code>this.age</code> becomes <code>alice.age</code> (28)</p>
</li>
<li><p><code>this.profession</code> becomes <code>alice.profession</code> ("developer")</p>
</li>
</ol>
</li>
</ul>
<h3 id="heading-what-happens-with-new">What happens with 'new'?</h3>
<p>When you use <code>new</code>, JavaScript does four things:</p>
<ol>
<li><p>Creates a new empty object</p>
</li>
<li><p>Sets <code>this</code> to that new object</p>
</li>
<li><p>Sets the new object's prototype to the constructor's prototype</p>
</li>
<li><p>Returns the new object (unless the constructor explicitly returns something else)</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Car</span>(<span class="hljs-params">make, model</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>); <span class="hljs-comment">// Shows the new empty object</span>
    <span class="hljs-built_in">this</span>.make = make;
    <span class="hljs-built_in">this</span>.model = model;

    <span class="hljs-comment">// JavaScript automatically returns 'this' (the new object)</span>
}

<span class="hljs-keyword">const</span> myCar = <span class="hljs-keyword">new</span> Car(<span class="hljs-string">"Toyota"</span>, <span class="hljs-string">"Camry"</span>);
<span class="hljs-built_in">console</span>.log(myCar); <span class="hljs-comment">// Output: Car { make: "Toyota", model: "Camry" }</span>
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>function Car(make, model) { ... }</code> – Constructor function for creating car objects</p>
</li>
<li><p><code>console.log(this);</code> – When called with <code>new</code>, this shows the new empty object that was just created</p>
</li>
<li><p><code>this.make = make;</code> – Adds a <code>make</code> property to the new object</p>
</li>
<li><p><code>this.model = model;</code> – Adds a <code>model</code> property to the new object</p>
</li>
<li><p><code>const myCar = new Car("Toyota", "Camry");</code> – The <code>new</code> process:</p>
<ol>
<li><p>Creates new empty object: <code>{}</code></p>
</li>
<li><p>Sets <code>this</code> to point to this object</p>
</li>
<li><p>Calls <code>Car("Toyota", "Camry")</code></p>
</li>
<li><p>Inside the function, <code>this.make = "Toyota"</code> and <code>this.model = "Camry"</code></p>
</li>
<li><p>Object becomes: <code>{ make: "Toyota", model: "Camry" }</code></p>
</li>
<li><p>Returns this object and stores it in <code>myCar</code></p>
</li>
</ol>
</li>
<li><p><code>console.log(myCar);</code> – Shows the final object with all its properties</p>
</li>
</ul>
<h3 id="heading-constructor-function-best-practices">Constructor Function Best Practices</h3>
<p>When creating constructor functions, following established patterns makes your code more maintainable and less error-prone. Here are the key best practices demonstrated in a realistic example:</p>
<ol>
<li><p><strong>Use descriptive parameter names</strong> that match property names</p>
</li>
<li><p><strong>Initialize all properties</strong> in the constructor</p>
</li>
<li><p><strong>Add methods that modify the object state</strong> appropriately</p>
</li>
<li><p><strong>Include validation logic</strong> for business rules</p>
</li>
<li><p><strong>Provide user feedback</strong> for operations</p>
</li>
<li><p><strong>Use consistent naming conventions</strong> throughout</p>
</li>
</ol>
<p>Let's see these practices in action with a <code>BankAccount</code> constructor:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BankAccount</span>(<span class="hljs-params">accountNumber, initialBalance</span>) </span>{
    <span class="hljs-built_in">this</span>.accountNumber = accountNumber;
    <span class="hljs-built_in">this</span>.balance = initialBalance;
    <span class="hljs-built_in">this</span>.transactions = [];

    <span class="hljs-built_in">this</span>.deposit = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">amount</span>) </span>{
        <span class="hljs-built_in">this</span>.balance += amount;
        <span class="hljs-built_in">this</span>.transactions.push(<span class="hljs-string">`Deposit: +$<span class="hljs-subst">${amount}</span>`</span>);
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Deposited $<span class="hljs-subst">${amount}</span>. New balance: $<span class="hljs-subst">${<span class="hljs-built_in">this</span>.balance}</span>`</span>);
    };

    <span class="hljs-built_in">this</span>.withdraw = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">amount</span>) </span>{
        <span class="hljs-keyword">if</span> (amount &lt;= <span class="hljs-built_in">this</span>.balance) {
            <span class="hljs-built_in">this</span>.balance -= amount;
            <span class="hljs-built_in">this</span>.transactions.push(<span class="hljs-string">`Withdrawal: -$<span class="hljs-subst">${amount}</span>`</span>);
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Withdrew $<span class="hljs-subst">${amount}</span>. New balance: $<span class="hljs-subst">${<span class="hljs-built_in">this</span>.balance}</span>`</span>);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Insufficient funds. Current balance: $<span class="hljs-subst">${<span class="hljs-built_in">this</span>.balance}</span>`</span>);
        }
    };
}

<span class="hljs-keyword">const</span> account = <span class="hljs-keyword">new</span> BankAccount(<span class="hljs-string">"123456789"</span>, <span class="hljs-number">1000</span>);
account.deposit(<span class="hljs-number">500</span>);  <span class="hljs-comment">// Output: "Deposited $500. New balance: $1500"</span>
account.withdraw(<span class="hljs-number">200</span>); <span class="hljs-comment">// Output: "Withdrew $200. New balance: $1300"</span>
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>function BankAccount(accountNumber, initialBalance) { ... }</code> – Constructor for bank account objects</p>
</li>
<li><p><code>this.accountNumber = accountNumber;</code> – Sets the account number property</p>
</li>
<li><p><code>this.balance = initialBalance;</code> – Sets the initial balance</p>
</li>
<li><p><code>this.transactions = [];</code> – Creates an empty array to store transaction history</p>
</li>
<li><p><code>this.deposit = function(amount) { ... }</code> – Adds a deposit method to each account object:</p>
<ol>
<li><p><code>this.balance += amount;</code> – Increases the balance by the deposit amount</p>
</li>
<li><p><code>this.transactions.push(...)</code> – Adds a record to the transactions array</p>
</li>
<li><p><code>console.log(...)</code> – Shows confirmation message with new balance</p>
</li>
</ol>
</li>
<li><p><code>this.withdraw = function(amount) { ... }</code> – Adds a withdrawal method:</p>
<ol>
<li><p><code>if (amount &lt;= this.balance)</code> – Checks if there's enough money</p>
</li>
<li><p>If yes: decreases balance, adds transaction record, shows confirmation</p>
</li>
<li><p>If no: shows an " insufficient funds message”</p>
</li>
</ol>
</li>
<li><p><code>const account = new BankAccount("123456789", 1000);</code> – Creates a new account with:</p>
<ul>
<li><p>Account number: "123456789"</p>
</li>
<li><p>Initial balance: 1000</p>
</li>
<li><p>Empty transactions array</p>
</li>
</ul>
</li>
<li><p><code>account.deposit(500);</code> – Calls the deposit method on the account:</p>
<ol>
<li><p><code>this</code> inside deposit refers to <code>account</code></p>
</li>
<li><p><code>this.balance</code> (1000) becomes 1500</p>
</li>
<li><p>Adds "Deposit: +$500" to transactions array</p>
</li>
</ol>
</li>
<li><p><code>account.withdraw(200);</code> – Calls withdraw method:</p>
<ol>
<li><p>Checks if 200 &lt;= 1500 (true)</p>
</li>
<li><p><code>this.balance</code> (1500) becomes 1300</p>
</li>
<li><p>Adds "Withdrawal: -$200" to transactions array</p>
</li>
</ol>
</li>
</ul>
<p>Here are the best practices identified from the code example:</p>
<ul>
<li><p><code>function BankAccount(accountNumber, initialBalance) { ... }</code> – <strong>Best Practice 1</strong>: Constructor name uses PascalCase and descriptive parameters</p>
</li>
<li><p><code>this.accountNumber = accountNumber;</code> – <strong>Best Practice 2</strong>: Initialize all properties with clear names</p>
</li>
<li><p><code>this.transactions = [];</code> – <strong>Best Practice 2</strong>: Initialize collections to prevent undefined errors</p>
</li>
<li><p><code>this.deposit = function(amount) { ... }</code> – <strong>Best Practice 3</strong>: Add methods that logically modify object state</p>
</li>
<li><p><code>if (amount &lt;= this.balance)</code> – <strong>Best Practice 4</strong>: Include validation logic to enforce business rules</p>
</li>
<li><p><code>console.log(...)</code> – <strong>Best Practice 5</strong>: Provide immediate feedback for user operations</p>
</li>
<li><p><code>this.transactions.push(...)</code> – <strong>Best Practice 6</strong>: Maintain audit trail with consistent data structure</p>
</li>
</ul>
<h2 id="heading-rule-4-default-binding-the-fallback">Rule 4: Default Binding – The Fallback</h2>
<p>When none of the other rules apply, JavaScript uses default binding. In non-strict mode, <code>this</code> defaults to the global object (window in browsers, global in Node.js). In strict mode, <code>this</code> is <code>undefined</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Non-strict mode</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello from <span class="hljs-subst">${<span class="hljs-built_in">this</span>}</span>`</span>); <span class="hljs-comment">// 'this' refers to global object</span>
}

sayHello(); <span class="hljs-comment">// Output: "Hello from [object Window]" (in browser)</span>

<span class="hljs-comment">// Strict mode</span>
<span class="hljs-meta">"use strict"</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHelloStrict</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello from <span class="hljs-subst">${<span class="hljs-built_in">this</span>}</span>`</span>); <span class="hljs-comment">// 'this' is undefined</span>
}

sayHelloStrict(); <span class="hljs-comment">// Output: "Hello from undefined"</span>
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>function sayHello() {console.log(`Hello from ${this}`);}</code> – Function that logs the value of <code>this</code></p>
</li>
<li><p><code>sayHello();</code> – Called as a standalone function (not as a method, not with <code>new</code>, not with <code>call/apply/bind</code>)</p>
</li>
<li><p>In non-strict mode:</p>
<ol>
<li><p>No explicit binding rule applies</p>
</li>
<li><p>Not called as a method (no dot notation)</p>
</li>
<li><p>Not called with <code>new</code></p>
</li>
<li><p>Falls back to default binding</p>
</li>
<li><p><code>this</code> becomes the global object (window in browsers)</p>
</li>
</ol>
</li>
<li><p><code>"use strict";</code> – Enables strict mode for the following code</p>
</li>
<li><p><code>function sayHelloStrict() { console.log(</code>Hello from ${this}<code>); }</code> – Same function in strict mode</p>
</li>
<li><p><code>sayHelloStrict();</code> – In strict mode:</p>
<ol>
<li><p>Same rules apply, but default binding behaves differently</p>
</li>
<li><p>Instead of using global object, <code>this</code> becomes <code>undefined</code></p>
</li>
<li><p>This helps catch errors where <code>this</code> is used incorrectly</p>
</li>
</ol>
</li>
</ul>
<h3 id="heading-global-variables-and-this">Global Variables and 'this'</h3>
<p>In non-strict mode, global variables become properties of the global object:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> globalName = <span class="hljs-string">"Global User"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showGlobalName</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.globalName); <span class="hljs-comment">// Accesses global variable</span>
}

showGlobalName(); <span class="hljs-comment">// Output: "Global User"</span>

<span class="hljs-comment">// In strict mode, this would be undefined</span>
<span class="hljs-meta">"use strict"</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showGlobalNameStrict</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.globalName); <span class="hljs-comment">// Error: Cannot read property of undefined</span>
}
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>var globalName = "Global User";</code> – Creates a global variable using <code>var</code></p>
</li>
<li><p>In non-strict mode, <code>var</code> variables become properties of the global object</p>
</li>
<li><p>So <code>globalName</code> becomes <code>window.globalName</code> (in browsers)</p>
</li>
<li><p><code>function showGlobalName() { console.log(this.globalName); }</code> – Function that accesses <code>this.globalName</code></p>
</li>
<li><p><code>showGlobalName();</code> – Called as standalone function:</p>
<ol>
<li><p><code>this</code> refers to global object (window)</p>
</li>
<li><p><code>this.globalName</code> becomes <code>window.globalName</code></p>
</li>
<li><p>Which is the same as the global variable <code>globalName</code></p>
</li>
<li><p>Outputs: "Global User"</p>
</li>
</ol>
</li>
<li><p><code>"use strict";</code> – Enables strict mode</p>
</li>
<li><p><code>function showGlobalNameStrict() { console.log(this.globalName); }</code> – Same function in strict mode</p>
</li>
<li><p><code>showGlobalNameStrict();</code> – In strict mode:</p>
<ol>
<li><p><code>this</code> is <code>undefined</code> (not the global object)</p>
</li>
<li><p><code>this.globalName</code> tries to access <code>undefined.globalName</code></p>
</li>
<li><p>This throws an error: "Cannot read property of undefined"</p>
</li>
</ol>
</li>
</ul>
<h2 id="heading-arrow-functions-the-game-changer">Arrow Functions – The Game Changer</h2>
<p>Arrow functions don't have their own <code>this</code> binding. They inherit <code>this</code> from the enclosing scope (lexical scoping). This is like having a function that always remembers where it came from.</p>
<p>Let’s look at an example of some code that doesn’t use an arrow function (and has a problem). Then you’ll see how the arrow function fixes the issue:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> team = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Development Team"</span>,
    <span class="hljs-attr">members</span>: [<span class="hljs-string">"Alice"</span>, <span class="hljs-string">"Bob"</span>, <span class="hljs-string">"Charlie"</span>],

    <span class="hljs-comment">// Regular function - 'this' refers to team object</span>
    <span class="hljs-attr">showTeamRegular</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">`Team: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>);

        <span class="hljs-comment">// Problem: 'this' is lost in callback</span>
        <span class="hljs-built_in">this</span>.members.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">member</span>) </span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${member}</span> is in <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>); <span class="hljs-comment">// 'this' is undefined or global</span>
        });
    },

    <span class="hljs-comment">// Arrow function solution</span>
    <span class="hljs-attr">showTeamArrow</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">`Team: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>);

        <span class="hljs-comment">// Arrow function inherits 'this' from parent scope</span>
        <span class="hljs-built_in">this</span>.members.forEach(<span class="hljs-function">(<span class="hljs-params">member</span>) =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${member}</span> is in <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>); <span class="hljs-comment">// 'this' correctly refers to team</span>
        });
    }
};

team.showTeamRegular(); 
<span class="hljs-comment">// Output: Team: Development Team</span>
<span class="hljs-comment">//         Alice is in undefined</span>
<span class="hljs-comment">//         Bob is in undefined</span>
<span class="hljs-comment">//         Charlie is in undefined</span>

team.showTeamArrow(); 
<span class="hljs-comment">// Output: Team: Development Team</span>
<span class="hljs-comment">//         Alice is in Development Team</span>
<span class="hljs-comment">//         Bob is in Development Team</span>
<span class="hljs-comment">//         Charlie is in Development Team</span>
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>const team = { name: "Development Team", members: ["Alice", "Bob", "Charlie"], ... };</code> – Object with team info</p>
</li>
<li><p><code>showTeamRegular: function() { ... }</code> – Regular function method</p>
</li>
<li><p><code>console.log(</code>Team: ${<a target="_blank" href="http://this.name">this.name</a>}<code>);</code> – Works correctly, <code>this</code> refers to <code>team</code> object</p>
</li>
<li><p><code>this.members.forEach(function(member) { ... });</code> – <strong>PROBLEM HERE</strong>:</p>
<ol>
<li><p><code>forEach</code> takes a callback function</p>
</li>
<li><p><code>function(member) { ... }</code> is a regular function passed as callback</p>
</li>
<li><p>When <code>forEach</code> calls this function, it calls it as a standalone function</p>
</li>
<li><p><code>this</code> inside the callback uses default binding (undefined or global)</p>
</li>
<li><p><code>this.name</code> is undefined, so output shows "undefined"</p>
</li>
</ol>
</li>
<li><p><code>showTeamArrow: function() { ... }</code> – Method using arrow function solution</p>
</li>
<li><p><code>this.members.forEach((member) =&gt; { ... });</code> – <strong>SOLUTION</strong>:</p>
<ol>
<li><p><code>(member) =&gt; { ... }</code> is an arrow function</p>
</li>
<li><p>Arrow functions don't have their own <code>this</code></p>
</li>
<li><p>They inherit <code>this</code> from the surrounding scope</p>
</li>
<li><p>The surrounding scope is <code>showTeamArrow</code> method where <code>this</code> refers to <code>team</code></p>
</li>
<li><p>So inside arrow function, <code>this</code> still refers to <code>team</code></p>
</li>
<li><p><code>this.name</code> correctly becomes <code>team.name</code> ("Development Team")</p>
</li>
</ol>
</li>
</ul>
<h3 id="heading-arrow-functions-in-different-contexts">Arrow Functions in Different Contexts</h3>
<p>Arrow functions behave differently depending on <strong>where they're defined</strong>, not how they're called. Understanding these different contexts is crucial for predicting <code>this</code> behavior:</p>
<p><strong>Different contexts:</strong></p>
<ul>
<li><p><strong>Global context</strong>: Arrow functions inherit global <code>this</code></p>
</li>
<li><p><strong>Object methods</strong>: Arrow functions DON'T get the object as <code>this</code></p>
</li>
<li><p><strong>Inside regular methods</strong>: Arrow functions inherit the method's <code>this</code></p>
</li>
<li><p><strong>Class properties</strong>: Arrow functions are bound to the instance</p>
</li>
</ul>
<p>Let's explore how the same arrow function syntax produces different results in each context:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Global context</span>
<span class="hljs-keyword">const</span> globalArrow = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>); <span class="hljs-comment">// Refers to global object (or undefined in strict mode)</span>
};

<span class="hljs-comment">// Object method</span>
<span class="hljs-keyword">const</span> obj = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"Object"</span>,

    <span class="hljs-attr">regularMethod</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">`Regular: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>); <span class="hljs-comment">// 'this' refers to obj</span>

        <span class="hljs-keyword">const</span> innerArrow = <span class="hljs-function">() =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Arrow inside regular: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>); <span class="hljs-comment">// Inherits 'this' from regularMethod</span>
        };

        innerArrow();
    },

    <span class="hljs-attr">arrowMethod</span>: <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Arrow method: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>); <span class="hljs-comment">// 'this' refers to global, not obj</span>
    }
};

obj.regularMethod(); 
<span class="hljs-comment">// Output: Regular: Object</span>
<span class="hljs-comment">//         Arrow inside regular: Object</span>

obj.arrowMethod(); 
<span class="hljs-comment">// Output: Arrow method: undefined (or global name)</span>
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>const globalArrow = () =&gt; { console.log(this); };</code> – Arrow function in global scope:</p>
<ol>
<li><p>Arrow functions inherit <code>this</code> from enclosing scope</p>
</li>
<li><p>Global scope's <code>this</code> is the global object (or undefined in strict mode)</p>
</li>
<li><p>So <code>this</code> inside this arrow function refers to global object</p>
</li>
</ol>
</li>
<li><p><code>const obj = { name: "Object", ... };</code> – Object with different types of methods</p>
</li>
<li><p><code>regularMethod: function() { ... }</code> – Regular function method:</p>
<ol>
<li><p>When called as <code>obj.regularMethod()</code>, <code>this</code> refers to <code>obj</code></p>
</li>
<li><p><code>this.name</code> becomes <code>obj.name</code> ("Object")</p>
</li>
</ol>
</li>
<li><p><code>const innerArrow = () =&gt; { ... };</code> – Arrow function defined inside regular method:</p>
<ol>
<li><p>Arrow function inherits <code>this</code> from the enclosing scope</p>
</li>
<li><p>Enclosing scope is <code>regularMethod</code> where <code>this</code> refers to <code>obj</code></p>
</li>
<li><p>So <code>this</code> inside arrow function also refers to <code>obj</code></p>
</li>
<li><p><code>this.name</code> becomes <code>obj.name</code> ("Object")</p>
</li>
</ol>
</li>
<li><p><code>arrowMethod: () =&gt; { ... }</code> – Arrow function as object method:</p>
<ol>
<li><p>Arrow function inherits <code>this</code> from enclosing scope</p>
</li>
<li><p>Enclosing scope is global scope (where <code>obj</code> is defined)</p>
</li>
<li><p>Global scope's <code>this</code> is global object (or undefined)</p>
</li>
<li><p>So <code>this</code> inside arrow function refers to global, not <code>obj</code></p>
</li>
<li><p><code>this.name</code> is undefined (assuming no global <code>name</code> variable)</p>
</li>
</ol>
</li>
</ul>
<h2 id="heading-class-context-and-this">Class Context and 'this'</h2>
<p>In ES6 classes, <code>this</code> works similarly to constructor functions:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicle</span> </span>{
    <span class="hljs-keyword">constructor</span>(make, model, year) {
        <span class="hljs-built_in">this</span>.make = make;
        <span class="hljs-built_in">this</span>.model = model;
        <span class="hljs-built_in">this</span>.year = year;
        <span class="hljs-built_in">this</span>.mileage = <span class="hljs-number">0</span>;
    }

    drive(miles) {
        <span class="hljs-built_in">this</span>.mileage += miles;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.make}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.model}</span> has driven <span class="hljs-subst">${miles}</span> miles. Total: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.mileage}</span>`</span>);
    }

    getInfo() {
        <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.year}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.make}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.model}</span>`</span>;
    }

    <span class="hljs-comment">// Arrow function as class property (bound to instance)</span>
    getInfoArrow = <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.year}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.make}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.model}</span>`</span>;
    }
}

<span class="hljs-keyword">const</span> car = <span class="hljs-keyword">new</span> Vehicle(<span class="hljs-string">"Honda"</span>, <span class="hljs-string">"Civic"</span>, <span class="hljs-number">2024</span>);
car.drive(<span class="hljs-number">100</span>); <span class="hljs-comment">// Output: "Honda Civic has driven 100 miles. Total: 100"</span>
<span class="hljs-built_in">console</span>.log(car.getInfo()); <span class="hljs-comment">// Output: "2024 Honda Civic"</span>

<span class="hljs-comment">// Method context loss and solution</span>
<span class="hljs-keyword">const</span> getCarInfo = car.getInfo; <span class="hljs-comment">// Lost context</span>
<span class="hljs-comment">// getCarInfo(); // Would throw error or return undefined values</span>

<span class="hljs-keyword">const</span> getBoundInfo = car.getInfoArrow; <span class="hljs-comment">// Arrow function preserves context</span>
<span class="hljs-built_in">console</span>.log(getBoundInfo()); <span class="hljs-comment">// Output: "2024 Honda Civic"</span>
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>class Vehicle { ... }</code> – ES6 class definition</p>
</li>
<li><p><code>constructor(make, model, year) { ... }</code> – Constructor method, similar to constructor function</p>
</li>
<li><p><code>this.make = make;</code> – Sets properties on the instance being created</p>
</li>
<li><p><code>drive(miles) { ... }</code> – Regular method where <code>this</code> refers to the instance</p>
</li>
<li><p><code>getInfo() { ... }</code> – Regular method that can lose context when assigned to variable</p>
</li>
<li><p><code>getInfoArrow = () =&gt; { ... }</code> – Arrow function as class property, permanently bound to instance</p>
</li>
<li><p><code>const car = new Vehicle("Honda", "Civic", 2024);</code> – Creates new instance</p>
</li>
<li><p><code>const getCarInfo = car.getInfo;</code> – Assigns method to variable (loses context)</p>
</li>
<li><p><code>const getBoundInfo = car.getInfoArrow;</code> – Arrow function preserves context even when assigned</p>
</li>
</ul>
<h2 id="heading-common-pitfalls-and-solutions">Common Pitfalls and Solutions</h2>
<p>Even experienced developers encounter <code>this</code>-related bugs in specific scenarios. These problems typically arise when JavaScript's context-switching behavior conflicts with our expectations. The most common issues occur in:</p>
<ul>
<li><p><strong>Event handlers</strong> where <code>this</code> switches to the DOM element</p>
</li>
<li><p><strong>Callback functions</strong> where <code>this</code> loses its original context</p>
</li>
<li><p><strong>Asynchronous operations</strong> where timing affects context</p>
</li>
<li><p><strong>Framework integration</strong> where libraries change calling patterns</p>
</li>
</ul>
<p>Let's examine each pitfall, understand why it happens, and learn multiple solutions for each scenario.</p>
<h3 id="heading-1-event-handlers">1. Event Handlers</h3>
<p>Event handlers are functions that respond to user interactions or browser events.</p>
<p><strong>The Problem</strong>: When you attach a method as an event listener, the browser calls it with <code>this</code> referring to the DOM element that triggered the event, not your class instance. This breaks access to your object's properties and methods.</p>
<p><strong>Why It Happens</strong>: Event listeners are called by the browser's event system, which sets <code>this</code> to the event target for convenience. Your method loses its original object context.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Button</span> </span>{
    <span class="hljs-keyword">constructor</span>(element) {
        <span class="hljs-built_in">this</span>.element = element;
        <span class="hljs-built_in">this</span>.clickCount = <span class="hljs-number">0</span>;

        <span class="hljs-comment">// Problem: 'this' will refer to the button element, not the Button instance</span>
        <span class="hljs-built_in">this</span>.element.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-built_in">this</span>.handleClick);

        <span class="hljs-comment">// Solution 1: Bind the method</span>
        <span class="hljs-built_in">this</span>.element.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-built_in">this</span>.handleClick.bind(<span class="hljs-built_in">this</span>));

        <span class="hljs-comment">// Solution 2: Arrow function</span>
        <span class="hljs-built_in">this</span>.element.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">this</span>.handleClick());
    }

    handleClick() {
        <span class="hljs-built_in">this</span>.clickCount++;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Button clicked <span class="hljs-subst">${<span class="hljs-built_in">this</span>.clickCount}</span> times`</span>);
    }

    <span class="hljs-comment">// Solution 3: Arrow function as class property</span>
    handleClickArrow = <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-built_in">this</span>.clickCount++;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Button clicked <span class="hljs-subst">${<span class="hljs-built_in">this</span>.clickCount}</span> times`</span>);
    }
}

<span class="hljs-keyword">const</span> button = <span class="hljs-keyword">new</span> Button(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myButton'</span>));
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>class Button { ... }</code> – Class for managing button click events</p>
</li>
<li><p><code>this.element.addEventListener('click', this.handleClick);</code> – <strong>PROBLEM</strong>: When the event fires, <code>this</code> inside <code>handleClick</code> refers to the button element, not the Button instance</p>
</li>
<li><p><code>this.element.addEventListener('click', this.handleClick.bind(this));</code> – <strong>SOLUTION 1</strong>: <code>bind()</code> creates a new function with <code>this</code> permanently set to the Button instance</p>
</li>
<li><p><code>this.element.addEventListener('click', () =&gt; this.handleClick());</code> – <strong>SOLUTION 2</strong>: Arrow function preserves <code>this</code> from surrounding scope</p>
</li>
<li><p><code>handleClickArrow = () =&gt; { ... }</code> – <strong>SOLUTION 3</strong>: Arrow function as class property is automatically bound to instance</p>
</li>
</ul>
<h3 id="heading-2-callback-functions">2. Callback Functions</h3>
<p>Callback functions are functions passed as arguments to other functions, called back later.</p>
<p><strong>The Problem</strong>: When passing methods as callbacks to array methods (<code>forEach</code>, <code>map</code>, and so on) or other functions, <code>this</code> becomes undefined or refers to the global object instead of your class instance.</p>
<p><strong>Why It Happens</strong>: Callback functions are invoked as standalone functions, not as methods, so they lose their object context and fall back to default binding rules.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DataProcessor</span> </span>{
    <span class="hljs-keyword">constructor</span>(data) {
        <span class="hljs-built_in">this</span>.data = data;
        <span class="hljs-built_in">this</span>.processedCount = <span class="hljs-number">0</span>;
    }

    processItem(item) {
        <span class="hljs-comment">// Process the item</span>
        <span class="hljs-built_in">this</span>.processedCount++;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Processed <span class="hljs-subst">${item}</span>. Total: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.processedCount}</span>`</span>);
    }

    processAll() {
        <span class="hljs-comment">// Problem: 'this' context lost in forEach callback</span>
        <span class="hljs-built_in">this</span>.data.forEach(<span class="hljs-built_in">this</span>.processItem); <span class="hljs-comment">// Won't work correctly</span>

        <span class="hljs-comment">// Solution 1: Bind</span>
        <span class="hljs-built_in">this</span>.data.forEach(<span class="hljs-built_in">this</span>.processItem.bind(<span class="hljs-built_in">this</span>));

        <span class="hljs-comment">// Solution 2: Arrow function</span>
        <span class="hljs-built_in">this</span>.data.forEach(<span class="hljs-function">(<span class="hljs-params">item</span>) =&gt;</span> <span class="hljs-built_in">this</span>.processItem(item));

        <span class="hljs-comment">// Solution 3: Store 'this' in variable</span>
        <span class="hljs-keyword">const</span> self = <span class="hljs-built_in">this</span>;
        <span class="hljs-built_in">this</span>.data.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>) </span>{
            self.processItem(item);
        });
    }
}

<span class="hljs-keyword">const</span> processor = <span class="hljs-keyword">new</span> DataProcessor([<span class="hljs-string">'item1'</span>, <span class="hljs-string">'item2'</span>, <span class="hljs-string">'item3'</span>]);
processor.processAll();
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>class DataProcessor { ... }</code> – Class for processing arrays of data</p>
</li>
<li><p><code>processItem(item) { ... }</code> – Method that processes individual items and updates counter</p>
</li>
<li><p><a target="_blank" href="http://this.data"><code>this.data</code></a><code>.forEach(this.processItem);</code> – <strong>PROBLEM</strong>: <code>forEach</code> calls <code>processItem</code> as standalone function, losing <code>this</code> context</p>
</li>
<li><p><a target="_blank" href="http://this.data"><code>this.data</code></a><code>.forEach(this.processItem.bind(this));</code> – <strong>SOLUTION 1</strong>: Bind <code>this</code> to the method</p>
</li>
<li><p><a target="_blank" href="http://this.data"><code>this.data</code></a><code>.forEach((item) =&gt; this.processItem(item));</code> – <strong>SOLUTION 2</strong>: Arrow function preserves <code>this</code></p>
</li>
<li><p><code>const self = this;</code> – <strong>SOLUTION 3</strong>: Store reference to <code>this</code> in variable for use in regular function</p>
</li>
</ul>
<h3 id="heading-3-asyncawait-and-promises">3. Async/Await and Promises</h3>
<p>Async/Await and Promises are a modern way to handle asynchronous operations, making async code look synchronous.</p>
<p><strong>The Problem</strong>: While <code>async/await</code> preserves <code>this</code> context better than traditional promises, issues can still arise when mixing different function types or when promise callbacks lose context.</p>
<p><strong>Why It Happens</strong>: Promise callbacks and certain async patterns can create new execution contexts where <code>this</code> doesn't point to your original object.</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ApiClient</span> </span>{
    <span class="hljs-keyword">constructor</span>(baseUrl) {
        <span class="hljs-built_in">this</span>.baseUrl = baseUrl;
        <span class="hljs-built_in">this</span>.requestCount = <span class="hljs-number">0</span>;
    }

    <span class="hljs-keyword">async</span> fetchData(endpoint) {
        <span class="hljs-built_in">this</span>.requestCount++;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Making request #<span class="hljs-subst">${<span class="hljs-built_in">this</span>.requestCount}</span> to <span class="hljs-subst">${<span class="hljs-built_in">this</span>.baseUrl}</span><span class="hljs-subst">${endpoint}</span>`</span>);

        <span class="hljs-keyword">try</span> {
            <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.baseUrl}</span><span class="hljs-subst">${endpoint}</span>`</span>);
            <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
            <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.processResponse(data); <span class="hljs-comment">// 'this' is preserved in async/await</span>
        } <span class="hljs-keyword">catch</span> (error) {
            <span class="hljs-built_in">this</span>.handleError(error);
        }
    }

    processResponse(data) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Processing response. Total requests: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.requestCount}</span>`</span>);
        <span class="hljs-keyword">return</span> data;
    }

    handleError(error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">`Error in request #<span class="hljs-subst">${<span class="hljs-built_in">this</span>.requestCount}</span>:`</span>, error);
    }

    <span class="hljs-comment">// Using promises with potential context loss</span>
    fetchDataWithPromises(endpoint) {
        <span class="hljs-built_in">this</span>.requestCount++;

        <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.baseUrl}</span><span class="hljs-subst">${endpoint}</span>`</span>)
            .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json()) <span class="hljs-comment">// Arrow function preserves 'this'</span>
            .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">this</span>.processResponse(data)) <span class="hljs-comment">// 'this' correctly refers to instance</span>
            .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">this</span>.handleError(error));
    }
}

<span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> ApiClient(<span class="hljs-string">'https://api.example.com/'</span>);
client.fetchData(<span class="hljs-string">'/users'</span>);
</code></pre>
<p><strong>Code explanation:</strong></p>
<ul>
<li><p><code>class ApiClient { ... }</code> – Class for making API requests</p>
</li>
<li><p><code>async fetchData(endpoint) { ... }</code> – Async method where <code>this</code> is preserved throughout</p>
</li>
<li><p><code>return this.processResponse(data);</code> – <code>this</code> context maintained in async functions</p>
</li>
<li><p><code>fetchDataWithPromises(endpoint) { ... }</code> – Alternative using Promises</p>
</li>
<li><p><code>.then(data =&gt; this.processResponse(data))</code> – Arrow function preserves <code>this</code> context in Promise chains</p>
</li>
<li><p><code>.catch(error =&gt; this.handleError(error))</code> – Arrow function ensures <code>this</code> refers to the instance</p>
</li>
</ul>
<h2 id="heading-when-to-use-this-practical-guidelines">When to Use 'this' – Practical Guidelines</h2>
<h3 id="heading-1-object-oriented-programming">1. Object-Oriented Programming</h3>
<p>Use <code>this</code> when creating objects with methods that need to access the object's properties:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Good use of 'this'</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ShoppingCart</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-built_in">this</span>.items = [];
        <span class="hljs-built_in">this</span>.total = <span class="hljs-number">0</span>;
    }

    addItem(item, price) {
        <span class="hljs-built_in">this</span>.items.push({ item, price });
        <span class="hljs-built_in">this</span>.total += price;
        <span class="hljs-built_in">this</span>.updateDisplay();
    }

    removeItem(index) {
        <span class="hljs-keyword">if</span> (index &gt;= <span class="hljs-number">0</span> &amp;&amp; index &lt; <span class="hljs-built_in">this</span>.items.length) {
            <span class="hljs-built_in">this</span>.total -= <span class="hljs-built_in">this</span>.items[index].price;
            <span class="hljs-built_in">this</span>.items.splice(index, <span class="hljs-number">1</span>);
            <span class="hljs-built_in">this</span>.updateDisplay();
        }
    }

    updateDisplay() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Cart: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.items.length}</span> items, Total: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.total}</span>`</span>);
    }
}

<span class="hljs-keyword">const</span> cart = <span class="hljs-keyword">new</span> ShoppingCart();
cart.addItem(<span class="hljs-string">'Laptop'</span>, <span class="hljs-number">999</span>);
cart.addItem(<span class="hljs-string">'Mouse'</span>, <span class="hljs-number">25</span>);
</code></pre>
<h3 id="heading-2-event-handling">2. Event Handling</h3>
<p>Use <code>this</code> when you need to access the object's state in event handlers:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">FormValidator</span> </span>{
    <span class="hljs-keyword">constructor</span>(formElement) {
        <span class="hljs-built_in">this</span>.form = formElement;
        <span class="hljs-built_in">this</span>.errors = [];

        <span class="hljs-comment">// Bind event handlers to preserve 'this'</span>
        <span class="hljs-built_in">this</span>.form.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-built_in">this</span>.handleSubmit.bind(<span class="hljs-built_in">this</span>));
        <span class="hljs-built_in">this</span>.form.addEventListener(<span class="hljs-string">'input'</span>, <span class="hljs-built_in">this</span>.handleInput.bind(<span class="hljs-built_in">this</span>));
    }

    handleSubmit(event) {
        event.preventDefault();
        <span class="hljs-built_in">this</span>.validateForm();

        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.errors.length === <span class="hljs-number">0</span>) {
            <span class="hljs-built_in">this</span>.submitForm();
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-built_in">this</span>.displayErrors();
        }
    }

    handleInput(event) {
        <span class="hljs-built_in">this</span>.clearErrorFor(event.target.name);
    }

    validateForm() {
        <span class="hljs-built_in">this</span>.errors = [];
        <span class="hljs-comment">// Validation logic that updates this.errors</span>
    }

    submitForm() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Form submitted successfully'</span>);
    }

    displayErrors() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Validation errors:'</span>, <span class="hljs-built_in">this</span>.errors);
    }

    clearErrorFor(fieldName) {
        <span class="hljs-built_in">this</span>.errors = <span class="hljs-built_in">this</span>.errors.filter(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> error.field !== fieldName);
    }
}
</code></pre>
<h3 id="heading-3-method-chaining">3. Method Chaining</h3>
<p>Method chaining is calling multiple methods in sequence by returning <code>this</code> from each method.</p>
<p>Use <code>this</code> to enable method chaining by returning the instance:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">QueryBuilder</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-built_in">this</span>.query = <span class="hljs-string">''</span>;
        <span class="hljs-built_in">this</span>.conditions = [];
    }

    select(fields) {
        <span class="hljs-built_in">this</span>.query += <span class="hljs-string">`SELECT <span class="hljs-subst">${fields}</span> `</span>;
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>; <span class="hljs-comment">// Return 'this' for chaining</span>
    }

    <span class="hljs-keyword">from</span>(table) {
        <span class="hljs-built_in">this</span>.query += <span class="hljs-string">`FROM <span class="hljs-subst">${table}</span> `</span>;
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }

    where(condition) {
        <span class="hljs-built_in">this</span>.conditions.push(condition);
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }

    build() {
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.conditions.length &gt; <span class="hljs-number">0</span>) {
            <span class="hljs-built_in">this</span>.query += <span class="hljs-string">`WHERE <span class="hljs-subst">${<span class="hljs-built_in">this</span>.conditions.join(<span class="hljs-string">' AND '</span>)}</span>`</span>;
        }
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.query.trim();
    }
}

<span class="hljs-comment">// Method chaining in action</span>
<span class="hljs-keyword">const</span> query = <span class="hljs-keyword">new</span> QueryBuilder()
    .select(<span class="hljs-string">'name, email'</span>)
    .from(<span class="hljs-string">'users'</span>)
    .where(<span class="hljs-string">'age &gt; 18'</span>)
    .where(<span class="hljs-string">'active = true'</span>)
    .build();

<span class="hljs-built_in">console</span>.log(query); <span class="hljs-comment">// "SELECT name, email FROM users WHERE age &gt; 18 AND active = true"</span>
</code></pre>
<h3 id="heading-4-pluginlibrary-development">4. Plugin/Library Development</h3>
<p>Plugin/library development refers to creating reusable code modules that can be used across different projects.</p>
<p>Use <code>this</code> when creating reusable components:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Modal</span> </span>{
    <span class="hljs-keyword">constructor</span>(element, options = {}) {
        <span class="hljs-built_in">this</span>.element = element;
        <span class="hljs-built_in">this</span>.options = {
            <span class="hljs-attr">closable</span>: <span class="hljs-literal">true</span>,
            <span class="hljs-attr">backdrop</span>: <span class="hljs-literal">true</span>,
            ...options
        };
        <span class="hljs-built_in">this</span>.isOpen = <span class="hljs-literal">false</span>;

        <span class="hljs-built_in">this</span>.init();
    }

    init() {
        <span class="hljs-built_in">this</span>.createBackdrop();
        <span class="hljs-built_in">this</span>.bindEvents();
    }

    createBackdrop() {
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.options.backdrop) {
            <span class="hljs-built_in">this</span>.backdrop = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
            <span class="hljs-built_in">this</span>.backdrop.className = <span class="hljs-string">'modal-backdrop'</span>;
            <span class="hljs-built_in">document</span>.body.appendChild(<span class="hljs-built_in">this</span>.backdrop);
        }
    }

    bindEvents() {
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.options.closable) {
            <span class="hljs-comment">// Using arrow function to preserve 'this'</span>
            <span class="hljs-built_in">this</span>.element.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
                <span class="hljs-keyword">if</span> (e.target.classList.contains(<span class="hljs-string">'close-btn'</span>)) {
                    <span class="hljs-built_in">this</span>.close();
                }
            });

            <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.backdrop) {
                <span class="hljs-built_in">this</span>.backdrop.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">this</span>.close());
            }
        }
    }

    open() {
        <span class="hljs-built_in">this</span>.isOpen = <span class="hljs-literal">true</span>;
        <span class="hljs-built_in">this</span>.element.classList.add(<span class="hljs-string">'open'</span>);
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.backdrop) {
            <span class="hljs-built_in">this</span>.backdrop.classList.add(<span class="hljs-string">'active'</span>);
        }
        <span class="hljs-built_in">document</span>.body.style.overflow = <span class="hljs-string">'hidden'</span>;
    }

    close() {
        <span class="hljs-built_in">this</span>.isOpen = <span class="hljs-literal">false</span>;
        <span class="hljs-built_in">this</span>.element.classList.remove(<span class="hljs-string">'open'</span>);
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.backdrop) {
            <span class="hljs-built_in">this</span>.backdrop.classList.remove(<span class="hljs-string">'active'</span>);
        }
        <span class="hljs-built_in">document</span>.body.style.overflow = <span class="hljs-string">''</span>;
    }
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-keyword">const</span> modal = <span class="hljs-keyword">new</span> Modal(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myModal'</span>), {
    <span class="hljs-attr">closable</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">backdrop</span>: <span class="hljs-literal">true</span>
});
</code></pre>
<h2 id="heading-when-not-to-use-this">When NOT to Use 'this'</h2>
<h3 id="heading-1-utility-functions">1. Utility Functions</h3>
<p>Utility functions are pure functions that perform common tasks without side effects.</p>
<p>Don't use <code>this</code> in pure utility functions that don't need object context</p>
<p><strong>So why should you avoid</strong> <code>this</code> in these cases? Utility functions should be pure and predictable. Using <code>this</code> introduces hidden dependencies and makes functions harder to test, reuse, and reason about. Pure functions are more maintainable because they always produce the same output for the same input.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Good - no 'this' needed</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">formatCurrency</span>(<span class="hljs-params">amount</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Intl</span>.NumberFormat(<span class="hljs-string">'en-US'</span>, {
        <span class="hljs-attr">style</span>: <span class="hljs-string">'currency'</span>,
        <span class="hljs-attr">currency</span>: <span class="hljs-string">'USD'</span>
    }).format(amount);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTax</span>(<span class="hljs-params">amount, rate</span>) </span>{
    <span class="hljs-keyword">return</span> amount * rate;
}

<span class="hljs-comment">// Better as module exports or standalone functions</span>
<span class="hljs-keyword">const</span> MathUtils = {
    <span class="hljs-attr">add</span>: <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a + b,
    <span class="hljs-attr">subtract</span>: <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a - b,
    <span class="hljs-attr">multiply</span>: <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> a * b,
    <span class="hljs-attr">divide</span>: <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> b !== <span class="hljs-number">0</span> ? a / b : <span class="hljs-number">0</span>
};
</code></pre>
<p><strong>Additional problems with</strong> <code>this</code> <strong>in utilities:</strong></p>
<ul>
<li><p>Makes functions dependent on calling context</p>
</li>
<li><p>Reduces reusability across different objects</p>
</li>
<li><p>Complicates testing since you need to mock object context</p>
</li>
<li><p>Breaks functional programming principles.</p>
</li>
</ul>
<h3 id="heading-2-functional-programming">2. Functional Programming</h3>
<p>When using functional programming patterns, avoid <code>this</code>. Functional programming emphasizes immutability and pure functions. The <code>this</code> keyword introduces mutable state and context dependency, which go against functional principles of predictability and composability.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Good - functional approach</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> processNumbers = <span class="hljs-function">(<span class="hljs-params">arr</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> arr
        .filter(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num &gt; <span class="hljs-number">2</span>)
        .map(<span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num * <span class="hljs-number">2</span>)
        .reduce(<span class="hljs-function">(<span class="hljs-params">sum, num</span>) =&gt;</span> sum + num, <span class="hljs-number">0</span>);
};

<span class="hljs-comment">// Instead of using 'this' in a class</span>
<span class="hljs-keyword">const</span> result = processNumbers(numbers);
</code></pre>
<p><strong>Additional benefits of avoiding</strong> <code>this</code>:</p>
<ul>
<li><p>Functions become more composable and chainable</p>
</li>
<li><p>Easier to reason about data flow</p>
</li>
<li><p>Better support for functional techniques like currying and partial application</p>
</li>
<li><p>More compatible with functional libraries like Lodash or Ramda</p>
</li>
</ul>
<h3 id="heading-3-simple-event-handlers">3. Simple Event Handlers</h3>
<p>For simple event handlers that don't need object state, you should avoid using <code>this</code>. Using <code>this</code> in these cases adds unnecessary complexity. Direct DOM manipulation or simple actions are clearer when written as straightforward functions.</p>
<pre><code class="lang-javascript">javascript<span class="hljs-comment">// Good - simple function without 'this'</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleButtonClick</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Button clicked!'</span>);
    event.target.style.backgroundColor = <span class="hljs-string">'blue'</span>;
}

<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myButton'</span>).addEventListener(<span class="hljs-string">'click'</span>, handleButtonClick);
</code></pre>
<p><strong>When</strong> <code>this</code> <strong>becomes overhead</strong>:</p>
<ul>
<li><p>One-time interactions that don't need state</p>
</li>
<li><p>Simple DOM manipulations</p>
</li>
<li><p>Static responses that don't vary based on object properties</p>
</li>
<li><p>Event handlers that only affect the event target itself.</p>
</li>
</ul>
<h2 id="heading-best-practices-and-tips">Best Practices and Tips</h2>
<h3 id="heading-1-always-be-explicit">1. Always Be Explicit</h3>
<p>When in doubt, be explicit about what <code>this</code> should refer to:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DataManager</span> </span>{
    <span class="hljs-keyword">constructor</span>(data) {
        <span class="hljs-built_in">this</span>.data = data;
    }

    <span class="hljs-comment">// Good - explicit binding</span>
    processData() {
        <span class="hljs-built_in">this</span>.data.forEach(<span class="hljs-built_in">this</span>.processItem.bind(<span class="hljs-built_in">this</span>));
    }

    <span class="hljs-comment">// Better - arrow function</span>
    processDataArrow() {
        <span class="hljs-built_in">this</span>.data.forEach(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> <span class="hljs-built_in">this</span>.processItem(item));
    }

    processItem(item) {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Processing: <span class="hljs-subst">${item}</span>`</span>);
    }
}
</code></pre>
<h3 id="heading-2-use-arrow-functions-for-callbacks">2. Use Arrow Functions for Callbacks</h3>
<p>Arrow functions are perfect for callbacks where you need to preserve <code>this</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Timer</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-built_in">this</span>.seconds = <span class="hljs-number">0</span>;
        <span class="hljs-built_in">this</span>.intervalId = <span class="hljs-literal">null</span>;
    }

    start() {
        <span class="hljs-comment">// Arrow function preserves 'this'</span>
        <span class="hljs-built_in">this</span>.intervalId = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
            <span class="hljs-built_in">this</span>.seconds++;
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Time: <span class="hljs-subst">${<span class="hljs-built_in">this</span>.seconds}</span>s`</span>);
        }, <span class="hljs-number">1000</span>);
    }

    stop() {
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.intervalId) {
            <span class="hljs-built_in">clearInterval</span>(<span class="hljs-built_in">this</span>.intervalId);
            <span class="hljs-built_in">this</span>.intervalId = <span class="hljs-literal">null</span>;
        }
    }
}
</code></pre>
<h3 id="heading-3-avoid-mixing-arrow-functions-and-regular-functions">3. Avoid Mixing Arrow Functions and Regular Functions</h3>
<p>Be consistent in your approach:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Good - consistent use of arrow functions</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Calculator</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-built_in">this</span>.result = <span class="hljs-number">0</span>;
    }

    add = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> {
        <span class="hljs-built_in">this</span>.result += num;
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }

    multiply = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> {
        <span class="hljs-built_in">this</span>.result *= num;
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }

    getResult = <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.result;
    }
}

<span class="hljs-comment">// Or consistent use of regular functions with proper binding</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CalculatorRegular</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-built_in">this</span>.result = <span class="hljs-number">0</span>;

        <span class="hljs-comment">// Bind methods in constructor</span>
        <span class="hljs-built_in">this</span>.add = <span class="hljs-built_in">this</span>.add.bind(<span class="hljs-built_in">this</span>);
        <span class="hljs-built_in">this</span>.multiply = <span class="hljs-built_in">this</span>.multiply.bind(<span class="hljs-built_in">this</span>);
    }

    add(num) {
        <span class="hljs-built_in">this</span>.result += num;
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }

    multiply(num) {
        <span class="hljs-built_in">this</span>.result *= num;
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>;
    }
}
</code></pre>
<h3 id="heading-4-use-strict-mode">4. Use Strict Mode</h3>
<p>Always use strict mode to catch <code>this</code> related errors:</p>
<pre><code class="lang-javascript">j<span class="hljs-string">'use strict'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>); <span class="hljs-comment">// undefined in strict mode, global object in non-strict</span>
}
</code></pre>
<h2 id="heading-modern-javascript-and-this">Modern JavaScript and 'this'</h2>
<h3 id="heading-1-react-components">1. React Components</h3>
<p>Understanding <code>this</code> is crucial for React class components. In React class components, proper <code>this</code> binding is essential because event handlers and lifecycle methods need access to component state and props. Incorrect binding leads to runtime errors when trying to call <code>this.setState()</code> or access <code>this.props</code>.</p>
<p>This is challenging because React doesn't automatically bind methods to component instances. When you pass a method as a prop (like <code>onClick={this.handleClick}</code>), the method loses its component context because it's called by React event system, not directly by your component.</p>
<p>Understanding <code>this</code> in React affects:</p>
<ul>
<li><p>Event handler functionality</p>
</li>
<li><p>State updates and component re-rendering</p>
</li>
<li><p>Access to props and lifecycle methods</p>
</li>
<li><p>Performance (incorrect binding creates new functions on each render)</p>
</li>
<li><p>Debugging (context loss creates confusing error messages)</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TodoList</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
    <span class="hljs-keyword">constructor</span>(props) {
        <span class="hljs-built_in">super</span>(props);
        <span class="hljs-built_in">this</span>.state = {
            <span class="hljs-attr">todos</span>: [],
            <span class="hljs-attr">inputValue</span>: <span class="hljs-string">''</span>
        };

        <span class="hljs-comment">// Bind methods in constructor</span>
        <span class="hljs-built_in">this</span>.handleInputChange = <span class="hljs-built_in">this</span>.handleInputChange.bind(<span class="hljs-built_in">this</span>);
        <span class="hljs-built_in">this</span>.addTodo = <span class="hljs-built_in">this</span>.addTodo.bind(<span class="hljs-built_in">this</span>);
    }

    <span class="hljs-comment">// Or use arrow functions as class properties</span>
    handleInputChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
        <span class="hljs-built_in">this</span>.setState({ <span class="hljs-attr">inputValue</span>: event.target.value });
    }

    addTodo = <span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">this</span>.state.inputValue.trim()) {
            <span class="hljs-built_in">this</span>.setState({
                <span class="hljs-attr">todos</span>: [...this.state.todos, <span class="hljs-built_in">this</span>.state.inputValue],
                <span class="hljs-attr">inputValue</span>: <span class="hljs-string">''</span>
            });
        }
    }

    render() {
        <span class="hljs-keyword">return</span> (
            <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">input</span> 
                    <span class="hljs-attr">value</span>=<span class="hljs-string">{this.state.inputValue}</span>
                    <span class="hljs-attr">onChange</span>=<span class="hljs-string">{this.handleInputChange}</span>
                /&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.addTodo}</span>&gt;</span>Add Todo<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
                    {this.state.todos.map((todo, index) =&gt; (
                        <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{index}</span>&gt;</span>{todo}<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
                    ))}
                <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
        );
    }
}
</code></pre>
<h3 id="heading-2-nodejs-and-this">2. Node.js and 'this'</h3>
<p>In Node.js, <code>this</code> behavior depends on the context. Node has unique <code>this</code> behavior due to its module system and execution environment. Unlike browsers, where global <code>this</code> refers to <code>window</code>, Node.js has different global context rules that affect how your code behaves.</p>
<p><strong>Key differences in Node.js</strong>:</p>
<ul>
<li><p><strong>Module level</strong>: <code>this</code> refers to <code>module.exports</code>, not a global object</p>
</li>
<li><p><strong>Function context</strong>: Global <code>this</code> is different from browser environments</p>
</li>
<li><p><strong>CommonJS vs ES modules</strong>: Different <code>this</code> binding rules</p>
</li>
<li><p><strong>REPL vs file execution</strong>: Context changes between interactive and file-based execution</p>
</li>
</ul>
<p><strong>Why this is important</strong>:</p>
<ul>
<li><p>It affects how you structure modules and exports</p>
</li>
<li><p>It changes debugging strategies for context-related issues</p>
</li>
<li><p>It influences how you write universal code that runs in both browsers and Node.js</p>
</li>
<li><p>It impacts testing strategies since test frameworks may change context</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-comment">// In a module, 'this' at the top level refers to module.exports</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span> === <span class="hljs-built_in">module</span>.exports); <span class="hljs-comment">// true</span>

<span class="hljs-comment">// In a function, 'this' depends on how it's called</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">nodeFunction</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>); <span class="hljs-comment">// undefined in strict mode, global object otherwise</span>
}

<span class="hljs-comment">// In a class, 'this' works the same as in browsers</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">NodeClass</span> </span>{
    <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-built_in">this</span>.property = <span class="hljs-string">'value'</span>;
    }

    method() {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>.property); <span class="hljs-comment">// 'value'</span>
    }
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The <code>this</code> keyword in JavaScript is a powerful feature that enables dynamic object-oriented programming. While it can be confusing at first, understanding the four binding rules and when to use each approach will make you a more effective JavaScript developer.</p>
<p><strong>Key Takeaways:</strong></p>
<ol>
<li><p><code>this</code> is determined by how a function is called, not where it's defined</p>
</li>
<li><p><strong>The four rules (in order of precedence): explicit binding, implicit binding, new binding, default binding</strong></p>
</li>
<li><p><strong>Arrow functions inherit</strong> <code>this</code> from their enclosing scope</p>
</li>
<li><p><strong>Use</strong> <code>bind()</code>, <code>call()</code>, or <code>apply()</code> when you need explicit control</p>
</li>
<li><p><strong>Arrow functions are perfect for callbacks and event handlers</strong></p>
</li>
<li><p><strong>Always use strict mode to catch</strong> <code>this</code> related errors</p>
</li>
<li><p><strong>Be consistent in your approach within a codebase</strong></p>
</li>
</ol>
<p><strong>When to Use</strong> <code>this</code>:</p>
<ul>
<li><p>Object-oriented programming with classes and constructors</p>
</li>
<li><p>Event handling where you need to access object state</p>
</li>
<li><p>Method chaining patterns</p>
</li>
<li><p>Creating reusable components and libraries</p>
</li>
<li><p>React class components and similar frameworks</p>
</li>
</ul>
<p><strong>When NOT to Use</strong> <code>this</code>:</p>
<ul>
<li><p>Pure utility functions</p>
</li>
<li><p>Functional programming patterns</p>
</li>
<li><p>Simple event handlers without state</p>
</li>
<li><p>Functions that don't need object context</p>
</li>
</ul>
<p>Mastering <code>this</code> will help you write more maintainable, reusable, and professional JavaScript code. Practice with different scenarios, and always remember that context is king when it comes to understanding what <code>this</code> refers to in any given situation.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Fetch API vs. Axios vs. Alova: Which HTTP Client Should You Use in 2025? ]]>
                </title>
                <description>
                    <![CDATA[ Before the days of the Fetch API and Axios, developers used callback-based HTTP requests. They manually managed requests with asynchronous operations and, in the process, wrote deeply nested code. This was known as callback hell. Then, in 2015, a pro... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/fetch-api-vs-axios-vs-alova/</link>
                <guid isPermaLink="false">67ed4e54f03ad9ca955f36d0</guid>
                
                    <category>
                        <![CDATA[ Alova ]]>
                    </category>
                
                    <category>
                        <![CDATA[ XHP ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ javascript framework ]]>
                    </category>
                
                    <category>
                        <![CDATA[ js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ blob ]]>
                    </category>
                
                    <category>
                        <![CDATA[ axios ]]>
                    </category>
                
                    <category>
                        <![CDATA[ fetch API ]]>
                    </category>
                
                    <category>
                        <![CDATA[ fetching apis ]]>
                    </category>
                
                    <category>
                        <![CDATA[ APIs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ API basics  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ API ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Abdullah Salaudeen ]]>
                </dc:creator>
                <pubDate>Wed, 02 Apr 2025 14:48:52 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1743605319873/9f7583a0-1b01-4714-9fe6-f39bed3954e8.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Before the days of the Fetch API and Axios, developers used callback-based HTTP requests. They manually managed requests with asynchronous operations and, in the process, wrote deeply nested code. This was known as callback hell.</p>
<p>Then, in 2015, a promise-based API request, the Fetch API, was built into JavaScript ES6 to ease the process. After that, libraries like Axios and Alova also appeared.</p>
<p>But why would anyone consider using a third-party API when the lightweight inbuilt Fetch API is an effective option? Well, Axios and Alova provide more than just fetching simple JSON responses. While Axios automates the parsing of JSON and provides shorthand methods for requests, Alova caches responses which prevents making new requests that are redundant.</p>
<p>So which should you stick to – Fetch API, Axios, or Alova? </p>
<p>In this guide, we’ll examine each of these tools based on their features, performance, and project suitability. Walk with me…</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-fetch-api">The Fetch API</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-key-features-of-the-fetch-api">Key Features of the Fetch API</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-limitations-of-the-fetch-api">Limitations of the Fetch API</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-axios">Axios</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-key-features-of-axios">Key Features of Axios</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-limitations-of-axios">Limitations of Axios</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-alova">Alova</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-key-features-of-alova">Key Features of Alova</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-limitations-of-alova">Limitations of Alova</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-feature-by-feature-comparison">Feature-by-Feature Comparison</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-cases-and-best-scenarios">Use Cases and Best Scenarios</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-when-to-use-fetch-api">When to Use Fetch API</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-axios">When to Use Axios</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-alova">When to Use Alova</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-community-and-ecosystem">Community and Ecosystem</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-ecosystem-and-integrations">Ecosystem and Integrations</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ol>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before you start this tutorial, you should have a basic understanding of JavaScript and ES6+ features, such as <a target="_blank" href="https://www.freecodecamp.org/news/javascript-async-await/"><code>async/await</code></a>, <a target="_blank" href="https://www.freecodecamp.org/news/javascript-arrow-functions-in-depth/">arrow functions</a>, and <a target="_blank" href="https://salaudeenabdu.hashnode.dev/destructuring-in-javascript">object destructuring</a>. Being familiar with the <code>fetch()</code> API will also be helpful, as we’ll compare it with Axios and Alova.</p>
<p>You should also have a fundamental knowledge of HTTP methods (GET, POST, PUT, DELETE, PATCH) and handling API responses based on status codes to better understand the API examples.</p>
<p>While this tutorial focuses on JavaScript, some examples use React. So you should be familiar with React and understand the basics of components, state, and hooks (like <code>useState</code> and <code>useEffect</code>). Alova also works with frameworks like Vue and Svelte.</p>
<p>Basic experience with package managers (NPM or Yarn) is useful for installing dependencies like Axios and Alova. And understanding Node.js and browser environments will help, as Alova works in both contexts.</p>
<p>Lastly, familiarity with state management and caching concepts will enhance your understanding of Alova’s features, as it integrates state management and caching directly into API requests.</p>
<h2 id="heading-the-fetch-api"><strong>The Fetch API</strong></h2>
<p>Fetch API is a promise-based API request feature in JavaScript that was released to replace the old callback-based XMLHttpRequest (XHP). Unlike the old tool, Fetch API is compatible with modern website features, including <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API">service workers</a> and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS">Cross-Origin Resource Sharing (CORS)</a>. </p>
<p>With this tool, calling API data is as simple as making a fetch() request on the API URL, as shown below:  </p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">"https://fakestoreapi.com/products"</span>)
</code></pre>
<p>The <code>fetch()</code> returns the server’s promise which is fulfilled with a response object. Then, you pass in some optional arguments to configure the response as JSON or text, attach it to a variable, and use the data.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> products;

  fetch(<span class="hljs-string">"https://fakestoreapi.com/products"</span>)

    .then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> res.json())

    .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {

      products = data

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

    })

    .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>
<p>In the code above, the <code>fetch()</code> requests API data from the URL. The response <code>res</code> gets parsed as JSON <code>res.json</code>. Then, the resulting data is attached to the <code>products</code> variable and logged on the console.  </p>
<p>Since Node.js v17.5, the Fetch API has been available natively, eliminating the reliance on external packages like <code>node-fetch</code>, <code>got</code>, or <code>cross-fetch</code> for handling HTTP requests. This native support in both browsers and Node.js removes the need for additional dependencies, reducing the overall bundle size of your application. With this built-in functionality, the Fetch API has become the go-to tool for making asynchronous API calls in JavaScript applications.</p>
<h3 id="heading-key-features-of-the-fetch-api">Key Features of the Fetch API</h3>
<h4 id="heading-promises-based-syntax">Promises-based syntax</h4>
<p>As I mentioned earlier, the Fetch API uses a promise-based syntax that sends a promise from the server and executes it with a response object. While the <code>.then</code> chaining can be optimal for simple requests, using several <code>.then</code>s can lead to callback hell and give you a hard time tracking errors. This is why the <code>async/await</code> alternative is a more optimal solution. Check out the code example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {

      <span class="hljs-keyword">try</span> {

        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://fakestoreapi.com/products"</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">`HTTP error! Status: <span class="hljs-subst">${response.status}</span>`</span>);

        }

        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();

        products = data

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

      } <span class="hljs-keyword">catch</span> (error) {

        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error fetching data:"</span>, error);

      }

    };

    fetchData();
</code></pre>
<p>As shown above, the fetch makes a get request. Then, the server returns an error status if the response is not ok (returns an error status like <code>error 404</code>). Then, the response gets parsed as JSON and used. </p>
<p>Keep in mind that all methods passed on the response are asynchronous, including the <code>fetch()</code> and the <code>json()</code> parsing.</p>
<h4 id="heading-supports-the-get-post-put-patch-and-delete-methods">Supports the <code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>PATCH</code> and <code>DELETE</code> methods</h4>
<p><code>GET</code>, used to receive responses, is the Fetch API’s default method. So when you’re using it, you don’t have to define it explicitly or attach a body. But for methods that send requests like <code>POST</code>, <code>PUT</code>, <code>PATCH</code> and <code>DELETE</code>, you must specify their method and attach a body. </p>
<p>All these methods send requests to the backend. You can send data to the server with <code>POST</code>,  completely replace an existing resource with new data using <code>PUT</code>, partially update with <code>PATCH</code>, or remove the resource with <code>DELETE</code>.  </p>
<ol>
<li><strong>Here’s how you can define a method:</strong></li>
</ol>
<p>In the code below, I set the POST method to send data to the specified API: </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://example.com/products1"</span>, {

          <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>

          <span class="hljs-comment">//...</span>

        });
</code></pre>
<p>Apart from posting data, you can also clear data on the server using <code>DELETE</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://example.com/products1"</span>, {

      <span class="hljs-attr">method</span>: <span class="hljs-string">"DELETE"</span>

      <span class="hljs-comment">//...</span>

    });
</code></pre>
<ol start="2">
<li><strong>Then, define the header:</strong></li>
</ol>
<p>Defining the header lets the server understand the type of content you are sending for proper data handling. As shown here, the header asks the server to store the content as a JSON file and set the authorization token to <code>my-classified-token</code><em>.</em> Keep in mind that the token is the API key that will be used to verify user identity upon use.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://example.com/products1"</span>, {

          <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,

          <span class="hljs-attr">header</span>: {

            <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application-json"</span>,

            <span class="hljs-string">"Authorization"</span>: <span class="hljs-string">"Bearer my-classified-token"</span>,

          }

          <span class="hljs-comment">//..</span>

        });
</code></pre>
<p>Here is a full list of parameters that can be passed into the header:</p>
<table><tbody><tr><td><p><strong>Header</strong></p></td><td><p><strong>Purpose</strong></p></td></tr><tr><td><p>"Content-Type": "application/json"</p></td><td><p>Tells the server that the request body is in JSON format.</p></td></tr><tr><td><p>"Authorization": "Bearer token"</p></td><td><p>Provides authentication (API keys, JWT, OAuth tokens).</p></td></tr><tr><td><p>"Accept": "application/json"</p></td><td><p>Specifies that the client expects a JSON response.</p></td></tr><tr><td><p>"Content-Type": "application/x-www-form-urlencoded"</p></td><td><p>Used for sending form data instead of JSON.</p></td></tr><tr><td><p>"Origin": "http://example.com"</p></td><td><p>Indicates where the request is coming from (used in CORS).</p></td></tr></tbody></table>

<ol start="3">
<li><strong>Next, attach the body:</strong></li>
</ol>
<p>After specifying the header, you then attach the body. The body is the data being sent to the backend server. It cannot be used with the GET method which only fetches responses. Besides, the information attached should always be in a valid format that matches the content type specified in the headers. You can add as much value as you require to the body.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">"https://example.com/products1"</span>, {

          <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,

          <span class="hljs-attr">header</span>: {

            <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application-json"</span>,

            <span class="hljs-string">"Authorization"</span>: <span class="hljs-string">"Bearer my-classified-token"</span>,

          },

          <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">name</span>: <span class="hljs-string">"Laptop"</span>, <span class="hljs-attr">price</span>: <span class="hljs-number">1200</span> })

        });
</code></pre>
<h4 id="heading-streaming-data">Streaming Data</h4>
<p>It is also worth noting that the Fetch API facilitates large data handling via streaming. It receives copious data in chunks instead of loading the whole data and buffering in the process. So it data displays real-time as they arrive. Here is a simple example of streaming:</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {

<span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://www.example.com/large-text-file.txt'</span>);

      <span class="hljs-keyword">const</span> reader = response.body.getReader();

      <span class="hljs-keyword">const</span> decoder = <span class="hljs-keyword">new</span> TextDecoder();

      <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {

        <span class="hljs-keyword">const</span> { done, value } = <span class="hljs-keyword">await</span> reader.read();

        <span class="hljs-keyword">if</span> (done) <span class="hljs-keyword">break</span>;

        <span class="hljs-keyword">const</span> chunk = decoder.decode(value, { <span class="hljs-attr">stream</span>: <span class="hljs-literal">true</span> });

        <span class="hljs-built_in">console</span>.log(chunk); <span class="hljs-comment">// Process the chunk (e.g., display it in UI)</span>

      }

      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Stream complete'</span>);

    }

    fetchData();
</code></pre>
<h4 id="heading-fetching-documents-with-the-dom-parser">Fetching Documents with the DOM Parser</h4>
<p>Unlike its predecessor, XHP, which can directly return a document, Fetch API can’t achieve the same results without using the DOM Parser. To use it, you have to set the response type to text, then convert to a document using the DOMParser. Here is an example:</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">"example.xml"</span>)

  .then(<span class="hljs-function"><span class="hljs-params">res</span> =&gt;</span> res.text()) <span class="hljs-comment">// Get raw text</span>

  .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> {

    <span class="hljs-keyword">const</span> parser = <span class="hljs-keyword">new</span> DOMParser();

    <span class="hljs-keyword">const</span> doc = parser.parseFromString(data, <span class="hljs-string">"text/xml"</span>); <span class="hljs-comment">// Convert text to Document</span>

    <span class="hljs-built_in">console</span>.log(doc); <span class="hljs-comment">// Now it's a Document object</span>

  })

  .catch(<span class="hljs-built_in">console</span>.error);
</code></pre>
<h4 id="heading-request-cancellation-with-abortcontroller">Request Cancellation with AbortController</h4>
<p>Previously, the Fetch API couldn’t abort requests. But it is now possible with <code>AbortController</code> and <code>AbortSignal</code>. But the AbortController API is not native either, which means there is extra bundle and set up required. </p>
<h3 id="heading-limitations-of-the-fetch-api"><strong>Limitations of the Fetch API</strong></h3>
<h4 id="heading-response-flexibility-or-no-automatic-json-parsing">Response Flexibility or No automatic JSON parsing</h4>
<p>Depends on how you see it. Having to specify whether you want your response as JSON <code>res.json()</code> or text <code>res.text()</code> or blob <code>res.blob()</code> lets you set which response type you want from the get go. But it can also be a limitation since most API fetches are in JSON. This means that alternatives like Axios, which sets defaults as <code>res.json()</code>, helps write shorter and cleaner code, and is therefore often preferred by developers. </p>
<h4 id="heading-no-built-in-requestresponse-interceptors">No built-in request/response interceptors</h4>
<p>Unlike Axios, Fetch API does not have built-in methods that intercept and modify requests or responses. This limitation means you have to write boilerplate code to create a custom interceptor.</p>
<p>For instance, via interception, you can attach an Authorization token automatically before sending requests or asking all 401 errors to automatically reload when receiving responses. With the Fetch API, you have to wrap the <code>fetch()</code> in a function to do that, which means more lines of code.</p>
<p>Here is some code built to mimic request/ response interception:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> customFetch = <span class="hljs-keyword">async</span> (url, options = {}) =&gt; {

      <span class="hljs-comment">// Request Interception</span>

      <span class="hljs-keyword">const</span> modifiedOptions = {

          ...options,

          <span class="hljs-attr">headers</span>: {

              <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,

              <span class="hljs-attr">Authorization</span>: Bearer ${<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"token"</span>)}, <span class="hljs-comment">// Interceptor behavior</span>

              ...options.headers

          }

      };



      <span class="hljs-keyword">try</span> {

          <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url, modifiedOptions);



          <span class="hljs-comment">// Response Interception</span>

          <span class="hljs-keyword">if</span> (!response.ok) {

              <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Intercepted Error:"</span>, response.status);

          }



          <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> response.json();

      } <span class="hljs-keyword">catch</span> (error) {

          <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Fetch error intercepted:"</span>, error);

          <span class="hljs-keyword">throw</span> error;

      }

  };

  <span class="hljs-comment">// Usage (No need to set headers manually)</span>

  customFetch(<span class="hljs-string">'https://api.example.com/data'</span>)

      .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data))

      .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<h4 id="heading-error-handling-requires-additional-logic">Error handling requires additional logic</h4>
<p>The Fetch API only rejects network errors, not failed HTTP status codes like 404 or 501. This means that when a fetching request fails, it does not return a  <code>404 Not Found</code> or <code>500 Internal Server Error</code> unless you configure that with additional code. But Axios does.  </p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://jsonplaceholder.typicode.com/invalid-url'</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-comment">// Manually handle non-2xx responses</span>

      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`HTTP Error! Status: <span class="hljs-subst">${response.status}</span>`</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(data))

  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error:'</span>, error.message));
</code></pre>
<h2 id="heading-axios"><strong>Axios</strong></h2>
<p>After XHP was replaced with the Fetch API, <a target="_blank" href="https://axios-http.com/docs/intro">Axios</a> emerged in 2016 to address some issues with the new JavaScript-native fetching tool. Built on top of XHP, Axios quickly gained widespread adoption due to combining many Fetch API promise-based features with some methods on the legacy XMLHttpRequest. In no time, it became a popular choice amongst developers.</p>
<p>Axios stands out because it:</p>
<ul>
<li><p>Automates JSON parsing</p>
</li>
<li><p>Has a built-in method to intercept and modify requests and responses </p>
</li>
<li><p>Automates error handling </p>
</li>
<li><p>Automates timeout handling</p>
</li>
<li><p>Can track upload and download progress</p>
</li>
</ul>
<p>And many more features.</p>
<p>In particular, Axios is widely loved because it reduces boilerplate code. Since most API requests encode data with <code>JSON</code>, Axios sets its default parsing to accordingly, which means you don’t have to define <code>JSON</code> again. And why worry anyway, since developers use far fewer <code>res.text()</code> and <code>res.blob()</code> API responses in comparison.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {

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

    <span class="hljs-built_in">console</span>.log(response.data); <span class="hljs-comment">// JSON is already parsed</span>

  };
</code></pre>
<p>Now, compare that to a like-for-like fetching with Fetch API:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {

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

    <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json(); <span class="hljs-comment">// Extra step</span>

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

  };
</code></pre>
<p>Yeah, there’s an extra line, right? That could mean several lines of code for larger codebases. </p>
<h3 id="heading-key-features-of-axios"><strong>Key Features of Axios</strong></h3>
<h4 id="heading-automatic-json-parsing">Automatic JSON Parsing</h4>
<p>As explained above, you don’t have to call <code>res.json()</code> again while using Axios, since the method is automatically set. But what happens, in rare cases, when you want to fetch a blob or text using Axios? Then, you have to set the response type accordingly. Here’s how you can do that:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fetchData = <span class="hljs-keyword">async</span> () =&gt; {
    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">'https://api.example.com/data'</span>, {
      <span class="hljs-attr">responseType</span>: <span class="hljs-string">'text'</span>, <span class="hljs-comment">// Treats response as plain text</span>
    });

    <span class="hljs-built_in">console</span>.log(response.data); <span class="hljs-comment">// Plain text string</span>
  };
</code></pre>
<h4 id="heading-built-in-interceptors-to-modify-requests-and-responses">Built-in Interceptors to Modify Requests and Responses</h4>
<p>Axios comes with its built-in interceptors to intercept and modify API responses or requests. Interceptors can help set authorization tokens for requests or modify global responses and errors before they render. Use the <code>.interceptors.request.use()</code> for requests and <code>.interceptors.response.use()</code> for responses. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">"axios"</span>;

  <span class="hljs-keyword">const</span> apiClient = axios.create({

      <span class="hljs-attr">baseURL</span>: <span class="hljs-string">"https://api.example.com"</span>,

      <span class="hljs-attr">headers</span>: {

          <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>

      }

  });



  <span class="hljs-comment">// Request Interceptor: Attach Authorization headers</span>

  apiClient.interceptors.request.use(<span class="hljs-function"><span class="hljs-params">config</span> =&gt;</span> {

      config.headers.Authorization = Bearer ${<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"token"</span>)};

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

  }, <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">Promise</span>.reject(error));

  <span class="hljs-comment">// Usage: Axios automatically includes the Authorization header</span>

  apiClient.get(<span class="hljs-string">"/data"</span>)

      .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))

      .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<p>To achieve that with Fetch API, you will have to write an interceptor wrapper on your API, which needs far more boilerplate code.</p>
<h4 id="heading-request-cancellation-with-canceltoken">Request cancellation with CancelToken</h4>
<p>Although now deprecated, Axios used to have its native request cancellation method known as <code>CancelToken</code>. But now, the <code>AbortController</code> API is regarded as a globally-recognized and reliable method for request abortion.</p>
<h4 id="heading-error-handling">Error Handling</h4>
<p>Axios handles errors better by automatically rejecting all non-2xx status codes like <code>Error 404</code> and <code>501</code>. You do not need to check any <code>response.ok</code> message:</p>
<pre><code class="lang-javascript">axios.get(<span class="hljs-string">'https://jsonplaceholder.typicode.com/invalid-url'</span>)

  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))

  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> {

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error Status:'</span>, error.response?.status); <span class="hljs-comment">// Axios auto-rejects non-2xx responses</span>

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error Message:'</span>, error.message);

  });
</code></pre>
<h4 id="heading-built-in-progress-tracking">Built-in Progress Tracking</h4>
<p>Axios incorporates XHP methods like <code>onDownloadProgress</code> and <code>onUploadProgress</code>. This inbuilt feature facilitates tracking download and uploads progress. Whereas with the Fetch API, you’d need <code>ReadableStream</code> to achieve similar results. </p>
<p>Here is an example showing how you can use <code>onUploadProgress</code>: </p>
<pre><code class="lang-javascript">axios.post(url, data, {

    <span class="hljs-attr">onUploadProgress</span>: <span class="hljs-function"><span class="hljs-params">progressEvent</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(progressEvent.loaded)

  });
</code></pre>
<h4 id="heading-supports-other-methods-too">Supports Other Methods, too</h4>
<p>Just like the Fetch API, Axios’ default Method is <code>GET</code>. But you can use the <code>POST</code>, <code>PUT</code>, <code>PATCH</code> or <code>DELETE</code> methods using <code>axios.request()</code>. Here’s how:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">"axios"</span>;

  axios.request({

      <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,

      <span class="hljs-attr">url</span>: <span class="hljs-string">"https://api.example.com/users"</span>,

      <span class="hljs-attr">body</span>: { <span class="hljs-attr">name</span>: <span class="hljs-string">"Abdullah"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> }, <span class="hljs-comment">// Request body</span>

      <span class="hljs-attr">headers</span>: {

          <span class="hljs-string">"Authorization"</span>: Bearer ${<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"token"</span>)},

          <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>

      }

  })

  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))

  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Axios Request Error:"</span>, error));
</code></pre>
<p>Axios also provides a shorthand with methods like <code>axios.get</code>, <code>axios.post</code>, <code>axios.put</code>, <code>axios.patch</code>, and <code>axios.delete</code>, as shown below:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// POST Request</span>

axios.post(<span class="hljs-string">"https://api.example.com/users"</span>,

  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Abdullah"</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">25</span> }, <span class="hljs-comment">// Request body</span>

  { <span class="hljs-attr">headers</span>: { <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span> } }

)

.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))

.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Axios POST Error:"</span>, error));

<span class="hljs-comment">// PUT Request</span>

axios.put(<span class="hljs-string">"https://api.example.com/users/123"</span>,

  { <span class="hljs-attr">name</span>: <span class="hljs-string">"Updated Name"</span> }, <span class="hljs-comment">// Updated data</span>

  { <span class="hljs-attr">headers</span>: { <span class="hljs-string">"Authorization"</span>: Bearer ${<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"token"</span>)} } }

)

.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))

.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Axios PUT Error:"</span>, error));

<span class="hljs-comment">// DELETE Request</span>

axios.delete(<span class="hljs-string">"https://api.example.com/users/123"</span>, {

  <span class="hljs-attr">headers</span>: { <span class="hljs-string">"Authorization"</span>: Bearer ${<span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">"token"</span>)} }

})

.then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"User deleted successfully"</span>))

.catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Axios DELETE Error:"</span>, error));
</code></pre>
<h3 id="heading-limitations-of-axios"><strong>Limitations of Axios</strong></h3>
<h4 id="heading-slightly-larger-bundle-size">Slightly larger bundle size</h4>
<p>Axios <a target="_blank" href="https://bundlephobia.com/package/axios@1.8.4">adds 35 kb</a> of extra bundle, while FetchAPI adds 0. While Axios clearly offers more features than Fetch in every other metric, you have to make do with the larger bundle size. And in an age where lightweight and fast applications are often preferred, you might not want that load.</p>
<h4 id="heading-dependency-on-third-party-maintenance">Dependency on third-party maintenance</h4>
<p>Depending on a third-party option for something as crucial as API might not be desirable. So a native tool like the Fetch API, built within JavaScript, offers more reliability.</p>
<h2 id="heading-alova"><strong>Alova</strong></h2>
<p><a target="_blank" href="https://github.com/alovajs/alova">Alova</a> is a request management library that combines simple API fetching with other functionalities like state management, hooks, and caching, amongst many others.</p>
<p>While we use <code>react-query</code> and <code>SWR</code> to process Axios-fetched data, Alova saves you those extra installations and coding by providing these methods natively. The all-in-one alternative not only fetches responses and sends requests, but also merges requests, caches responses, and optimizes them for UI frameworks. </p>
<p>Built in 2022, Alova’s adoption is still early but nonetheless seems promising. It is supported on browsers, Node.js, and most frameworks, including Vue, React, Svelte, and vanilla JavaScript. But it has limited usage for Angular.js.</p>
<p><a target="_blank" href="https://bundlephobia.com/package/alova@2.6.1">At just 10kb</a>, it is about 3 times smaller than Axios, making it a more lightweight alternative for building fast applications. </p>
<p>You can also use Alova to either replace react-query to facilitate Axios or be the one-stop-shop for everything API integration-related. </p>
<p>Here is a simple Alova fetch:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> alovaInstance.Get(<span class="hljs-string">'https://jsonplaceholder.typicode.com'</span>).send();

<span class="hljs-built_in">console</span>.log(response); <span class="hljs-comment">// Response data</span>
</code></pre>
<p>When you are fetching Alova on React components, you can use the <code>createAlova()</code> to set parameters and <code>useRequest()</code> to manage state. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">import</span> { createAlova, useRequest } <span class="hljs-keyword">from</span> <span class="hljs-string">"alova"</span>;

<span class="hljs-keyword">import</span> GlobalFetch <span class="hljs-keyword">from</span> <span class="hljs-string">"alova/GlobalFetch"</span>;

<span class="hljs-comment">// Initialize Alova</span>

<span class="hljs-keyword">const</span> alovaInstance = createAlova({

  <span class="hljs-attr">statesHook</span>: React,

  <span class="hljs-attr">requestAdapter</span>: GlobalFetch(),

});

<span class="hljs-comment">// GET request with useRequest</span>

<span class="hljs-keyword">const</span> Profile = <span class="hljs-function">() =&gt;</span> {

  <span class="hljs-keyword">const</span> { data, loading, error } = useRequest(<span class="hljs-function">() =&gt;</span> alovaInstance.Get(<span class="hljs-string">"https://jsonplaceholder.typicode.com"</span>));

  <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;

  <span class="hljs-keyword">if</span> (error) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Error fetching profile<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Username: {data.username}<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;

};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Profile;
</code></pre>
<h3 id="heading-key-features-of-alova"><strong>Key Features of Alova</strong></h3>
<h4 id="heading-one-stop-shop">One-Stop Shop</h4>
<p>For some functionalities that come built into Alova, Fetch API or Axios might need additional libraries like <code>react-query</code> or <code>SWR</code> to fulfill. </p>
<h4 id="heading-request-sharing-prevents-redundant-requests">Request Sharing Prevents Redundant Requests</h4>
<p>Alova fuses identical requests. Let’s say several components ask for the same data from the API. The Fetch API and Axios send multiple identical requests to the server which creates traffic. But Alova merges them, sends a single request, and shares its response across all components, which reduces network traffic.</p>
<h4 id="heading-state-management">State Management</h4>
<p>With tools like Fetch API and Axios, you have to manage data, loading, and error states manually. Alova lets you do that on the go within a single line of code. Here is how it looks:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//...</span>

<span class="hljs-keyword">const</span> { data, loading, error } = useRequest(alova.Get(<span class="hljs-string">"/posts/1"</span>));

<span class="hljs-comment">//...</span>
</code></pre>
<h4 id="heading-advanced-request-management">Advanced Request Management</h4>
<p>Alova offers several request management functionalities with each tailored to specific use cases. With its request management, you can request preload for data to be used later, cache data to prevent reload, manage form submission, handle pagination, and automate refetching when needed. Check out their docs to <a target="_blank" href="https://alova.js.org/tutorial/client/strategy/">read more</a>. </p>
<h4 id="heading-multi-level-caching">Multi-Level Caching</h4>
<p>You can also use Alova to cache data, especially when the response isn’t constantly changing and does not need refetching. Unlike <code>react-query</code> that simply stores caches in RAM, Alova offers a more flexible framework. </p>
<p>Its three-pronged caching modes include the memory mode, cache occupying mode, and recovery mode. While memory mode stores data in the RAM, recovery mode persistently stores it in a Local Storage and is made available for longer periods and even offline. Meanwhile, the occupying mode prevents duplicate or redundant requests coming in quick succession. </p>
<p>Independent on any component, cached data can be accessed anywhere in the app if the request URL and parameters match. These features lower traffic going to servers, reduce buffering, and help facilitating a swifter and better user experience.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//...</span>

<span class="hljs-comment">// Initialize Alova instance</span>

<span class="hljs-keyword">const</span> alovaInstance = createAlova({

  <span class="hljs-attr">baseURL</span>: <span class="hljs-string">"https://jsonplaceholder.typicode.com"</span>,

  <span class="hljs-attr">statesHook</span>: React,

  <span class="hljs-attr">requestAdapter</span>: GlobalFetch(),

});

<span class="hljs-comment">// Define GET request</span>

<span class="hljs-keyword">const</span> getPosts = alovaInstance.Get(<span class="hljs-string">"/posts"</span>, {

  <span class="hljs-attr">cache</span>: {

    <span class="hljs-attr">mode</span>: <span class="hljs-string">"memory"</span>, <span class="hljs-comment">// Caches in memory</span>

    <span class="hljs-attr">expires</span>: <span class="hljs-number">1000</span> * <span class="hljs-number">60</span> * <span class="hljs-number">5</span>, <span class="hljs-comment">// Expires in 5 minutes</span>

  },

});

<span class="hljs-keyword">const</span> PostList = <span class="hljs-function">() =&gt;</span> {

  <span class="hljs-keyword">const</span> { data, loading, error } = useRequest(getPosts);

  <span class="hljs-keyword">if</span> (loading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;

  <span class="hljs-keyword">if</span> (error) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Error fetching data<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;

  <span class="hljs-comment">//...</span>

};
</code></pre>
<p>In the example above, Alova caches the response using the memory mode <code>cache: {mode: "memory"}</code> and sets the cache expiration to 5 minutes <code>expires: 1000 * 60 * 5</code><em>.</em> You can change <code>“memory”</code> to <code>“recovery”</code> if you want a longer storage duration. </p>
<h4 id="heading-usage-flexibility">Usage Flexibility</h4>
<p>You can use Alova with either Axios or the Fetch API. Here is an example where I fetched data using Axios and complemented it with Alova state management.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//...</span>

<span class="hljs-comment">// Initialize Alova</span>

<span class="hljs-keyword">const</span> alovaInstance = createAlova({

  <span class="hljs-attr">statesHook</span>: React,

  <span class="hljs-attr">requestAdapter</span>: GlobalFetch(),

});

<span class="hljs-comment">// Manage state with Alova</span>

<span class="hljs-keyword">const</span> { <span class="hljs-attr">data</span>: posts, setData } = useSnapshot([]);

<span class="hljs-keyword">const</span> fetchPosts = <span class="hljs-keyword">async</span> () =&gt; {

  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.get(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts"</span>);

  setData(response.data); <span class="hljs-comment">// Store data in Alova state</span>

};

<span class="hljs-comment">//...</span>
</code></pre>
<h4 id="heading-supports-other-methods">Supports Other Methods</h4>
<p>Alova also makes <code>GET</code> its default option while supporting other methods like <code>POST</code>, <code>PATCH</code>, <code>PUT</code> and <code>DELETE</code>. Here is how to use <code>POST</code> in Alova, for example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">import</span> { createAlova, useRequest } <span class="hljs-keyword">from</span> <span class="hljs-string">"alova"</span>;

<span class="hljs-keyword">import</span> GlobalFetch <span class="hljs-keyword">from</span> <span class="hljs-string">"alova/GlobalFetch"</span>;

<span class="hljs-keyword">const</span> alovaInstance = createAlova({

  <span class="hljs-attr">baseURL</span>: <span class="hljs-string">"https://jsonplaceholder.typicode.com"</span>,

  <span class="hljs-attr">statesHook</span>: React,

  <span class="hljs-attr">requestAdapter</span>: GlobalFetch(),

});

<span class="hljs-keyword">const</span> PostForm = <span class="hljs-function">() =&gt;</span> {

  <span class="hljs-keyword">const</span> [title, setTitle] = useState(<span class="hljs-string">""</span>);

  <span class="hljs-keyword">const</span> { <span class="hljs-attr">send</span>: createPost } = useRequest(alovaInstance.Post(<span class="hljs-string">"/posts"</span>, { title }), { <span class="hljs-attr">immediate</span>: <span class="hljs-literal">false</span> });

  createPost().then(<span class="hljs-built_in">console</span>.log)

};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> PostForm;
</code></pre>
<p>Of course, it has shorthand methods too:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">import</span> { createAlova, useRequest } <span class="hljs-keyword">from</span> <span class="hljs-string">"alova"</span>;

<span class="hljs-keyword">import</span> GlobalFetch <span class="hljs-keyword">from</span> <span class="hljs-string">"alova/GlobalFetch"</span>;

<span class="hljs-keyword">const</span> alova = createAlova({

  <span class="hljs-attr">baseURL</span>: <span class="hljs-string">"https://jsonplaceholder.typicode.com"</span>,

  <span class="hljs-attr">statesHook</span>: React,

  <span class="hljs-attr">requestAdapter</span>: GlobalFetch(),

});

<span class="hljs-keyword">const</span> { <span class="hljs-attr">send</span>: createPost } = useRequest(alova.Post(<span class="hljs-string">"/posts"</span>, { <span class="hljs-attr">title</span>: <span class="hljs-string">"New Post"</span> }), { <span class="hljs-attr">immediate</span>: <span class="hljs-literal">false</span> });

<span class="hljs-keyword">const</span> { <span class="hljs-attr">send</span>: updatePost } = useRequest(alova.Put(<span class="hljs-string">"/posts/1"</span>, { <span class="hljs-attr">title</span>: <span class="hljs-string">"Updated Post"</span> }), { <span class="hljs-attr">immediate</span>: <span class="hljs-literal">false</span> });

<span class="hljs-keyword">const</span> { <span class="hljs-attr">send</span>: patchPost } = useRequest(alova.Patch(<span class="hljs-string">"/posts/1"</span>, { <span class="hljs-attr">title</span>: <span class="hljs-string">"Patched Post"</span> }), { <span class="hljs-attr">immediate</span>: <span class="hljs-literal">false</span> });

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

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

patchPost().then(<span class="hljs-built_in">console</span>.log);
</code></pre>
<h4 id="heading-bundle-size">Bundle Size</h4>
<p>Alova is three times smaller than Axios, but that does not even tell the full story. With Axios and the Fetch API, you need different libraries to handle caching, request deduplication, and retries. But Alova has everything in-built. So using Axios and Fetch API in real code production will always require more bundles than Axios. And overall, Alova facilitates lighter-weight applications compared to Axios and sometimes the Fetch API as well. </p>
<h3 id="heading-limitations-of-alova"><strong>Limitations of Alova</strong></h3>
<h4 id="heading-adoption-is-still-low">Adoption Is Still Low</h4>
<p>While writing this article, I had a hard time getting enough resources on Alova. And that is because it only debuted in July 2022 which means adoption is still early. So, troubleshooting Alova might be problematic since there are fewer Alova-themed API communities, as well as fewer StackOverflow answers, Youtube Tutorials, or GitHub contributions. </p>
<h4 id="heading-potential-stability-amp-long-term-maintenance-risks">Potential Stability &amp; Long-Term Maintenance Risks</h4>
<p>Newer libraries have a higher risk of abandonment. Axios has been around for years, while Alova is still growing. Besides, it has fewer production use cases and battle-tested applications compared to Axios and Fetch.</p>
<h4 id="heading-learning-curve">Learning Curve</h4>
<p>Alova’s learning curve can take some getting used to because it handles API requests differently from tools like Axios or the Fetch API.</p>
<p>Instead of making requests directly, you work with request instances and manage state within Alova’s system. This requires learning new ways to structure API calls and use features like caching and request merging. While it may feel unfamiliar at first, it can help reduce redundant API calls and improve performance once you understand it.</p>
<h4 id="heading-fewer-third-party-integrations">Fewer Third Party Integrations</h4>
<p>Alova has fewer third-party libraries built specifically for it, requiring more manual work for compatibility with existing tools. </p>
<h2 id="heading-feature-by-feature-comparison"><strong>Feature-by-Feature Comparison</strong></h2>
<table><tbody><tr><td><p><strong>Feature</strong></p></td><td><p><strong>Fetch API</strong></p></td><td><p><strong>Axios</strong></p></td><td><p><strong>Alova</strong></p></td></tr><tr><td><p><strong>Ease of Use</strong></p></td><td><p>Medium (requires manual handling)</p></td><td><p>High (user-friendly syntax)</p></td><td><p>Medium (requires new patterns)</p></td></tr><tr><td><p><strong>Performance</strong></p></td><td><p>High (lightweight, native)</p></td><td><p>Medium (slightly larger size)</p></td><td><p>High (optimized for caching &amp; batch requests)</p></td></tr><tr><td><p><strong>JSON Handling</strong></p></td><td><p>Manual parsing (.json())</p></td><td><p>Automatic</p></td><td><p>Automatic</p></td></tr><tr><td><p><strong>Request Cancellation</strong></p></td><td><p>AbortController (manual)</p></td><td><p>Built-in with CancelToken</p></td><td><p>Built-in</p></td></tr><tr><td><p><strong>Interceptors</strong></p></td><td><p>No</p></td><td><p>Yes</p></td><td><p>Yes</p></td></tr><tr><td><p><strong>Timeout Handling</strong></p></td><td><p>No (manual with AbortController)</p></td><td><p>Yes (built-in)</p></td><td><p>Yes (built-in)</p></td></tr><tr><td><p><strong>Data Caching</strong></p></td><td><p>No</p></td><td><p>No (requires third-party caching)</p></td><td><p>Yes (built-in)</p></td></tr><tr><td><p><strong>Retry Mechanism</strong></p></td><td><p>No</p></td><td><p>Yes</p></td><td><p>Yes</p></td></tr><tr><td><p><strong>Error Handling</strong></p></td><td><p>Requires manual handling</p></td><td><p>Automatic rejection for non-2xx status codes</p></td><td><p>Built-in error recovery</p></td></tr><tr><td><p><strong>Browser Support</strong></p></td><td><p>All modern browsers</p></td><td><p>All modern browsers</p></td><td><p>All modern browsers</p></td></tr><tr><td><p><strong>Node.js Support</strong></p></td><td><p>Yes</p></td><td><p>Yes</p></td><td><p>Limited</p></td></tr></tbody></table>

<h2 id="heading-use-cases-and-best-scenarios"><strong>Use Cases and Best Scenarios</strong></h2>
<p>Choosing the right HTTP client for your project depends on several factors, including project complexity, dependencies, and performance considerations. Let’s explore when it’s best to use the Fetch API, Axios, or Alova.</p>
<h3 id="heading-when-to-use-fetch-api">When to Use Fetch API</h3>
<ol>
<li><h4 id="heading-suitable-for-lightweight-projects-and-simple-requests">Suitable for Lightweight Projects and Simple Requests</h4>
</li>
</ol>
<p>The Fetch API is built into modern browsers and is ideal for handling basic HTTP requests without adding dependencies. If your project requires only simple GET, POST, or DELETE requests with minimal configurations, Fetch API is a great choice.</p>
<ol start="2">
<li><h4 id="heading-when-working-in-environments-where-third-party-libraries-are-restricted">When Working in Environments Where Third-Party Libraries Are Restricted</h4>
</li>
</ol>
<p>Certain enterprise or security-sensitive applications may restrict the use of external libraries. Since the Fetch API is built into the browser, it remains a viable option when third-party packages like Axios or Alova are not allowed.</p>
<ol start="3">
<li><h4 id="heading-when-minimal-dependencies-are-preferred">When Minimal Dependencies Are Preferred</h4>
</li>
</ol>
<p>Since Fetch API is native to JavaScript, it does not require installing extra libraries, making it perfect for projects that need to keep dependencies low. This can be particularly beneficial for small lightweight apps or static websites.</p>
<h3 id="heading-when-to-use-axios">When to Use Axios</h3>
<ol>
<li><h4 id="heading-ideal-for-backend-heavy-applications-or-complex-apis">Ideal for Backend-Heavy Applications or Complex APIs</h4>
</li>
</ol>
<p>For projects that require multiple API calls, error handling, and efficient request management, Axios is a solid choice. It allows concurrent requests, request cancellation, and improved control over HTTP headers.</p>
<ol start="2">
<li><h4 id="heading-when-automatic-json-handling-interceptors-and-robust-error-handling-are-needed">When Automatic JSON Handling, Interceptors, and Robust Error Handling Are Needed</h4>
</li>
</ol>
<p>Axios simplifies working with JSON data by automatically parsing responses. It also provides built-in interceptors for request and response transformations, as well as superior error handling compared to Fetch API.</p>
<ol start="3">
<li><h4 id="heading-useful-when-working-with-nodejs-in-full-stack-applications">Useful When Working with Node.js in Full-Stack Applications</h4>
</li>
</ol>
<p>Axios works both in the browser and in Node.js, making it an excellent choice for full-stack applications where a unified API client is needed across the frontend and backend.</p>
<h3 id="heading-when-to-use-alova">When to Use Alova</h3>
<ol>
<li><h4 id="heading-when-working-with-frontend-heavy-applications-react-vue-svelte">When Working with Frontend-Heavy Applications (React, Vue, Svelte)</h4>
</li>
</ol>
<p>Alova integrates well with frontend frameworks and state management tools, making it a great choice for single-page applications (SPAs) that depend on smooth data fetching, pagination, and updates.</p>
<ol start="2">
<li><h4 id="heading-best-for-projects-requiring-optimized-caching-and-data-synchronization">Best for Projects Requiring Optimized Caching and Data Synchronization</h4>
</li>
</ol>
<p>Alova is designed for performance optimization and better caching strategies. It is suitable for applications that rely on real-time data synchronization and need to minimize redundant network requests.</p>
<ol start="3">
<li><h4 id="heading-when-performance-optimization-and-reduced-network-load-are-priorities">When Performance Optimization and Reduced Network Load Are Priorities</h4>
</li>
</ol>
<p>With its intelligent caching mechanisms, Alova can significantly reduce API call frequency, thereby improving the overall performance of the application. It is especially useful in scenarios where network efficiency is crucial, such as mobile applications or progressive web apps (PWAs).</p>
<h2 id="heading-community-and-ecosystem"><strong>Community and Ecosystem</strong></h2>
<p>The community and ecosystem surrounding an HTTP client can impact ease of use, available learning resources, and integration with other tools. Let's explore how the Fetch API, Axios, and Alova are perceived in 2025.</p>
<h3 id="heading-ecosystem-and-integrations"><strong>Ecosystem and Integrations</strong></h3>
<p>While Fetch API is widely supported, developers often supplement it with additional libraries for improved caching, timeouts, and request queuing. This can lead to increased development effort compared to using an out-of-the-box solution like Axios or Alova.</p>
<p>Meanwhile, Axios benefits from a well-established ecosystem with a variety of plugins and extensions, making it easy to integrate with different backend architectures, authentication systems, and request monitoring tools.</p>
<p>Alova is designed to work seamlessly with modern state management libraries such as React Query and Vue Query. These integrations make it an attractive choice for developers focused on optimizing frontend data fetching strategies.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Choosing between the Fetch API, Axios, and Alova depends on your project’s needs and priorities. The Fetch API is best for lightweight applications that require minimal dependencies, while Axios is a robust choice for full-stack applications and backend-heavy environments. Alova, on the other hand, is an excellent option for optimizing data fetching and caching in frontend-focused applications.</p>
<p>As developers explore new ways to enhance performance and reduce network load, Alova's adoption is expected to grow, particularly in SPAs and PWAs. But Axios remains a reliable and widely adopted solution, while the Fetch API continues to be the fundamental building block for HTTP requests in JavaScript.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How the Question Mark (?) Operator Works in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ By Nishant Kumar The conditional or question mark operator, represented by a ?, is one of the most powerful features in JavaScript. The ? operator is used in conditional statements, and when paired with a :, can function as a compact alternative to i... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-the-question-mark-works-in-javascript/</link>
                <guid isPermaLink="false">66d4605affe6b1f641b5fa3e</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 03 Feb 2021 17:13:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/01/Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--5--1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Nishant Kumar</p>
<p>The conditional or question mark operator, represented by a <code>?</code>, is one of the most powerful features in JavaScript. The <code>?</code> operator is used in conditional statements, and when paired with a <code>:</code>, can function as a compact alternative to <code>if...else</code> statements.</p>
<p>But there is more to it than meets the eye. There are three main uses for the <code>?</code> operator, two of which you might not used or even heard of. Let's learn about them all in detail.</p>
<h2 id="heading-three-main-uses-for-the-question-mark-in-javascript">Three Main Uses for the Question Mark (<code>?</code>) in JavaScript:</h2>
<ol>
<li>Ternary Operator</li>
<li>Optional Chaining</li>
<li>Nullish Coalescing</li>
</ol>
<p>We'll look at each of these in detail, starting with the most common way you'll see the <code>?</code> operator being used – as a ternary operator.</p>
<h2 id="heading-1-ternary-operator">1. Ternary Operator</h2>
<p>The term ternary means composed of three items or parts. The <code>?</code> operator is also called the ternary operator because, unlike other operators such as strict equal (<code>===</code>) or remainder (<code>%</code>), it's the only one that takes three operands.</p>
<p>Starting with <code>?</code>, we add a condition on the left side and a value on the right side to return when the condition is true. Then we add a colon (<code>:</code>) followed by a value to return if the condition is false.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--1-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The ternary operator is basically a shortcut for a traditional <code>if...else</code> statement.</p>
<p>Let's compare a ternary operator with a longer <code>if...else</code> statement:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--22-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here, the ternary operator occupies only one line of code, whereas the <code>if...else</code> takes seven lines.</p>
<p>Using a ternary operator is much more effective, right?</p>
<h2 id="heading-2-optional-chaining">2. Optional Chaining</h2>
<p>In 2020, an awesome new feature known as Optional Chaining was introduced.</p>
<p>To understand how it works, imagine this scenario.</p>
<p>Let's say you have code that calls on an object property that doesn't exist, which triggers an error at run time. This may be because of a missing or undefined value in your database or from an API:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--23--2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/Screenshot-2021-01-25-00-56-06.png" alt="Image" width="600" height="400" loading="lazy">
<em>A common error – <code>TypeError: Cannot read property ‘salary’ of undefined</code></em></p>
<p>Thanks to Optional Chaining, you can just insert a <code>?</code> between the property name and the period between the next property. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--24-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>With that, it will just return <code>undefined</code> instead of throwing an ugly error.</p>
<p>Optional Chaining is truly a life-changing feature for JavaScript developers. </p>
<h2 id="heading-3-nullish-coalescing">3. Nullish Coalescing</h2>
<p>In some cases, you have to set a default value for a missing property name or value. </p>
<p>For example, let's say we are creating a Weather App in which we are fetching the temperature, humidity, wind speed, pressure, time of sunrise and sunset, and the picture of the city. We inputted a place, let's say <em>Bangalore</em>, but for some reason, its image is not there in the database.</p>
<p>When the app fetches and displays the data, the picture will be blank, which can look ugly. What we can do, in that case, is set a default picture for those cities which don't have an image, Bangalore in our case. </p>
<p>This way, when the app displays the data, the default picture will be there for the cities without images.</p>
<p>You can do this using the <code>||</code> operator, known as the logical OR operator:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/01/Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--4-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>But if you use <code>||</code> to provide a default value, you may encounter unexpected behaviors if you consider some values as usable (for example, <code>''</code> or <code>0</code>).</p>
<p>Consider a scenario where a variable has the value of 0 or an empty string. If we use (<code>||</code>), it will be considered as undefined or NULL and return some default value that we have fixed.</p>
<p>Instead of the logical OR (<code>||</code>) operator, you can use double question marks (<code>??</code>), or Nullish Coalescing. </p>
<p>Let's learn with an example.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> value1 = <span class="hljs-number">0</span> || <span class="hljs-string">'default string'</span>;
<span class="hljs-built_in">console</span>.log(value1);


<span class="hljs-keyword">const</span> value2 = <span class="hljs-string">''</span> || <span class="hljs-number">1000</span>;
<span class="hljs-built_in">console</span>.log(value2);
</code></pre>
<p>Here, we have '0' and 'default string' in variable value1. If we log its value in the console, we will get 'default string', which is weird. Instead of the default string, we should be getting 0, as zero is not undefined or null. So, '<code>||</code>' fails to do the job here.</p>
<p>Similarly, it's the same with value2.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--25-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Output for '<code>||</code>'</em></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> value1 = <span class="hljs-number">0</span> ?? <span class="hljs-string">'default string'</span>;
<span class="hljs-built_in">console</span>.log(value1);


<span class="hljs-keyword">const</span> value2 = <span class="hljs-string">''</span> ?? <span class="hljs-number">1000</span>;
<span class="hljs-built_in">console</span>.log(value2);
</code></pre>
<p>But if we replace '<code>||</code>' with '<code>??</code>', we will get 0 and an empty string, which makes it so cool.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/Pink-Cute-Chic-Vintage-90s-Virtual-Trivia-Quiz-Presentations--26-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Output for '<code>??</code>'</em></p>
<p>Nullish Coalescing works exactly like the logical OR operator, except you will get the right side value when the left side value is <code>undefined</code> or <code>null</code>.</p>
<p>In other words, <code>??</code> only allows <code>undefined</code> and <code>null</code> values, not empty strings (<code>''</code>) or <code>0</code>s.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Now hopefully you understand how the <code>?</code> operator works in JavaScript. It looks simple, but it's one of the most powerful characters in the language. It provides syntactic sugar in three awesome but different ways. </p>
<p>Try them them out and let me know how it goes.</p>
<p>Happy learning!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Arrow Function JavaScript Tutorial – How to Declare a JS Function with the New ES6 Syntax ]]>
                </title>
                <description>
                    <![CDATA[ By Amy Haddad You’ve probably seen arrow functions written a few different ways. //example 1 const addTwo = (num) => {return num + 2;}; //example 2 const addTwo = (num) => num + 2; //example 3 const addTwo = num => num + 2; //example 4 const addTw... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/arrow-function-javascript-tutorial-how-to-declare-a-js-function-with-the-new-es6-syntax/</link>
                <guid isPermaLink="false">66d45d97bc9760a197a10345</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learn to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ programing ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 02 Jun 2020 15:38:35 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/05/nick-fewings-zF_pTLx_Dkg-unsplash-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Amy Haddad</p>
<p>You’ve probably seen arrow functions written a few different ways.</p>
<pre><code class="lang-JS"><span class="hljs-comment">//example 1</span>
<span class="hljs-keyword">const</span> addTwo = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> {<span class="hljs-keyword">return</span> num + <span class="hljs-number">2</span>;};

<span class="hljs-comment">//example 2</span>
<span class="hljs-keyword">const</span> addTwo = <span class="hljs-function">(<span class="hljs-params">num</span>) =&gt;</span> num + <span class="hljs-number">2</span>;

<span class="hljs-comment">//example 3</span>
<span class="hljs-keyword">const</span> addTwo = <span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num + <span class="hljs-number">2</span>;

<span class="hljs-comment">//example 4</span>
<span class="hljs-keyword">const</span> addTwo = <span class="hljs-function"><span class="hljs-params">a</span> =&gt;</span> {
 <span class="hljs-keyword">const</span> newValue = a + <span class="hljs-number">2</span>;
 <span class="hljs-keyword">return</span> newValue;
};
</code></pre>
<p>Some have parentheses around the parameters, while others don’t. Some use curly brackets and the <code>return</code> keyword, others don’t. One even spans multiple lines, while the others consist of a single line.</p>
<p>Interestingly, when we invoke the above arrow functions with the same argument we get the same result.</p>
<pre><code class="lang-JS"><span class="hljs-built_in">console</span>.log(addTwo(<span class="hljs-number">2</span>));
<span class="hljs-comment">//Result: 4</span>
</code></pre>
<p>How do you know which arrow function syntax to use? That’s what this article will uncover: how to declare an arrow function.</p>
<h2 id="heading-a-major-difference">A Major Difference</h2>
<p>Arrow functions are another—more concise—way to write function expressions. However, they don’t have their own binding to the <strong><code>this</code></strong> keyword. </p>
<pre><code class="lang-JS"><span class="hljs-comment">//Function expression</span>
<span class="hljs-keyword">const</span> addNumbers = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">number1, number2</span>) </span>{
   <span class="hljs-keyword">return</span> number1 + number2;
};

<span class="hljs-comment">//Arrow function expression</span>
<span class="hljs-keyword">const</span> addNumbers = <span class="hljs-function">(<span class="hljs-params">number1, number2</span>) =&gt;</span> number1 + number2;
</code></pre>
<p>When we invoke these functions with the same arguments we get the same result.</p>
<pre><code class="lang-JS"><span class="hljs-built_in">console</span>.log(addNumbers(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>));
<span class="hljs-comment">//Result: 3</span>
</code></pre>
<p>There's an important syntactical difference to note: arrow functions use the arrow <strong><code>=&gt;</code></strong> instead of the <strong><code>function</code></strong> keyword. There are other differences to be aware of when you write arrow functions, and that’s what we’ll explore next.</p>
<h2 id="heading-parentheses">Parentheses</h2>
<p>Some arrow functions have parentheses around the parameters and others don't.</p>
<pre><code class="lang-JS"><span class="hljs-comment">//Example with parentheses</span>
<span class="hljs-keyword">const</span> addNums = <span class="hljs-function">(<span class="hljs-params">num1, num2</span>) =&gt;</span> num1 + num2;

<span class="hljs-comment">//Example without parentheses</span>
<span class="hljs-keyword">const</span> addTwo = <span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num + <span class="hljs-number">2</span>;
</code></pre>
<p>As it turns out, the number of parameters an arrow function has determines whether or not we need to include parentheses.</p>
<p>An arrow function with <strong>zero parameters</strong> requires parentheses.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> hello = <span class="hljs-function">() =&gt;</span> <span class="hljs-string">"hello"</span>;
<span class="hljs-built_in">console</span>.log(hello());
<span class="hljs-comment">//Result: "hello"</span>
</code></pre>
<p>An arrow function with <strong>one parameter</strong> does <em>not</em> require parentheses. In other words, parentheses are optional. </p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> addTwo = <span class="hljs-function"><span class="hljs-params">num</span> =&gt;</span> num + <span class="hljs-number">2</span>;
</code></pre>
<p>So we can add parentheses to the above example and the arrow function still works.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> addTwo = <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(addTwo(<span class="hljs-number">2</span>));
<span class="hljs-comment">//Result: 4</span>
</code></pre>
<p>An arrow function with <strong>multiple parameters</strong> requires parentheses.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> addNums = <span class="hljs-function">(<span class="hljs-params">num1, num2</span>) =&gt;</span> num1 + num2;
<span class="hljs-built_in">console</span>.log(addNums(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>));
<span class="hljs-comment">//Result: 3</span>
</code></pre>
<p>Arrow functions also support <strong>rest parameters</strong> and <strong>destructuring</strong>. Both features require parentheses.</p>
<p>This is an example of an arrow function with a <strong>rest parameter</strong>.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> nums = <span class="hljs-function">(<span class="hljs-params">first, ...rest</span>) =&gt;</span> rest;
<span class="hljs-built_in">console</span>.log(nums(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>));
<span class="hljs-comment">//Result: [ 2, 3, 4 ]</span>
</code></pre>
<p>And here’s one that uses <strong>destructuring</strong>.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> location = {
   <span class="hljs-attr">country</span>: <span class="hljs-string">"Greece"</span>,
   <span class="hljs-attr">city</span>: <span class="hljs-string">"Athens"</span>
};

<span class="hljs-keyword">const</span> travel = <span class="hljs-function">(<span class="hljs-params">{city}</span>) =&gt;</span> city;

<span class="hljs-built_in">console</span>.log(travel(location));
<span class="hljs-comment">//Result: "Athens"</span>
</code></pre>
<p>To summarize: if there’s only one parameter—and you’re not using rest parameters or destructuring—then parentheses are optional. Otherwise, be sure to include them.</p>
<h2 id="heading-the-function-body">The Function Body</h2>
<p>Now that we’ve got the parentheses rules covered, let’s turn to the function body of an arrow function.</p>
<p>An arrow function body can either have a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#:~:text=An%20arrow%20function%20expression%20is,cannot%20be%20used%20as%20constructors.">“concise body” or “block body”</a>. The body type influences the syntax.</p>
<p>First, the “concise body” syntax.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> addTwo = <span class="hljs-function"><span class="hljs-params">a</span> =&gt;</span> a + <span class="hljs-number">2</span>;
</code></pre>
<p>The “concise body” syntax is just that: it’s concise! We don’t use the <code>return</code> keyword or curly brackets. </p>
<p>If you have a one-line arrow function (like the example above), then the value is implicitly returned. So you can omit the <code>return</code> keyword and the curly brackets. </p>
<p>Now let’s look at “block body” syntax.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> addTwo = <span class="hljs-function"><span class="hljs-params">a</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> total = a + <span class="hljs-number">2</span>;
    <span class="hljs-keyword">return</span> total;
}
</code></pre>
<p>Notice that we use <em>both</em> curly brackets and the <code>return</code> keyword in the above example. </p>
<p>You normally see this syntax when the body of the function is more than one line. And that’s a key point: wrap the body of a multi-line arrow function in curly brackets and use the <code>return</code> keyword.</p>
<h3 id="heading-objects-and-arrow-functions">Objects and Arrow Functions</h3>
<p>There’s one more syntax nuance to know about: wrap the function body in parentheses when you want to return an <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">object literal expression</a>.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> f = <span class="hljs-function">() =&gt;</span> ({
 <span class="hljs-attr">city</span>:<span class="hljs-string">"Boston"</span>
})
<span class="hljs-built_in">console</span>.log(f().city)
</code></pre>
<p>Without the parentheses, we get an error.</p>
<pre><code class="lang-JS"><span class="hljs-keyword">const</span> f = <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-attr">city</span>:<span class="hljs-string">"Boston"</span>
}
<span class="hljs-comment">//Result: error</span>
</code></pre>
<p>If you find the arrow function syntax a bit confusing, you’re not alone. It takes some time to get familiar with it. But being aware of your options and requirements are steps in that direction.</p>
<p><em>I write about learning to program and the best ways to go about it (</em><a target="_blank" href="https://amymhaddad.com/">amymhaddad.com</a>).  </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Translate jQuery Code Into Vanilla JS ]]>
                </title>
                <description>
                    <![CDATA[ jQuery was once one of the most popular JS libraries available. It solved a lot of problems, like making DOM manipulation and Ajax calls standard across all the different browsers, which all handled JavaScript slightly differently. A lot of jQuery's ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-translate-jquery-code-into-vanilla-js/</link>
                <guid isPermaLink="false">66c35536c7095d76345eaf6a</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ jQuery ]]>
                    </category>
                
                    <category>
                        <![CDATA[ js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 02 Jun 2020 02:15:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9aa7740569d1a4ca26e2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>jQuery was once one of the most popular JS libraries available. It solved a lot of problems, like making DOM manipulation and Ajax calls standard across all the different browsers, which all handled JavaScript slightly differently.</p>
<p>A lot of jQuery's once cutting edge features have made it into vanilla JavaScript, so there's no need to load an entire library for just a few functionalities. Given this, it's not uncommon that one of your tasks on the job will be to rewrite jQuery into vanilla JavaScript.</p>
<h3 id="heading-how-to-rewrite-jquery-into-vanilla-js">How to rewrite jQuery into vanilla JS</h3>
<p>Imagine you have the following code:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"m1 menu"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"menu-center"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"active"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#home"</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>

            <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#portfolio"</span>&gt;</span>Portfolio<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>

            <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#about"</span>&gt;</span>About<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>

            <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#contact"</span>&gt;</span>Contact<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>

            <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"home"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"portfolio"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"about"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"contact"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span>, <span class="hljs-selector-tag">html</span> {
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">100%</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}
<span class="hljs-selector-class">.menu</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">75px</span>;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgba</span>(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>);
    <span class="hljs-attribute">position</span>: fixed;
    <span class="hljs-attribute">background-color</span>:<span class="hljs-built_in">rgba</span>(<span class="hljs-number">4</span>, <span class="hljs-number">180</span>, <span class="hljs-number">49</span>, <span class="hljs-number">0.6</span>);
    <span class="hljs-attribute">-webkit-transition</span>: all <span class="hljs-number">0.3s</span> ease;
    <span class="hljs-attribute">-moz-transition</span>: all <span class="hljs-number">0.3s</span> ease;
    <span class="hljs-attribute">-o-transition</span>: all <span class="hljs-number">0.3s</span> ease;
    <span class="hljs-attribute">transition</span>: all <span class="hljs-number">0.3s</span> ease;
}
<span class="hljs-selector-class">.light-menu</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">75px</span>;
    <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">rgba</span>(<span class="hljs-number">255</span>, <span class="hljs-number">255</span>, <span class="hljs-number">255</span>, <span class="hljs-number">1</span>);
    <span class="hljs-attribute">position</span>: fixed;
    <span class="hljs-attribute">background-color</span>:<span class="hljs-built_in">rgba</span>(<span class="hljs-number">4</span>, <span class="hljs-number">180</span>, <span class="hljs-number">49</span>, <span class="hljs-number">0.6</span>);
    <span class="hljs-attribute">-webkit-transition</span>: all <span class="hljs-number">0.3s</span> ease;
    <span class="hljs-attribute">-moz-transition</span>: all <span class="hljs-number">0.3s</span> ease;
    <span class="hljs-attribute">-o-transition</span>: all <span class="hljs-number">0.3s</span> ease;
    <span class="hljs-attribute">transition</span>: all <span class="hljs-number">0.3s</span> ease;
}
<span class="hljs-selector-id">#menu-center</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">980px</span>;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">75px</span>;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> auto;
}
<span class="hljs-selector-id">#menu-center</span> <span class="hljs-selector-tag">ul</span> {
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">15px</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
}
<span class="hljs-selector-id">#menu-center</span> <span class="hljs-selector-tag">ul</span> <span class="hljs-selector-tag">li</span> {
    <span class="hljs-attribute">list-style</span>: none;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> <span class="hljs-number">30px</span> <span class="hljs-number">0</span> <span class="hljs-number">0</span>;
    <span class="hljs-attribute">display</span>: inline;
}
<span class="hljs-selector-class">.active</span> {
    <span class="hljs-attribute">font-family</span>:<span class="hljs-string">'Droid Sans'</span>, serif;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">14px</span>;
    <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
    <span class="hljs-attribute">text-decoration</span>: none;
    <span class="hljs-attribute">line-height</span>: <span class="hljs-number">50px</span>;
}
<span class="hljs-selector-tag">a</span> {
    <span class="hljs-attribute">font-family</span>:<span class="hljs-string">'Droid Sans'</span>, serif;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">14px</span>;
    <span class="hljs-attribute">color</span>: black;
    <span class="hljs-attribute">text-decoration</span>: none;
    <span class="hljs-attribute">line-height</span>: <span class="hljs-number">50px</span>;
}
<span class="hljs-selector-id">#home</span> {
    <span class="hljs-attribute">background-color</span>: grey;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">100%</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
    <span class="hljs-attribute">overflow</span>: hidden;
    <span class="hljs-attribute">background-image</span>: <span class="hljs-built_in">url</span>(images/home-bg2.png);
}
<span class="hljs-selector-id">#portfolio</span> {
    <span class="hljs-attribute">background-image</span>: <span class="hljs-built_in">url</span>(images/portfolio-bg.png);
    <span class="hljs-attribute">height</span>: <span class="hljs-number">100%</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}
<span class="hljs-selector-id">#about</span> {
    <span class="hljs-attribute">background-color</span>: blue;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">100%</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}
<span class="hljs-selector-id">#contact</span> {
    <span class="hljs-attribute">background-color</span>: red;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">100%</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}
</code></pre>
<pre><code class="lang-js">$(<span class="hljs-built_in">document</span>).ready(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    $(<span class="hljs-built_in">document</span>).on(<span class="hljs-string">"scroll"</span>, onScroll);

    <span class="hljs-comment">//smoothscroll</span>
    $(<span class="hljs-string">'a[href^="#"]'</span>).on(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
        e.preventDefault();
        $(<span class="hljs-built_in">document</span>).off(<span class="hljs-string">"scroll"</span>);

        $(<span class="hljs-string">'a'</span>).each(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            $(<span class="hljs-built_in">this</span>).removeClass(<span class="hljs-string">'active'</span>);
        })
        $(<span class="hljs-built_in">this</span>).addClass(<span class="hljs-string">'active'</span>);

        <span class="hljs-keyword">var</span> target = <span class="hljs-built_in">this</span>.hash,
            menu = target;
        $target = $(target);
        $(<span class="hljs-string">'html, body'</span>).stop().animate({
            <span class="hljs-string">'scrollTop'</span>: $target.offset().top+<span class="hljs-number">2</span>
        }, <span class="hljs-number">500</span>, <span class="hljs-string">'swing'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
            <span class="hljs-built_in">window</span>.location.hash = target;
            $(<span class="hljs-built_in">document</span>).on(<span class="hljs-string">"scroll"</span>, onScroll);
        });
    });
});

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onScroll</span>(<span class="hljs-params">event</span>)</span>{
    <span class="hljs-keyword">var</span> scrollPos = $(<span class="hljs-built_in">document</span>).scrollTop();
    $(<span class="hljs-string">'#menu-center a'</span>).each(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">var</span> currLink = $(<span class="hljs-built_in">this</span>);
        <span class="hljs-keyword">var</span> refElement = $(currLink.attr(<span class="hljs-string">"href"</span>));
        <span class="hljs-keyword">if</span> (refElement.position().top &lt;= scrollPos &amp;&amp; refElement.position().top + refElement.height() &gt; scrollPos) {
            $(<span class="hljs-string">'#menu-center ul li a'</span>).removeClass(<span class="hljs-string">"active"</span>);
            currLink.addClass(<span class="hljs-string">"active"</span>);
        }
        <span class="hljs-keyword">else</span>{
            currLink.removeClass(<span class="hljs-string">"active"</span>);
        }
    });
}
</code></pre>
<p>When you scroll down the page, the navbar should change colors as you get to different sections:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/Peek-2020-05-25-18-44.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The function that handles this is <code>onScroll</code>:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onScroll</span>(<span class="hljs-params">event</span>)</span>{
    <span class="hljs-keyword">var</span> scrollPos = $(<span class="hljs-built_in">document</span>).scrollTop();
    <span class="hljs-comment">/* console.log(scrollPos); */</span>
    $(<span class="hljs-string">'#menu-center a'</span>).each(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">var</span> currLink = $(<span class="hljs-built_in">this</span>);
        <span class="hljs-keyword">var</span> refElement = $(currLink.attr(<span class="hljs-string">"href"</span>));
        <span class="hljs-keyword">if</span> (refElement.position().top &lt;= scrollPos &amp;&amp; refElement.position().top + refElement.height() &gt; scrollPos) {
            $(<span class="hljs-string">'#menu-center ul li a'</span>).removeClass(<span class="hljs-string">"active"</span>);
            currLink.addClass(<span class="hljs-string">"active"</span>);
        }
        <span class="hljs-keyword">else</span>{
            currLink.removeClass(<span class="hljs-string">"active"</span>);
        }
    });
}
</code></pre>
<p>To translate <code>onScroll</code> into vanilla JS, you have a few options.</p>
<h3 id="heading-option-1-use-an-online-compiler">Option #1: Use an online compiler</h3>
<p>You can use an online tool like Google's <a target="_blank" href="https://closure-compiler.appspot.com/">Closure Compiler</a> to compress the code and strip out any unnecessary jQuery.</p>
<p>The problem is that you're still essentially left with jQuery code, so the browser would still need to load the library.</p>
<h3 id="heading-option-2-manually-translate-the-code">Option #2: Manually translate the code</h3>
<p>The best option is to check out resources like <a target="_blank" href="https://github.com/nefe/You-Dont-Need-jQuery">You Don't Need jQuery</a> and <a target="_blank" href="http://youmightnotneedjquery.com/">You Might Not Need jQuery</a> before rewriting your jQuery code. You'll be able to find the native JS versions of the most popular jQuery methods, some of which you can use in your own code.</p>
<p>Here's the <code>onScroll</code> function in vanilla JS:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onScroll</span>(<span class="hljs-params">event</span>) </span>{
  <span class="hljs-keyword">var</span> sections = [...document.querySelectorAll(<span class="hljs-string">'#menu-center a'</span>)];
  <span class="hljs-keyword">var</span> scrollPos = <span class="hljs-built_in">window</span>.pageYOffset || <span class="hljs-built_in">document</span>.documentElement.scrollTop || <span class="hljs-built_in">document</span>.body.scrollTop;
  sections.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">currLink</span>) </span>{
    <span class="hljs-keyword">var</span> val = currLink.getAttribute(<span class="hljs-string">'href'</span>);
    <span class="hljs-keyword">var</span> refElement = <span class="hljs-built_in">document</span>.querySelector(val);
    <span class="hljs-keyword">if</span> (refElement.offsetTop &lt;= scrollPos &amp;&amp; (refElement.offsetTop + refElement.offsetHeight &gt; scrollPos)) {
      <span class="hljs-comment">//document.querySelector('#menu-center ul li a').classList.remove('active');</span>
      currLink.classList.add(<span class="hljs-string">'active'</span>);
    } <span class="hljs-keyword">else</span> {
      currLink.classList.remove(<span class="hljs-string">'active'</span>);
    }
  });
}

<span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'scroll'</span>, onScroll);
</code></pre>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Add Search to a React App with Fuse.js ]]>
                </title>
                <description>
                    <![CDATA[ Search is a powerful way help people visiting your site find the content that's most important to them. But often it's really challenging to figure out the rules and logic to make that happen. In this article, we'll see how can we can use fuse.js to ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-add-search-to-a-react-app-with-fuse-js/</link>
                <guid isPermaLink="false">66b8e33e6a98b2a27ee1f348</guid>
                
                    <category>
                        <![CDATA[ fuse.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ front end ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ frontend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ json ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ search ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Colby Fayock ]]>
                </dc:creator>
                <pubDate>Tue, 26 May 2020 14:45:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/05/fusejs-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Search is a powerful way help people visiting your site find the content that's most important to them. But often it's really challenging to figure out the rules and logic to make that happen. In this article, we'll see how can we can use fuse.js to add search to our apps.</p>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-fusejs">What is fuse.js?</a></li>
<li><a class="post-section-overview" href="#heading-why-is-search-important">Why is search important?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-we-going-to-build">What are we going to build?</a></li>
<li><a class="post-section-overview" href="#heading-step-0-bootstrapping-our-app">Step 0: Bootstrapping our app</a></li>
<li><a class="post-section-overview" href="#heading-step-1-installing-fusejs">Step 1: Installing Fuse.js</a></li>
<li><a class="post-section-overview" href="#heading-step-2-creating-a-new-fuse-search-instance">Step 2: Creating a new Fuse search instance</a></li>
<li><a class="post-section-overview" href="#heading-step-3-setting-up-dynamic-search-based-on-user-input">Step 3: Setting up dynamic search based on user input</a></li>
</ul>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/GZl-yEz4_qw" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-what-is-fusejs">What is fuse.js?</h2>
<p><a target="_blank" href="https://fusejs.io/">Fuse.js</a> is a JavaScript library that provides fuzzy search capabilities for applications and websites. It's nice and easy to use out of the box, but also includes configuration options that allow you to tweak and create powerful solutions.</p>
<h2 id="heading-why-is-search-important">Why is search important?</h2>
<p>Whether you're a content creator or are trying to sell a product with your website, it's important to help your visitors actually find what they're looking for. </p>
<p>If you're building an ecommerce website, you want someone to be able to easily find your Bender vinyl figures rather than having to dig through the entire catalog first.</p>
<h2 id="heading-what-are-we-going-to-build">What are we going to build?</h2>
<p>We're going to start off with a basic Create React App example. It's going to include some character info as structured data for one of my favorite shows Futurama that's simply dumped out into an HTML list.</p>
<p>With that list, we're going to use fuse.js to provide client-side search capabilities, allowing us to demonstrate searching for the character we're looking for by their name and other details.</p>
<h2 id="heading-step-0-bootstrapping-our-app">Step 0: Bootstrapping our app</h2>
<p>To get started, we're going to need content to work with. I got started by building a list of characters from Futurama as structured json data that I put in a list with a fresh Create React App.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/futurama-character-search-demo.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Futurama character search demo</em></p>
<p>You'll also notice I've already added an input for our search. It's not yet functional but we'll use that to get started.</p>
<p>If you'd like to start off at the same place, I created a branch with my demo repo that you can clone locally to walk through the project with me!</p>
<pre><code class="lang-shell">git clone --single-branch --branch start git@github.com:colbyfayock/my-futurama-characters.git
</code></pre>
<p><a target="_blank" href="https://github.com/colbyfayock/my-futurama-characters/tree/start">Git branch "start"</a></p>
<p>Or <a target="_blank" href="https://github.com/colbyfayock/my-futurama-characters/commit/20d4e42aaf69e214b63e684e012cd2f8c95d427b">follow along with the commit</a>.</p>
<h2 id="heading-step-1-installing-fusejs">Step 1: Installing Fuse.js</h2>
<p>First thing we'll want to do is actually add Fuse.js to our app. In your project, run:</p>
<pre><code class="lang-shell">yarn add fuse.js
# or
npm install --save fuse.js
</code></pre>
<p>This will save the dependency to our project so that we'll be able to use it in our project.</p>
<p>Next we'll want to import the dependency to our app so that we can start building with it. At the top of your file, in our case <code>src/App.js</code> if you're following along with me in a new Create React App project, add:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> Fuse <span class="hljs-keyword">from</span> <span class="hljs-string">'fuse.js'</span>;
</code></pre>
<p>If you want to test that it's working, you can <code>console.log(Fuse)</code> and see our <code>Fuse</code> class we'll use to create our search capabilities.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/fusejs-class.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Imported fuse.js class</em></p>
<p>And with that, we're ready to get started!</p>
<p><a target="_blank" href="https://github.com/colbyfayock/my-futurama-characters/commit/54720daffa6ff415997c319b12f8f44d7ec8b748">Follow along with the commit</a></p>
<h2 id="heading-step-2-creating-a-new-fuse-search-instance">Step 2: Creating a new Fuse search instance</h2>
<p>To use Fuse.js, we'll want to first create a new instance of it.</p>
<p>At the top of your component, add:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fuse = <span class="hljs-keyword">new</span> Fuse(characters, {
  <span class="hljs-attr">keys</span>: [
    <span class="hljs-string">'name'</span>,
    <span class="hljs-string">'company'</span>,
    <span class="hljs-string">'species'</span>
  ]
});
</code></pre>
<p>With this does:</p>
<ul>
<li>Creates a new instance of Fuse</li>
<li>Passes in our <code>characters</code> array of objects</li>
<li>Specifies the 3 keys in our data that we want to search on</li>
</ul>
<p>Next, to perform the search, we can add:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> results = fuse.search(<span class="hljs-string">'bender'</span>);
</code></pre>
<p>And if we console log out the results, we can see:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/basic-fusejs-search-results.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Basic fuse.js search results</em></p>
<p>You'll notice that we have more results than our friend Bender though. Fuse.js provides a "fuzzy search" meaning it tries to help you in case you're not sure what you're looking for or if you're misspelling your query.</p>
<p>To get an idea of how this works, let's add the <code>includeScore</code> option to our search:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> fuse = <span class="hljs-keyword">new</span> Fuse(characters, {
  <span class="hljs-attr">keys</span>: [
    <span class="hljs-string">'name'</span>,
    <span class="hljs-string">'company'</span>,
    <span class="hljs-string">'species'</span>
  ],
  <span class="hljs-attr">includeScore</span>: <span class="hljs-literal">true</span>
});
</code></pre>
<p>Now we can see the <code>score</code> attribute in our results object.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/fusejs-search-results-with-score.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Fuse.js search results with score</em></p>
<p>You'll notice that our first result has a really low score. With fuse.js, a lower score means it's closer to an exact match.</p>
<p>A score of 0 indicates a perfect match, while a score of 1 indicates a complete mismatch.</p>
<p>It's saying that is incredibly likely that the first result is what we're looking for, but it's not confident in the others.</p>
<p>So with our results, we want to actually connect that to our UI. If you notice our array output is different than what we are mapping through for the HTML list, so let's create a new variable that we can change it to:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> results = fuse.search(<span class="hljs-string">'bender'</span>);
<span class="hljs-keyword">const</span> characterResults = results.map(<span class="hljs-function"><span class="hljs-params">character</span> =&gt;</span> character.item);
</code></pre>
<p>What this is doing is creating a new array using the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a> method that will only include the <code>item</code> property from each array object.</p>
<p>Then if we replace our <code>characters</code> map inside of our list with <code>characterResults.map</code>:</p>
<pre><code class="lang-jsx">&lt;ul className=<span class="hljs-string">"characters"</span>&gt;
  {characterResults.map(<span class="hljs-function"><span class="hljs-params">character</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> { name, company, species, thumb } = character;
</code></pre>
<p>We can now see that our page only shows the results for "bender"!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/futurama-character-search-filtered-results.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Demo with filtered results</em></p>
<p><a target="_blank" href="https://github.com/colbyfayock/my-futurama-characters/commit/adbf30a872fa134cfca4e142ba479877b9665e9a">Follow along with the commit!</a></p>
<h2 id="heading-step-3-setting-up-dynamic-search-based-on-user-input">Step 3: Setting up dynamic search based on user input</h2>
<p>Now that we have a hard-coded search working, we want someone to actually be able to use the search input to search!</p>
<p>To achieve this, we're going to use the <code>useState</code> hook and listen for changes to the <code>input</code> field, which will dynamically create a search for our data.</p>
<p>First, import the <code>useState</code> hook from React:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
</code></pre>
<p>Next, let's use that hook to create a state instance:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> [query, updateQuery] = useState(<span class="hljs-string">''</span>);
</code></pre>
<p>Here, we're creating a new state of <code>query</code> that we can update with <code>updateQuery</code> that defaults to an empty string (<code>''</code>).</p>
<p>With that, let's tell our search input to use that <code>query</code> value as it's value:</p>
<pre><code class="lang-jsx">&lt;input type=<span class="hljs-string">"text"</span> value={query} /&gt;
</code></pre>
<p>At this point, nothing should be different, as we are using a blank query.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/futurama-character-search-filtered-results.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Demo with filtered results - nothing changed</em></p>
<p>Now let's add an event handler to our input that we can use to update our state:</p>
<pre><code class="lang-jsx">&lt;input type=<span class="hljs-string">"text"</span> value={query} onChange={onSearch} /&gt;
</code></pre>
<p>And we'll want to create that function so we can use it:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onSearch</span>(<span class="hljs-params">{ currentTarget }</span>) </span>{
  updateQuery(currentTarget.value);
}
</code></pre>
<p>This will update our <code>query</code> with the input's value any time it changes.</p>
<p>Now that our <code>query</code>  will have what we want to search for, we can update our search instance:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> results = fuse.search(query);
</code></pre>
<p>And now if you reload the page, it's blank! ?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/futurama-character-search-no-results.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Demo with no results</em></p>
<p>That's because by default, Fuse sees our empty query and doesn't match it to anything. If we now search for something like <code>slurms</code>, we can see our search dynamically update with results!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/futurama-character-search-results.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Demo with results for "slurms"</em></p>
<p>If we wanted to fix this though so that all of our results show when there's no query, we can do so with an <code>if</code> statement or in my example, a ternary, that will show all of the characters if there is no query:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> characterResults = query ? results.map(<span class="hljs-function"><span class="hljs-params">character</span> =&gt;</span> character.item) : characters;
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/futurama-character-search-demo.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Demo with all results</em></p>
<p>And with that, we have our basic search!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/05/futurama-character-search-results-query.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Demo with filtered results for "zoidberg"</em></p>
<p><a target="_blank" href="https://github.com/colbyfayock/my-futurama-characters/commit/1b8918fc56f31517686a6c73f1969787728736ac">Follow along with the commit!</a></p>
<h2 id="heading-what-can-i-do-next">What can I do next?</h2>
<h3 id="heading-tuning-your-search">Tuning your search</h3>
<p>Fuse.js comes with a lot of options that you can use to tune your search to however you'd like. Want to only show confident results? Use the <code>threshold</code> option! Want case sensitive queries? Use the <code>isCaseSensitive</code> option!</p>
<p><a target="_blank" href="https://fusejs.io/api/options.html">https://fusejs.io/api/options.html</a></p>
<h3 id="heading-setting-the-default-query-with-url-parameters">Setting the default query with URL parameters</h3>
<p>Sometimes you want someone to be able to link to a particular set of results. To do this, we might want to be able to add a new URL parameter like <code>?q=bender</code>.</p>
<p>To make this work, you can grab that URL parameter with javascript and use that value to set our <code>query</code> state.</p>
<h2 id="heading-join-the-conversation">Join the conversation!</h2>
<div class="embed-wrapper">
        <blockquote class="twitter-tweet">
          <a href="https://twitter.com/colbyfayock/status/1265298322891378688"></a>
        </blockquote>
        <script defer="" src="https://platform.twitter.com/widgets.js" charset="utf-8"></script></div>
<div id="colbyfayock-author-card">
  <p>
    <a href="https://twitter.com/colbyfayock">
      <img src="https://res.cloudinary.com/fay/image/upload/w_2000,h_400,c_fill,q_auto,f_auto/w_1020,c_fit,co_rgb:007079,g_north_west,x_635,y_70,l_text:Source%20Sans%20Pro_64_line_spacing_-10_bold:Colby%20Fayock/w_1020,c_fit,co_rgb:383f43,g_west,x_635,y_6,l_text:Source%20Sans%20Pro_44_line_spacing_0_normal:Follow%20me%20for%20more%20JavaScript%252c%20UX%252c%20and%20other%20interesting%20things!/w_1020,c_fit,co_rgb:007079,g_south_west,x_635,y_70,l_text:Source%20Sans%20Pro_40_line_spacing_-10_semibold:colbyfayock.com/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_68,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_145,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_222,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_295,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/v1/social-footer-card" alt="Follow me for more Javascript, UX, and other interesting things!" width="2000" height="400" loading="lazy">
    </a>
  </p>
  <ul>
    <li>
      <a href="https://twitter.com/colbyfayock">? Follow Me On Twitter</a>
    </li>
    <li>
      <a href="https://youtube.com/colbyfayock">?️ Subscribe To My Youtube</a>
    </li>
    <li>
      <a href="https://www.colbyfayock.com/newsletter/">✉️ Sign Up For My Newsletter</a>
    </li>
  </ul>
</div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Don’t just lint your code - fix it with Prettier ]]>
                </title>
                <description>
                    <![CDATA[ Linting makes our lives easier because it tells us what’s wrong with our code. But how can we avoid doing the actual work that goes into fixing it? Previously I wrote about linting, what it is, and how it makes your life easier. At the end, I actuall... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/dont-just-lint-your-code-fix-it-with-prettier/</link>
                <guid isPermaLink="false">66b8e322682e4a25eed26199</guid>
                
                    <category>
                        <![CDATA[ clean code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Code Quality ]]>
                    </category>
                
                    <category>
                        <![CDATA[ code review ]]>
                    </category>
                
                    <category>
                        <![CDATA[ eslint ]]>
                    </category>
                
                    <category>
                        <![CDATA[ front end ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ frontend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Prettier ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Colby Fayock ]]>
                </dc:creator>
                <pubDate>Wed, 06 Nov 2019 15:45:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/11/formatting-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Linting makes our lives easier because it tells us what’s wrong with our code. But how can we avoid doing the actual work that goes into fixing it?</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/what-is-linting-and-how-can-it-save-you-time/">Previously I wrote about linting</a>, what it is, and how it makes your life easier. At the end, I actually included a way that you could automatically fix your code. So why am I writing this?</p>
<h2 id="heading-what-do-you-mean-fix-it"><strong>What do you mean fix it?</strong></h2>
<p>Before we roll into it, let’s hit this quick. Linters are powerful and provide an easy way to scan your code for syntax errors that could lead to bugs. Or they can simply help keep a codebase clean, healthy, and consistent. When run, it will show all the issues and let you go through each one individually to fix them.</p>
<p>Taking that to the next level, some linters will actually allow you to pass in an argument to the command running the linter that allows it to fix it for you automagically. This means you don’t have to manually go through and make all of those little whitespace and semicolon (add them! ?) tweaks yourself!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/ron-swanson-happy.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Ron Swanson happy</em></p>
<h2 id="heading-so-what-more-can-i-do-to-fix-things"><strong>So what more can I do to fix things?</strong></h2>
<p>If you already use the fix option, thats a good start. But there are tools out there that have been developed specifically to tackle this problem beyond just a flag into your command. The one I’m going to cover is Prettier.</p>
<h2 id="heading-what-is-prettier"><strong>What is Prettier?</strong></h2>
<p><a target="_blank" href="https://prettier.io/">Prettier</a> pegs itself as “an opinionated code formatter." It takes an input of your code and outputs it in a consistent format stripping any of the original code style. It actually converts your code to a <a target="_blank" href="https://github.com/benjamn/recast">syntax tree</a>, then rewrites it using the styles and rules you and Prettier provide together via your ESLint config and Prettier’s default rules.</p>
<p>You can easily use Prettier alone just to format your code, which works just fine. But if you combine this with an underlying ESLint process, you get both a powerful linter and a powerful fixer. I’m going to show you how to make those work together.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/voltron.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Voltron</em></p>
<h2 id="heading-getting-started-with-prettier"><strong>Getting started with Prettier</strong></h2>
<p>For this walkthrough, I’m going to assume that you have ESLint set up and configured in an application. Particularly, I’m going to pick up where I left off in my previous walkthrough where <a target="_blank" href="https://www.freecodecamp.org/news/what-is-linting-and-how-can-it-save-you-time/">we installed ESLint to a React application</a>.</p>
<p>Additionally of note, Prettier tells us right from the start that it's an opinionated code formatter. You should expect that it will format your code in a consistent way, but maybe a different way than you currently have it configured. But don’t fret! You can tweak this configuration.</p>
<p>So what are we starting off with? We already:</p>
<ul>
<li>Have installed <a target="_blank" href="https://github.com/eslint/eslint">ESLint</a></li>
<li>Have added <a target="_blank" href="https://github.com/babel/babel-eslint">Babel</a> as our parser</li>
<li>Have added a <a target="_blank" href="https://github.com/yannickcr/eslint-plugin-react">plugin</a> that includes React configurations</li>
</ul>
<p>Next, let’s get started by installing a few packages:</p>
<pre><code class="lang-shell">yarn add prettier prettier-eslint prettier-eslint-cli -D
</code></pre>
<p><em>Note: the command above is similar to using <code>npm</code>. If your project doesn't use <code>yarn</code>, swap out to <code>npm</code> as appropriate.</em></p>
<p>Above, we’re installing:</p>
<ul>
<li><a target="_blank" href="https://github.com/prettier/prettier">prettier</a>: core Prettier package and engine</li>
<li><a target="_blank" href="https://github.com/prettier/prettier-eslint">prettier-lint</a>: passes the Prettier result to ESLint to fix using your ESLint config</li>
<li><a target="_blank" href="https://github.com/prettier/prettier-eslint-cli">prettier-eslint-cli</a>: helps Prettier and ESLint work together on various files across your project</li>
</ul>
<p>And we’re installing them as a dev dependency, as we don’t need it outside development.</p>
<h2 id="heading-configuring-your-new-formatter"><strong>Configuring your new formatter</strong></h2>
<p>Now that our packages are installed, we can set up <code>yarn</code> to run this command for us.</p>
<p>Previously, we set up a <code>lint</code> script to look like this in our <code>package.json</code>:</p>
<pre><code class="lang-json"><span class="hljs-string">"scripts"</span>: {
  ...
  <span class="hljs-attr">"lint"</span>: <span class="hljs-string">"eslint . --ext .js"</span>
  ...
}
</code></pre>
<p>We’re going to leave that as it is, but we’ll do something similar and create a new script right next to it called <code>format</code> for our formatter Prettier:</p>
<pre><code class="lang-json"><span class="hljs-string">"scripts"</span>: {
  ...
  <span class="hljs-attr">"format"</span>: <span class="hljs-string">"prettier-eslint --eslint-config-path ./.eslintrc.js --write '**/*.js'"</span>,
  <span class="hljs-attr">"lint"</span>: <span class="hljs-string">"eslint . --ext .js"</span>
  ...
}
</code></pre>
<p>So what’s going on there? We’re:</p>
<ul>
<li>Adding a new script called <code>format</code>, that we can run as <code>yarn format</code></li>
<li>We’re utilizing our <code>prettier-eslint-cli</code> package to run the formatting for us</li>
<li>We’re passing in our ESLint config located next to our <code>package.json</code> in the root of the project (change this if it’s in a different location)</li>
<li>And finally, we’re telling prettier to write all files matching <code>**/*.js</code>, or any JS files it finds recursively through our project</li>
</ul>
<p>The beauty here is that we're passing in our ESLint config to Prettier. This means we only have to maintain 1 config for both tools, but we still leverage the linting power of ESLint along with the formatting power of Prettier.</p>
<h2 id="heading-run-your-formatter"><strong>Run your formatter!</strong></h2>
<p>Now that we’re all set up, let’s run it! Run this following:</p>
<pre><code>yarn format
</code></pre><p>and immediately, we see that it works:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/prettier-command-line-success.png" alt="Image" width="600" height="400" loading="lazy">
<em>Successfully running Prettier</em></p>
<h2 id="heading-hey-my-code-looks-different"><strong>Hey, my code looks different!</strong></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/spongebob-pitchforks.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Angry mob with pitchforks</em></p>
<p>As I mentioned earlier, Prettier tells us straight up, it’s an opinionated formatter. It ships with its own rules, sort of like its own ESLint config, so it will go through and make those changes as well.</p>
<p>Don’t abandon your code! Instead, you can review the changes, see if maybe it makes sense to keep it that way (it will be very consistent) or you can update your ESLint config (<code>.eslintrc.js</code>) to overwrite the rules you don’t like. This is also a good way to maybe learn some new things that you might not have expected to get caught before.</p>
<h2 id="heading-so-where-does-this-leave-us"><strong>So where does this leave us?</strong></h2>
<p>If you’ve followed along so far, we now have two commands:</p>
<ul>
<li><code>lint</code>: which will check your code for you and tell you what's wrong</li>
<li><code>format</code>: will automatically try to fix the problems for you</li>
</ul>
<p>When using these in practice, your best bet is to always run <code>format</code> first to let it try to automatically fix anything it can. Then immediately run <code>lint</code> to catch anything Prettier wasn’t able to fix automatically.</p>
<h2 id="heading-whats-next"><strong>What’s next?</strong></h2>
<p>Now that we can format our code automatically, we should be able to fix our code automatically!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/fresh-off-the-boat-mind-blown.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Eddie from Fresh Off the Boat's mind blown</em></p>
<p>Next time we’ll take this a step further and set up a <code>git</code> hook that will allow this to run before you commit. This means you won't ever have to worry about forgetting to run this again!</p>
<div id="colbyfayock-author-card">
  <p>
    <a href="https://twitter.com/colbyfayock">
      <img src="https://res.cloudinary.com/fay/image/upload/w_2000,h_400,c_fill,q_auto,f_auto/w_1020,c_fit,co_rgb:007079,g_north_west,x_635,y_70,l_text:Source%20Sans%20Pro_64_line_spacing_-10_bold:Colby%20Fayock/w_1020,c_fit,co_rgb:383f43,g_west,x_635,y_6,l_text:Source%20Sans%20Pro_44_line_spacing_0_normal:Follow%20me%20for%20more%20JavaScript%252c%20UX%252c%20and%20other%20interesting%20things!/w_1020,c_fit,co_rgb:007079,g_south_west,x_635,y_70,l_text:Source%20Sans%20Pro_40_line_spacing_-10_semibold:colbyfayock.com/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_68,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_145,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_222,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_295,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/v1/social-footer-card" alt="Follow me for more Javascript, UX, and other interesting things!" width="2000" height="400" loading="lazy">
    </a>
  </p>
  <ul>
    <li>
      <a href="https://twitter.com/colbyfayock">? Follow Me On Twitter</a>
    </li>
    <li>
      <a href="https://youtube.com/colbyfayock">?️ Subscribe To My Youtube</a>
    </li>
    <li>
      <a href="https://www.colbyfayock.com/newsletter/">✉️ Sign Up For My Newsletter</a>
    </li>
  </ul>
</div>

<p><em>Originally published at <a target="_blank" href="https://www.colbyfayock.com/2019/11/dont-just-lint-your-code-fix-it-with-prettier/">https://www.colbyfayock.com/2019/11/dont-just-lint-your-code-fix-it-with-prettier/</a></em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is linting and how can it save you time? ]]>
                </title>
                <description>
                    <![CDATA[ One of the biggest challenges in software development is time. It’s something we can’t easily get more of, but linting can help us make the most out of the time we have. So what is linting? lint, or a linter, is a tool that analyzes source code to fl... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-linting-and-how-can-it-save-you-time/</link>
                <guid isPermaLink="false">66b8e39893a17625e9eef113</guid>
                
                    <category>
                        <![CDATA[ clean code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Code Quality ]]>
                    </category>
                
                    <category>
                        <![CDATA[ code review ]]>
                    </category>
                
                    <category>
                        <![CDATA[ eslint ]]>
                    </category>
                
                    <category>
                        <![CDATA[ front end ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ frontend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GatsbyJS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Colby Fayock ]]>
                </dc:creator>
                <pubDate>Wed, 09 Oct 2019 14:30:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/10/linting.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>One of the biggest challenges in software development is time. It’s something we can’t easily get more of, but linting can help us make the most out of the time we have.</p>
<h2 id="heading-so-what-is-linting">So what is linting?</h2>
<p><strong>lint</strong>, or a <strong>linter</strong>, is a tool that analyzes source code to flag programming errors, bugs, stylistic errors, and suspicious constructs. <a target="_blank" href="https://en.wikipedia.org/wiki/Lint(software)">https://en.wikipedia.org/wiki/Lint(software)</a></p>
<p>Simply put, a linter is a tool that programmatically scans your code with the goal of finding issues that can lead to bugs or inconsistencies with code health and style. Some can even help fix them for you!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/miachel-scott-tell-me-more.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Michael Scott - Tell me more</em></p>
<p>Take for instance, the following example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> test = <span class="hljs-string">'I am a test'</span>;
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Test: <span class="hljs-subst">${test}</span>`</span>);
<span class="hljs-keyword">const</span> test = <span class="hljs-string">'Another one.'</span>;
</code></pre>
<p>We’re declaring the constant <code>test</code> twice, which our javascript engine won’t be happy about. With the proper linter settings and watch configuration, instead of getting caught later as an error when the code runs, you’ll immediately get an error through your linter running in the background:</p>
<pre><code>  <span class="hljs-number">10</span>:<span class="hljs-number">9</span>  error  Parsing error: Identifier <span class="hljs-string">'test'</span> has already been declared

   <span class="hljs-number">8</span> |   <span class="hljs-keyword">const</span> test = <span class="hljs-string">'I am a test'</span>;
   <span class="hljs-number">9</span> |   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Test: <span class="hljs-subst">${<span class="hljs-number">2</span>}</span>`</span>);
&gt; <span class="hljs-number">10</span> |   <span class="hljs-keyword">const</span> test = <span class="hljs-string">'Another one.'</span>;
     |         ^
</code></pre><p>It might be pretty obvious that you have 2 of the same <code>const</code> declarations given this is only 3 lines, but in a more complex application, this can save tons of time having to hunt down a pesky bug that’s not always obvious.</p>
<h2 id="heading-what-all-can-linting-help-with"><strong>What all can linting help with?</strong></h2>
<p><a target="_blank" href="https://eslint.org/docs/rules/">Lots of things</a>, including but not limited to:</p>
<ul>
<li>Flagging bugs in your code from syntax errors</li>
<li>Giving you warnings when code may not be intuitive</li>
<li>Providing suggestions for common best practices</li>
<li>Keeping track of TODO’s and FIXME’s</li>
<li>Keeping a consistent code style</li>
</ul>
<p>Most things you can think of probably already <a target="_blank" href="https://github.com/dustinspecker/awesome-eslint">exist in one form or another</a>, and if not, you can even <a target="_blank" href="https://gist.github.com/sindresorhus/1656c46f23545deff8cc713649dcff26">create custom rules</a> that fit your needs!</p>
<h2 id="heading-how-is-this-actually-helping-or-why-should-i-care"><strong>How is this actually helping or why should I care?</strong></h2>
<p>Probably the biggest overlying theme of the list above is the fact that these issues will be called out immediately. No longer will these issues creep up on you in the middle of running your app or give someone anxiety during a code review. No longer will you and your reviewer endlessly fight passive aggressively through the comments about whether or not to include a semicolon at the end of JS statements (<a target="_blank" href="https://stackoverflow.com/a/444082">you should</a> ?).</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/looking-for-semicolon.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Grandma looking for a semicolon</em></p>
<p>All of those moments that stop you from being productive because of a silly syntax error or the micro-interactions you and your teammates have during a review take time. They add up and end up taking away the time you can spend fixing another bug or developing the next great feature of your product.</p>
<h2 id="heading-so-how-do-i-actually-get-started"><strong>So how do I actually get started?</strong></h2>
<p>Even though there are linters for most, if not all, other mainstream languages, for the purpose of this post, I’m going to focus on Javascript. The same principles apply, but the tooling may be a bit different.</p>
<p>I’m going to run through how you can get set up for basic linting in a React app. You can easily follow along by spinning up your own React app or using my <a target="_blank" href="https://www.gatsbyjs.org/">Gatsby</a> starter: <a target="_blank" href="https://github.com/colbyfayock/gatsby-starter-sass#starting-from-scratch">https://github.com/colbyfayock/gatsby-starter-sass#starting-from-scratch</a></p>
<h3 id="heading-your-linter"><strong>Your Linter</strong></h3>
<p>To get started, we first need a linter. <a target="_blank" href="https://trends.google.com/trends/explore?geo=US&amp;q=eslint,jshint,jslint">Probably the most popular</a> in the Javascript world is <a target="_blank" href="https://eslint.org/">ESLint</a>. Your linter will actually be the engine for defining rules and parsing your files to test against. ESLint is available as an <a target="_blank" href="https://www.npmjs.com/package/eslint">npm package</a> by itself and <a target="_blank" href="https://eslint.org/docs/user-guide/getting-started">once installed</a>, out of the box it allows you to set up a basic configuration file and hit the ground running with some command line tools.</p>
<p>Let’s first add our ESLint dependency:</p>
<pre><code>yarn add eslint -D
</code></pre><p>We’re installing this as a <code>devDependency</code> (hence the <code>-D</code> flag), because this isn’t something our application needs to run. After it’s successfully installed, let’s add it to our <code>package.json</code> as a script:</p>
<pre><code class="lang-json">...
<span class="hljs-string">"scripts"</span>: {
  ...
  <span class="hljs-attr">"lint"</span>: <span class="hljs-string">"eslint .  --ext .js"</span>
  ...
},
...
</code></pre>
<p>In the above, we’re running our linter on the entire project directory on any file that has an extension of <code>.js</code>. If you're working with a large project with many file types, maybe even some you don't want linted, you can <a target="_blank" href="https://eslint.org/docs/user-guide/command-line-interface">change that flag or be more specific</a> with other options.</p>
<p>To support ESLint, we’ll need to do one more thing. Let’s add a file at the root of our project (probably where your <code>package.json</code> is) called <code>.eslintrc.js</code> and make the contents of the file simply:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = {};
</code></pre>
<p>Once you’re ready, you can run <code>yarn lint</code> and… get an error.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/lint-with-import-errors.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Lint results - Import errors</em></p>
<p>This is okay, and expected in our project, so let’s move on.</p>
<h3 id="heading-your-parser"><strong>Your Parser</strong></h3>
<p>A common tool in the chain for Javascript developers is <a target="_blank" href="https://babeljs.io/">Babel</a>, which allows you to write code with features that may not be supported in all browsers, such as using <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a>, that are available in <a target="_blank" href="http://es6-features.org/#Constants">ES6</a>, and other conventions like importing files via <code>import</code>.</p>
<p>The code you write may already run through Babel to work in a browser, but that doesn’t apply to ESLint by default, so ESLint allows you to specify a parser that allows the linting processing to look at the same code as your browser sees. In this case we’ll want to use <a target="_blank" href="https://github.com/babel/babel-eslint">Babel’s ESLint</a> parser that’s made available to us.</p>
<p>To set that up, we’ll want to first install our dependency:</p>
<pre><code>yarn add babel-eslint -D
</code></pre><p>Typically if you're using <code>babel-eslint</code> you'll want to make sure <code>babel</code> is installed next to it, but in our case, Gatsby already uses <code>babel</code>, so we don’t necessarily need to add it. After that’s set up, we’ll want to update our <code>.eslintrc.js</code> config file with some new options:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = {
    <span class="hljs-string">"env"</span>: {
        <span class="hljs-string">"browser"</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-string">"node"</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-string">"es6"</span>: <span class="hljs-literal">true</span>
    },
    <span class="hljs-string">"parser"</span>: <span class="hljs-string">"babel-eslint"</span>
};
</code></pre>
<p>Here, we’re letting ESLint know that our environment will be run in node (Gatsby’s precompiling), inside the browser (the app), and it will use ES6. This helps ESLint know how to run your code. Additionally, we want to set up our parser to be <code>babel-eslint</code>.</p>
<p>Once we’re ready to go, run <code>yarn lint</code> again and… well nothing really happened.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/lint-with-nothing-happening.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Lint results - Nothing happened</em></p>
<p>This is still expected, as we don’t have any rules set up!</p>
<h3 id="heading-plugins-for-your-code"><strong>Plugins for your code</strong></h3>
<p>Writing a <a target="_blank" href="https://reactjs.org/">React</a> app? The Babel parser may help you transform your code, but you might have a hard time being productive, as ESLint needs to understand how it should work to lint your React files.</p>
<p>Part of the beauty of ESLint is that it allows you to <a target="_blank" href="https://eslint.org/docs/developer-guide/working-with-plugins">configure plugins</a> that have the opportunity to create and set rules for you. Luckily, along with our Babel parser above that does some of the heavy lifting, we have a <a target="_blank" href="https://github.com/yannickcr/eslint-plugin-react">React plugin</a> available that does just that and takes care of linting the JSX for us.</p>
<p>Let’s first install our dependency:</p>
<pre><code>yarn add eslint-plugin-react -D
</code></pre><p>Further, let’s update our <code>.eslintrc.js</code> file again:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = {
    <span class="hljs-string">"settings"</span>: {
        <span class="hljs-string">"react"</span>: {
            <span class="hljs-string">"version"</span>: <span class="hljs-string">"detect"</span>
        }
    },
    <span class="hljs-string">"env"</span>: {
        <span class="hljs-string">"browser"</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-string">"node"</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-string">"es6"</span>: <span class="hljs-literal">true</span>
    },
    <span class="hljs-string">"plugins"</span>: [
        <span class="hljs-string">"react"</span>
    ],
    <span class="hljs-string">"parser"</span>: <span class="hljs-string">"babel-eslint"</span>
};
</code></pre>
<p>What we’re adding here is a setting that automatically detects what React version you’re using, which is helpful to let your linting get parsed properly, and then set up our react plugin that we installed above.</p>
<p>For one last final time, we will run our <code>lint</code> script and get nothing:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/lint-with-nothing-happening-1.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Lint results - Nothing happened</em></p>
<h3 id="heading-rules-defined-by-otherss-opinions"><strong>Rules defined by others’s opinions</strong></h3>
<p>If you’re not really sure where to get started or just want to quickly get up and running, it’s recommend that you enable <a target="_blank" href="https://eslint.org/docs/rules/">ESLint’s own recommended rules</a>. Let’s add this to our <code>.eslintrc.js</code> config file:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = {
    <span class="hljs-string">"settings"</span>: {
        <span class="hljs-string">"react"</span>: {
            <span class="hljs-string">"version"</span>: <span class="hljs-string">"detect"</span>
        }
    },
    <span class="hljs-string">"env"</span>: {
        <span class="hljs-string">"browser"</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-string">"node"</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-string">"es6"</span>: <span class="hljs-literal">true</span>
    },
    <span class="hljs-string">"plugins"</span>: [
        <span class="hljs-string">"react"</span>
    ],
    <span class="hljs-string">"extends"</span>: [
        <span class="hljs-string">"eslint:recommended"</span>
    ],
    <span class="hljs-string">"parser"</span>: <span class="hljs-string">"babel-eslint"</span>
};
</code></pre>
<p>And let’s run our <code>yarn lint</code>.</p>
<p>Woah! This will immediately give you a lot errors, it seems like something’s wrong.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/lint-with-react-errors.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Lint results - React errors</em></p>
<p>Since we’re running a React app, we also want to make sure our linter understands the rules it should follow, so let’s also add our React plugin to the <code>.eslintrc.js</code> config setup:</p>
<pre><code class="lang-json">    <span class="hljs-string">"extends"</span>: [
        <span class="hljs-string">"eslint:recommended"</span>,
        <span class="hljs-string">"plugin:react/recommended"</span>
    ],
</code></pre>
<p>Now if you run <code>yarn lint</code>, you get something a little more logical.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/lint-with-errors.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Lint results - Normal errors</em></p>
<p>If you’re following along, it looks like our starter app had a misplaced semicolon and a missing prop in our <code>propTypes</code> validation for <code>Layout.js</code>. Writing this helped me fix my own repo! ?</p>
<p>Going further, if those don’t seem to fit your needs, lots of developers and teams have published their own configurations that ESLint allows you to easily tap into.</p>
<p>Some popular ones include:</p>
<ul>
<li><a target="_blank" href="https://www.npmjs.com/package/eslint-config-airbnb">Airbnb’s config</a></li>
<li><a target="_blank" href="https://github.com/standard/eslint-config-semistandard">Semistandard</a></li>
<li><a target="_blank" href="https://github.com/google/eslint-config-google">Google’s JS Style Guide</a></li>
</ul>
<p>Not happy with the options available? You can even <a target="_blank" href="https://eslint.org/docs/6.0.0/developer-guide/shareable-configs">create and publish your own</a> to either layer on top of others as a starting point or give it a go from scratch.</p>
<h3 id="heading-let-it-do-the-work-most-of-it"><strong>Let it do the work (most of it)</strong></h3>
<p>You don’t think I’m going to make you fix all of those thing yourself do you? Well, you may have to fix some, but let’s try to get ESLint to fix some of it for us.</p>
<p>If you noticed after we ran the command above, ESLint gave us an extra message:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/lint-fix-option.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Lint results - Option to fix</em></p>
<p>So let’s give it a try! Let’s run:</p>
<pre><code>yarn lint --fix
</code></pre><p>And what do you know, it now only gives us 1 linting error.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/lint-with-one-error.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Lint results - 1 error</em></p>
<p>Turns out ESLint was able to fix our semicolon issue automatically, but we’ll still have to add <code>pageName</code> to our <code>Layout</code>’s <code>propTypes</code> manually, not too much of a lift.</p>
<p>Running one more time and finally nothing again! But this time because everything's looking good.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/lint-with-nothing-happening-2.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Lint results - No errors</em></p>
<h2 id="heading-go-forth-and-write-messy-code"><strong>Go forth and write messy code!</strong></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/10/bruce-almighty-typing.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Bruce Almighty - Typing</em></p>
<p>Kidding ? The good news here, is now you can easily take a look at the general health of your codebase as well as hopefully fix most of it automatically. This is going to save a lot of headaches as you work with others on your team, and generally, it’s nice to have all of your code neat and tidy.</p>
<p>This post is just getting started. ESLint is a wide open book with tons of plugins and rules, and it’s not the only linting tool in the game. Play around and find what fits best for you and your team. The little time spent configuring it to your app will save you lots more time in the long run.</p>
<h2 id="heading-other-linting-tools-to-check-out"><strong>Other linting tools to check out</strong></h2>
<ul>
<li><a target="_blank" href="https://jshint.com/">JSHint</a>: an alternative to ESLint</li>
<li><a target="_blank" href="https://github.com/stylelint/stylelint">Stylelint</a>: a linting tool for CSS and CSS-like syntaxes like <a target="_blank" href="https://sass-lang.com/">Sass</a></li>
<li><a target="_blank" href="https://github.com/dustinspecker/awesome-eslint">Awesome ESLint</a>: a simple list of awesome configs, parsers, plugins, and other tools to boost your ESLint game</li>
<li><a target="_blank" href="https://webhint.io/">Webhint</a>: linting tool for accessibility, speed, and more website best practices</li>
<li><a target="_blank" href="https://github.com/evcohen/eslint-plugin-jsx-a11y">A11y JSX Plugin</a>: ESLint plugin for checking accessibility rules on JSX elements</li>
</ul>
<div id="colbyfayock-author-card">
  <p>
    <a href="https://twitter.com/colbyfayock">
      <img src="https://res.cloudinary.com/fay/image/upload/w_2000,h_400,c_fill,q_auto,f_auto/w_1020,c_fit,co_rgb:007079,g_north_west,x_635,y_70,l_text:Source%20Sans%20Pro_64_line_spacing_-10_bold:Colby%20Fayock/w_1020,c_fit,co_rgb:383f43,g_west,x_635,y_6,l_text:Source%20Sans%20Pro_44_line_spacing_0_normal:Follow%20me%20for%20more%20JavaScript%252c%20UX%252c%20and%20other%20interesting%20things!/w_1020,c_fit,co_rgb:007079,g_south_west,x_635,y_70,l_text:Source%20Sans%20Pro_40_line_spacing_-10_semibold:colbyfayock.com/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_68,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_145,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_222,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_295,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/v1/social-footer-card" alt="Follow me for more Javascript, UX, and other interesting things!" width="2000" height="400" loading="lazy">
    </a>
  </p>
  <ul>
    <li>
      <a href="https://twitter.com/colbyfayock">? Follow Me On Twitter</a>
    </li>
    <li>
      <a href="https://youtube.com/colbyfayock">?️ Subscribe To My Youtube</a>
    </li>
    <li>
      <a href="https://www.colbyfayock.com/newsletter/">✉️ Sign Up For My Newsletter</a>
    </li>
  </ul>
</div>

<p><em>Originally published</em> at <a target="_blank" href="https://www.colbyfayock.com/2019/10/what-is-linting-and-how-can-it-save-you-time">https://www.colbyfayock.com/2019/10/what-is-linting-and-how-can-it-save-you-time</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A Learning Path for Newbies in WordPress Development ]]>
                </title>
                <description>
                    <![CDATA[ By Ihtisham Zahoor In this information age, one obstacle in learning something new is not where to find the resources. It’s from where to start and make sense of all the resources available online these days. This holds especially true in web develop... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learning-path-for-newbies-in-wordpress-development-a283981adf53/</link>
                <guid isPermaLink="false">66d45f32b6b7f664236cbdcc</guid>
                
                    <category>
                        <![CDATA[ Bootstrap ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS3 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Design ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML5 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ jQuery ]]>
                    </category>
                
                    <category>
                        <![CDATA[ js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ PHP ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Sass ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ WordPress ]]>
                    </category>
                
                    <category>
                        <![CDATA[ wordpress plugins ]]>
                    </category>
                
                    <category>
                        <![CDATA[ WordPress Theme ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 12 Sep 2018 18:46:58 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*RlFuY9MLjBJDt1U5" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ihtisham Zahoor</p>
<p>In this information age, one obstacle in learning something new is not where to find the resources. It’s from where to start and make sense of all the resources available online these days. This holds especially true in web development when new tools are popping up overnight.</p>
<p>Back in 2015, since I first decided to learn web development, I have faced challenges of self-doubt and lack of motivation. But the one challenge which drained my energies was not knowing what path to follow.</p>
<p>Considering the initial challenges in this path I have written this piece for technology enthusiasts who want to get their hands dirty in web development. Especially WordPress development. All in the hope you are going to spend your time building something cool than getting into this never-ending vicious cycle of learning one tool to another.</p>
<h1 id="heading-caution-a-lot-of-learning-in-this-path"><strong>Caution! A lot of learning in this path</strong></h1>
<p>I am a WordPress developer (although my impostor syndrome tells me otherwise). I can share my experience only related to WordPress. But before diving into details, let’s examine a Q/A session first.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/NXiCcxwi7e3plLZMWr3KAfpSuCMA1KA5ODNe" alt="Image" width="700" height="418" loading="lazy"></p>
<p>Now, is the answer mean? Maybe. Is it true? Absolutely! WordPress and Web Development, in general, are as serious and demanding as any profession. So be ready for…</p>
<ul>
<li>Lifetime of Learning</li>
<li>Pulling all-nighters occasionally</li>
</ul>
<p>All right, have you read and understood the above points? Great. Now relax as it is not to discourage you or anything. It’s just how the life of a developer is as the ever-changing nature of this field requires.</p>
<p>The good news is there are not many web technologies you have to learn to master the craft of WordPress Development. That being said, give your time to this amazing piece of software, and WordPress will adore you in return.</p>
<p>WordPress will change your life if you let it — Chris Lema</p>
<p>It’s all inspiring and cute, right? It is one of the reasons <a target="_blank" href="https://topher1kenobe.com/">Topher DeRosia</a> (huge props) has provided the <a target="_blank" href="https://heropress.com/">HeroPress</a> platform for WordPressers (yes, this is what we proudly call ourselves). Here WordPressers share regularly their WordPress origin stories with the <a target="_blank" href="https://opensource.org/community">community</a>. Rest assured while reading through the stories you are going to feel adrenaline rush through your body as many of you are going to find yourself related to those stories.</p>
<h1 id="heading-wordpress-for-everyone">WordPress for Everyone!</h1>
<p>WordPress is super easy to use. In fact, anyone without any technical knowledge, can set up and start using WordPress in no time. However, WordPress has a vast ecosystem. I, for one, would categorize WordPress development being carried out in two different domains. I’ll first list those domains below and then I will discuss each one separately.</p>
<ul>
<li>WordPress Site Customization</li>
<li>WordPress Themes/Plugins Development</li>
</ul>
<h1 id="heading-wordpress-site-customization">WordPress Site Customization</h1>
<p>WordPress Site Customization is where all the buzz is about, as it amounts for most of the work done with respect to WordPress usage. Site Customization is that domain where no prior coding knowledge is required.</p>
<p>That is to say, a WordPress power user can easily perform tasks like Theme/Plugin setup and customization using page builders, site debugging, and site maintenance, etc. Moreover, Theme customization is all about customizing or modifying a pre-made theme as per the requirements of your client.</p>
<p>Considering that, and to give you a perspective about the process, you can watch the following short tutorial by Tyler Moore. In his tutorial, he builds a new website by customizing a pre-made theme using the Elementor page builder.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/8AZ8GqW5iak" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h1 id="heading-wordpress-themesplugins-development">WordPress Themes/Plugins Development</h1>
<p>It is where all the fun is for WordPress geeks. We can call it the <em>actual</em> WordPress development, as this domain is all about knowing and getting into the nitty-gritty technical details of programming. It can be as simple as using a few WordPress hooks to modify responses or as complex as building a full-fledge product on WordPress.</p>
<p>So, in case you want to start into this domain, you have to invest more time learning about web technologies involved in WordPress development. Considering that, the rest of this article will discuss all the technologies and a few tips and tricks to get you started in <em>actual</em> WordPress development.</p>
<h1 id="heading-learning-path"><strong>Learning Path</strong></h1>
<p>To get started in your WordPress Development journey, these tools and technologies are what you are going to be working with.</p>
<ol>
<li><p>Say hello and embrace g̵o̵o̵d̵ ̵o̵̵̵l̵̵̵’ HTML5 modules with Semantics and Accessibility concepts. HTML is what gives structure to the site contents.</p>
</li>
<li><p>This quote says it all:</p>
</li>
</ol>
<p>You are the CSS to my HTML — Some Genius</p>
<p>CSS is how HTML is presented in the web browser. Make sure to learn SASS preprocessor as your savior in writing modular CSS once you get a grasp of the basics.</p>
<ol start="3">
<li>The organization behind WordPress has big plans for making JavaScript part of the WordPress Front-end. This officially came from the original author of WordPress.</li>
</ol>
<p>Learn JavaScript, Deeply — Matt Mullenweg</p>
<p>Yes, I know that might be far-fetched for a newbie who is starting out to follow this advice, but keep an eye out for development in this area. Now, this doesn’t mean you have to master JavaScript to work with WordPress. Start with the basics including its hugely popular library jQuery.</p>
<ol start="4">
<li><p>Wouldn’t it be nice if you could get a 1000-step head-start with these three technologies to speed up your development process? Well, that is where front-end frameworks like <a target="_blank" href="http://getbootstrap.com/">Twitter Bootstrap</a> come into play. Explore it and get amazed. Don’t confuse front-end frameworks with JavaScript frameworks. Front-end is used interchangeably with JavaScript libraries and frameworks, which is a whole different path.</p>
</li>
<li><p>PHP is the scripting language that powers WordPress. If you want to dive deep in WordPress, learn PHP head-first with its OOP concepts including MySQL as its back-end database.</p>
</li>
<li><p>In general, when people talk about WordPress Development, it usually means only two segments of WordPress.</p>
</li>
<li><p>WordPress Theme Development, which is developing a presentation (layout) of sites (hence the name “Theme”).</p>
</li>
<li>WordPress Plugin Development, which is to add functionality to WordPress sites</li>
</ol>
<p>For a developer, it is of utmost importance to understand and be comfortable working with both these segments. And to add a tad bit more in your learning journey, get familiar with Internationalization and Localization. You also need to know WordPress Hooks and APIs to name a few.</p>
<p>While developing sites, most of your time is going to be spent in a local development environment and in a code editor. For the sake of complete information in this article, let me point you to an easy-to-setup yet powerful local development environment (<a target="_blank" href="https://local.getflywheel.com/">Local by Flywheel</a>) and lightning-fast code editor (<a target="_blank" href="https://code.visualstudio.com/">Visual Studio Code</a> by Microsoft). Yes, they are both free of cost like WordPress.</p>
<h2 id="heading-workflow"><strong>Workflow</strong></h2>
<p>As your workflow becomes more advanced and complex, it’s important for you to stay sane and keep enjoying life. In that case, you are going to need to streamline your workflow. Try task automation tools like <a target="_blank" href="https://gruntjs.com/">Grunt</a>/<a target="_blank" href="https://gulpjs.com/">Gulp</a> and use a version control system like <a target="_blank" href="https://git-scm.com/">git</a> to keep you from making blunders.</p>
<h2 id="heading-illustration-of-learning-path-guide-published-on-github"><strong>Illustration of Learning Path Guide Published on GitHub</strong></h2>
<p>To make things more clear for you, I have published an illustration of the Learning Path as a step-by-step guide on <a target="_blank" href="https://github.com/ihtishamzahoor/wordpress-learning-path">GitHub</a> which I have provided below.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/BglSkXSPbis8Tkk86z5kuf3VVx4Pt2KNkdfx" alt="Image" width="800" height="584" loading="lazy"></p>
<p>Learn from it, give feedback, improve it to make it better for newbies, and by that means feel free to send PR requests.</p>
<h1 id="heading-resources"><strong>Resources</strong></h1>
<p>In case you are still worried that you are going to need more than a bunch of motivational words to actually start doing meaningful work, maybe you need like a step by step guide — well, worry no more. Follow the <a target="_blank" href="https://developer.wordpress.org/"><strong><em>WordPress WordPress Developer Handbook</em></strong></a> and <a target="_blank" href="https://codex.wordpress.org/"><strong><em>WordPress Developer Codex</em></strong></a> like religion and consider yourself in safe hands.</p>
<p>Moreover, you can receive great help from the <a target="_blank" href="https://wordpress.org/support/"><strong><em>WordPress Support</em></strong></a> forum as well as digging your answers from the Q&amp;A site <a target="_blank" href="https://stackoverflow.com/"><strong><em>Stack Overflow</em></strong></a>, which is immensely popular among the developer community.</p>
<p>Apart, from the official WordPress resources, support forum, and developer-centric Q&amp;A sites. There are a plethora of sites like <a target="_blank" href="https://wpbeginner.com/"><strong><em>WPBeginner</em></strong></a><strong><em>,</em></strong> made possible by the awesome WordPress community, offering WordPress centric free tutorials and guides.</p>
<p><a target="_blank" href="https://www.codexspot.com/category/tutorials/"><strong><em>CodexSpot</em></strong></a> is one such attempt by a bunch of <a target="_blank" href="https://www.codexspot.com/about-us/"><em>WordPress geeks</em></a> including yours truly to give back to the community. <em>CodexSpot</em> is an online platform, focused solely on providing web solutions. Our aim is to provide quality tutorials, DIY guides, and keep you up-to-date with web industry news and trend reports.</p>
<p>We are a huge supporter of free and open-source software initiative and don’t miss any opportunity to evangelize FOSS practices to promote this movement. Besides that, we also offer free web development generators and tools to speed up your development time.</p>
<p>Now, there is one other type of learning resource, which is premium courses. By comparison with free resources, the main benefit of premium ones is the timely support offered by the course instructors for their students. That is to say, the ability to get your queries answered by the very instructors from whom you are learning, hugely benefits you during your learning journey. Furthermore, they stay on top of the latest industry trends.</p>
<p>I have personally learned a great deal from the <a target="_blank" href="https://www.lynda.com/learning-paths/Web/become-a-junior-wordpress-developer"><strong><em>Lynda.com</em></strong></a> (now <em>LinkedIn Learning</em>) courses, highly recommended. I have also found <a target="_blank" href="https://onemonth.com/courses/wordpress"><strong><em>Learn WordPress</em></strong></a> course by <em>Chris Castiglione, a nice beginner-friendly course to start with. So, if you are looking for a premium course on WordPress, you will find any of these courses worth your buck</em>.</p>
<p>At this point, you have the dedication and tons of resources readily available for you to learn everything about WordPress. However, it is equally important that you understand the job market and what the companies seek in candidates applying for the WordPress developer position.</p>
<p><a target="_blank" href="https://www.toptal.com/">Toptal</a>, an exclusive network of the top freelancers in the world, has published a guide for hiring a “<a target="_blank" href="https://www.toptal.com/wordpress#hiring-guide">Great WordPress Developer</a>” which you can read to better align yourself with the most in-demand WordPress skills.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>Don’t try to learn everything at once. Start with the basics. Implement what you’ve learned and then build from there. Take note of these following two not hard-and-fast rules for guidance, as these rules will come in handy in your journey.</p>
<ul>
<li><em>Just in Time (JIT) learning</em> is you learn the tool when you need it.</li>
<li><em>80/20 rule of learning</em> is you give 20% of your time to learning and 80% of your time implementing what you have learned already.</li>
</ul>
<p>Now repeat after me:</p>
<p>I learn.<br>I code!<br>I code again!!<br>I code some more!!!<br>I keep coding!!!!!</p>
<p>…and that is how you start in WordPress. Good Luck WordPresser and welcome to the WordPress family!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
