<?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[ Kamaldeen Lawal - 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[ Kamaldeen Lawal - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 24 May 2026 16:29:54 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/Kamaldeen/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ The JavaScript this Keyword Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ All leading web browsers support JavaScript, a popular and versatile programming language. The this keyword is a very important concept to know in JavaScript. The this keyword is a reference to an object, but the object varies based on where and how ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-javascript-this-keyword-explained-with-examples/</link>
                <guid isPermaLink="false">66d0396f871ae63f179f6bf0</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kamaldeen Lawal ]]>
                </dc:creator>
                <pubDate>Wed, 05 Jun 2024 14:58:48 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/Python-Data-Types--3-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>All leading web browsers support JavaScript, a popular and versatile programming language. The <code>this</code> keyword is a very important concept to know in JavaScript.</p>
<p>The <code>this</code> keyword is a reference to an object, but the object varies based on where and how it is called.</p>
<p>In this article, you'll learn how to implicitly (based on context) and explicitly (using the <code>call()</code>,  <code>apply()</code>, and <code>bind()</code> methods) determine the value of the <code>this</code> keyword. </p>
<p>Here are the topics we will be covering:</p>
<ul>
<li><a class="post-section-overview" href="#heading-what-are-the-rules-that-guide-the-behavior-of-the-this-keyword">What are the Rules that Guide the Behavior of the <code>this</code> keyword</a>?</li>
<li><a class="post-section-overview" href="#heading-what-is-the-call-method-in-javascript">What is the <code>call()</code> Method in JavaScript</a>?</li>
<li><a class="post-section-overview" href="#heading-what-is-the-apply-method-in-javascript">What is the <code>apply()</code> Method in JavaScript</a>?</li>
<li><a class="post-section-overview" href="#heading-what-is-the-bind-method-in-javascript">What is the <code>bind()</code> Method in JavaScript</a>?</li>
<li><a class="post-section-overview" href="#heading-why-were-the-call-apply-and-bind-methods-introduced-to-javascript">Why were the <code>call()</code>, <code>apply()</code>, and <code>bind()</code> Methods Introduced to JavaScript?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-the-differences-between-the-call-apply-and-bind-methods">What are the Differences Between the <code>call()</code>, <code>apply()</code>, and <code>bind()</code> Methods?</a></li>
<li><a class="post-section-overview" href="#heading-why-use-the-call-apply-and-bind-methods-in-javascript">Why Use the <code>call()</code>, <code>apply()</code>, and <code>bind()</code> Methods in Javascript?</a></li>
</ul>
<h2 id="heading-what-are-the-rules-that-guide-the-behavior-of-the-this-keyword">What are the Rules that Guide the Behavior of the <code>this</code> keyword?</h2>
<p>Some rules guide the behavior of  the <code>this</code>  keyword in JavaScript. They are the global scope, function context, object method, constructor, and event handlers.</p>
<h3 id="heading-global-scope">Global Scope</h3>
<p>Whenever the <code>this</code> keyword is used outside of any function, it refers to the global object. </p>
<p>While the global object is <code>global</code> in the Node.js environment, it's a <code>window</code> in the context of a web browser:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
</code></pre>
<p><img src="https://hackmd.io/_uploads/Hy3UshesT.png" alt="bind 1" width="600" height="400" loading="lazy">
<em>Global Scope Result</em></p>
<p>The result from the code above shows that <code>this</code> returns the <code>window</code>, which is the global object for the web browser.</p>
<h3 id="heading-function-context">Function Context</h3>
<p>The method of invocation determines the value of the <code>this</code> keyword in a standard regular function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">saySomething</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>)
}

saySomething()  <span class="hljs-comment">// {window: Window, self: Window, document: document, name: '', location: Location, …}</span>
</code></pre>
<p><img src="https://hackmd.io/_uploads/H1oponlia.png" alt="bind 1" width="600" height="400" loading="lazy">
<em>Function context result</em></p>
<p>The above code result is the global object for the web browser.</p>
<h3 id="heading-object-method">Object Method</h3>
<p>Methods are function-holder properties of an object. In JavaScript, they allow an object to manipulate its properties using <code>this</code> keyword:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> club = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Arsenal"</span>,
  <span class="hljs-attr">yearFounded</span>: <span class="hljs-string">"1989"</span>,
  details() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Hey, <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.yearFounded}</span>`</span>;
  },
};

<span class="hljs-built_in">console</span>.log(club.details()); <span class="hljs-comment">// Arsenal , 1989</span>
</code></pre>
<p>In the context of the above code, <code>this</code> refers to the <code>club</code>. As you can see from the output, it says <code>Arsenal 1989</code>.</p>
<p>But we would have a different result if we created a new variable for the details method, as shown below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> club = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Arsenal"</span>,
  <span class="hljs-attr">yearFounded</span>: <span class="hljs-string">"1989"</span>,
  details() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`Hey, <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.yearFounded}</span>`</span>;
  },
};

<span class="hljs-keyword">const</span> full = club.details;
<span class="hljs-built_in">console</span>.log(full()); <span class="hljs-comment">// Hey,  undefined</span>
</code></pre>
<p>Although the <code>details()</code> method was defined inside the <code>club</code> object, it's not expressly bound to it. We call the <code>details()</code> as a method on the object.</p>
<p>In JavaScript, a method gets the value of <code>this</code> when it looks at the function that comes before the dot.</p>
<h3 id="heading-constructor-function">Constructor Function</h3>
<p>It's not news that the function constructor was the default initializer for user-defined objects before the introduction of the ECMAScript 2015 update.</p>
<p>The <code>new</code> keyword creates an instance of a constructor function:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Country</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
  <span class="hljs-built_in">this</span>.age = <span class="hljs-number">1960</span>;

  <span class="hljs-built_in">this</span>.info = <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">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> was founded <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years ago`</span>);
  };
}

<span class="hljs-keyword">const</span> country = <span class="hljs-keyword">new</span> Country(<span class="hljs-string">"Nigeria"</span>);
<span class="hljs-built_in">console</span>.log(country.name);
<span class="hljs-built_in">console</span>.log(country.info());
</code></pre>
<p><img src="https://hackmd.io/_uploads/Skn8R3eip.png" alt="nigeria" width="600" height="400" loading="lazy">
<em>Constructor function result</em></p>
<p>The <code>this</code> refers to the newly created object, in this case, the instance of the country.</p>
<h3 id="heading-event-handlers">Event Handlers</h3>
<p>In an <code>addEventListener</code> event handler,  <code>this</code> refers to the element before the dot. This is the element that the event listener was added to trigger the event:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"button"</span>);

button.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
});

<span class="hljs-comment">// OUTPUT  &lt;button&gt;click&lt;/button&gt;</span>
</code></pre>
<p>Once the above code runs, a button with an <code>innerText</code> value of <code>click</code> will be logged to the console.</p>
<p>In all the above rules that guide the behavior of the popular <code>this</code> keyword, one thing is clear: the context determines the value of the <code>this</code> keyword.</p>
<p>Aside from implicitly determining the value of <code>this</code>, function methods like <code>call()</code>, <code>apply()</code>, and <code>bind()</code> can be used to explicitly determine what <code>this</code> should refer to.</p>
<h2 id="heading-what-is-the-call-method-in-javascript">What is the <code>call()</code> Method in JavaScript?</h2>
<p>The <code>call()</code> method is one of the most popular ways to explicitly define what <code>this</code> refers to.  In JavaScript, the <code>call()</code> method is mostly used to borrow a method from an isolated object and use it on another with a specific context.</p>
<p>The <code>call()</code> method requires its arguments to be passed one by one:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> game = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"PrisonBreak"</span>,
  <span class="hljs-attr">year</span>: <span class="hljs-number">1979</span>,
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">detail</span>(<span class="hljs-params"></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>.title}</span>, was released in <span class="hljs-subst">${<span class="hljs-built_in">this</span>.year}</span>`</span>);
}
detail();

<span class="hljs-comment">// RESULT undefined was released in undefined</span>
</code></pre>
<p>The above prints the result because there's no connection between the <code>game</code> and the <code>detail</code> method. Hence, calling the <code>detail</code> method by itself will only print <code>undefined</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> game = {
  <span class="hljs-attr">fullDetail</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.title + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.year;
  },
};

<span class="hljs-keyword">const</span> newGame = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"Merlin"</span>,
  <span class="hljs-attr">year</span>: <span class="hljs-number">1994</span>,
};

<span class="hljs-keyword">const</span> fullDetail = game.fullDetail.call(newGame);
<span class="hljs-built_in">console</span>.log(fullDetail); <span class="hljs-comment">// Output: Merlin 1994</span>
</code></pre>
<p>In the code above, there are <code>game</code> and  <code>newGame</code> objects. The <code>game</code> has a <code>fullDetail</code> method, while the <code>newGame</code> has title and year has properties.</p>
<p>As we know from the definition above, the <code>call()</code> method used the context of <code>newGame</code> to invoke the <code>fullDetail</code> method of the <code>game</code> object.</p>
<p>This means that, we have access to the <code>newGame</code> properties because the <code>this</code> inside of <code>fullDetail</code> refers to <code>newGame</code> object.</p>
<p>We now have a connection between the <code>game</code> and the <code>newGame</code> with the help of the <code>call()</code> method.</p>
<p>Aside from passing <code>this</code> as an argument, there's provision for passing additional arguments individually:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> game = {
  <span class="hljs-attr">fullDetail</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">category</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.title}</span> was released <span class="hljs-subst">${<span class="hljs-built_in">this</span>.year}</span>, and the film is a <span class="hljs-subst">${category}</span> film`</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.title + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.year + <span class="hljs-string">" "</span> + <span class="hljs-string">"category"</span>;
  },
};

<span class="hljs-keyword">const</span> newGame = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"Merlin"</span>,
  <span class="hljs-attr">year</span>: <span class="hljs-number">1994</span>,
};

<span class="hljs-keyword">const</span> fullDetail = game.fullDetail.call(newGame, <span class="hljs-string">"seasonal"</span>);

<span class="hljs-built_in">console</span>.log(fullDetail); <span class="hljs-comment">// Merlin was released 1994, and the film is a seasonal film</span>
</code></pre>
<p>The above code shows the possibility of passing another argument aside <code>this</code> keyword.</p>
<h3 id="heading-how-to-use-the-call-method-in-a-real-world-application">How to Use the call() Method in a Real World Application</h3>
<div class="embed-wrapper"><iframe height="300" style="width:100%" src="https://codepen.io/kamal90/embed/gOygyaO?default-tab=js" title="Embedded content" loading="lazy">
  See the Pen <a href="https://codepen.io/kamal90/pen/gOygyaO">
  call and apply javascript</a> by kamaldeeen (<a href="https://codepen.io/kamal90">@kamal90</a>)
  on <a href="https://codepen.io">CodePen</a>.
</iframe></div>

<p>The following code was extracted from the code above:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newMovie = {
    <span class="hljs-attr">info</span>: {
      title,
      [extraName]: extraValue,
    },
    <span class="hljs-attr">id</span>: <span class="hljs-built_in">Math</span>.random(),
    formatted() {
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.info.title.toUpperCase();
    }
  };
</code></pre>
<p>The above code is an object named <code>newMovie</code>. In the <code>newMovie</code> object, an <code>info</code> object with <code>title</code> and  <code>extraName</code> was created.</p>
<p>The <code>title</code> is the name of the movie, while the <code>[extraName]</code> line uses bracket notation to dynamically access the user input, using the value of the variable as the key name. While the <code>extraValue</code> is the value associated with the key.</p>
<p>The <code>id</code> is the unique identifier that generates a random number using the <code>Math.random()</code> function.</p>
<p>The <code>formatted()</code> method returns the uppercase format of the title. By using the <code>this.info.title</code>, where the <code>newMovie</code> object is the same as <code>this</code>, and the <code>info</code>is an object inside the <code>newMovie</code> that contains information like the title, and the rest.</p>
<pre><code class="lang-javascript">
filteredMovies.forEach(<span class="hljs-function">(<span class="hljs-params">movie</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> newMovieEl = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'li'</span>);
    <span class="hljs-keyword">const</span> {info} = movie;
    <span class="hljs-keyword">const</span> {formatted} = movie
    <span class="hljs-keyword">let</span> text = formatted.call(movie) + <span class="hljs-string">'-'</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">in</span> info) {
      <span class="hljs-keyword">if</span> (key !== <span class="hljs-string">'title'</span>) {
        text = text + <span class="hljs-string">`<span class="hljs-subst">${key}</span>: <span class="hljs-subst">${info[key]}</span>`</span>
      }
    }
    newMovieEl.textContent = text;
    movieList.append(newMovieEl)

  })
}
</code></pre>
<p>The above code shows the uses of the <code>call()</code> method in a real world application.</p>
<p>Let's explain what's happening in the code.</p>
<p>The line <code>const newMovieEl = document.createElement('li');</code> creates a new <code>&lt;li&gt;</code> element using <code>document.createElement('li')</code>, with the new element stored in the constant <code>newMovieEl</code>.</p>
<p>The line <code>const {info} = movie;</code> uses destructuring assignment to extract the <code>info</code> property from the movie object.</p>
<p>The line <code>const {formatted} = movie</code> uses destructuring assignment to extract the <code>formatted</code> method from the movie object.</p>
<p>The line <code>let text = formatted.call(movie) + '-';</code> shows how to use the <code>call()</code> method in an application.</p>
<p>Invoking the <code>formatted</code> function directly will not give the required result, as the function of <code>this</code> in that context is the window object.</p>
<p>By using the <code>call</code> method on the <code>formatted</code> function, the <code>call()</code> method allows the context of the <code>this</code> to change from the window object to the<code>movie</code> object.</p>
<p>As said above, in JavaScript, the <code>call()</code> method is used to borrow a method from an isolated object and use it on another with a specific context.</p>
<p>The <code>call()</code> method requires its arguments to be passed one by one, and executes the function instantly.</p>
<p>The line <code>for (const key in info) {if (key !== 'title') {text = text +</code> ${key}: ${info[key]}<code>}</code> iterates over each key in the info object and checks if the current key is not equal to <code>title</code>. It then appends the key-value pair to the text string.</p>
<p>The line <code>newMovieEl.textContent = text movieList.append(newMovieEl)</code> sets the text content of the newly created list item element to the generated text, and appends the newly created list item element to the parent element with the id <code>movieList</code>.</p>
<h2 id="heading-what-is-the-apply-method-in-javascript">What is the <code>apply()</code> Method in JavaScript?</h2>
<p>The <code>apply()</code> method is similar to the <code>call()</code> method, with the only difference being that the <code>apply()</code> method takes arguments as an array (or array-like object), while arguments get passed individually to the <code>call()</code> method.</p>
<p>To get started with the <code>apply()</code> method, let's check its syntax:</p>
<pre><code class="lang-javascript">nameOfFunction.apply(thisArg, [argsArray])
</code></pre>
<p>The <code>nameOfFunction</code> is the function to be called, <code>thisArg</code> is the <code>this</code> value provided for the function, and the array or array-like object is the <code>argsArray</code> to be passed to the function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> game = {
  <span class="hljs-attr">fullDetail</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.title + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.year;
  },
};

<span class="hljs-keyword">const</span> newGame = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"Merlin"</span>,
  <span class="hljs-attr">year</span>: <span class="hljs-number">1994</span>,
};

<span class="hljs-keyword">const</span> fullDetail = game.fullDetail.apply(newGame);
<span class="hljs-built_in">console</span>.log(fullDetail); <span class="hljs-comment">// Output: Merlin 1994</span>
</code></pre>
<p>Just as in the <code>call()</code> method, there are <code>game</code> , and <code>newGame</code> objects. The <code>game</code> has a <code>fullDetail</code> method, while the <code>newGame</code> has a title and year has properties.</p>
<p>As we know from the definition above, the <code>apply()</code> method used the context of <code>newGame</code> to invoke the <code>fullDetail</code> method of the <code>game</code> object.</p>
<p>This means that, we have access to the <code>newGame</code> properties because the <code>this</code> inside of <code>fullDetail</code> refers to the <code>newGame</code> object.</p>
<p>We now have a connection between the <code>game</code> and the <code>newGame</code> with the help of the <code>apply()</code> method.</p>
<p>The <code>apply()</code> method can also be used to pass an array or  array-like collection as an argument.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> game = {
  <span class="hljs-attr">fullDetail</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">greet</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${greet}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.title}</span> <span class="hljs-subst">${<span class="hljs-built_in">this</span>.year}</span>`</span>;
  },
};

<span class="hljs-keyword">const</span> newGame = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"Merlin"</span>,
  <span class="hljs-attr">year</span>: <span class="hljs-number">1994</span>,
};

<span class="hljs-keyword">const</span> fullDetail = game.fullDetail.apply(newGame, [<span class="hljs-string">"Welcome"</span>]);
<span class="hljs-built_in">console</span>.log(fullDetail); <span class="hljs-comment">// Output: Welcome Merlin 1994</span>
</code></pre>
<p>The above code shows that the <code>fullDetail</code> function inside the <code>game</code> object expects a <code>greet</code> parameter. The <code>apply()</code> method is used to invoke the <code>fullDetail</code> with the <code>newGame</code> object and the array <code>['Welcome']</code> as an argument passed to the function.</p>
<h3 id="heading-how-to-use-the-apply-method-in-a-real-world-application">How to Use the apply() Method in a Real World Application</h3>
<div class="embed-wrapper"><iframe height="300" style="width:100%" src="https://codepen.io/kamal90/embed/GRLWYoN?default-tab=js" title="Embedded content" loading="lazy">
  See the Pen <a href="https://codepen.io/kamal90/pen/GRLWYoN">
  Apply</a> by kamaldeeen (<a href="https://codepen.io/kamal90">@kamal90</a>)
  on <a href="https://codepen.io">CodePen</a>.
</iframe></div>

<p>The following code was extracted from the code above:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> newMovie = {
    <span class="hljs-attr">info</span>: {
      title,
      [extraName]: extraValue,
    },
    <span class="hljs-attr">id</span>: <span class="hljs-built_in">Math</span>.random(),
    formatted() {
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.info.title.toUpperCase();
    }
  };
</code></pre>
<p>The above code is an object named <code>newMovie</code>. In the <code>newMovie</code> object, an <code>info</code> object with <code>title</code>,<code>extraName</code> was created.</p>
<p>The <code>title</code> is the name of the movie, while the <code>[extraName]</code> line uses bracket notation to dynamically access the user input, using the value of the variable as the key name. While the <code>extraValue</code> is the value associated with the key.</p>
<p>The <code>id</code> is the unique identifier that generates a random number using the <code>Math.random()</code> function.</p>
<p>The <code>formatted()</code> method returns the uppercase format of the title. By using the <code>this.info.title</code>, where the <code>newMovie</code> object is the same as <code>this</code>, and the <code>info</code>is an object inside the <code>newMovie</code> that contains information like the title, and the rest.</p>
<pre><code class="lang-javascript">
filteredMovies.forEach(<span class="hljs-function">(<span class="hljs-params">movie</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> newMovieEl = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'li'</span>);
    <span class="hljs-keyword">const</span> {info} = movie;
    <span class="hljs-keyword">const</span> {formatted} = movie
    <span class="hljs-keyword">let</span> text = formatted.apply(movie) + <span class="hljs-string">'-'</span>;
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> key <span class="hljs-keyword">in</span> info) {
      <span class="hljs-keyword">if</span> (key !== <span class="hljs-string">'title'</span>) {
        text = text + <span class="hljs-string">`<span class="hljs-subst">${key}</span>: <span class="hljs-subst">${info[key]}</span>`</span>
      }
    }
    newMovieEl.textContent = text;
    movieList.append(newMovieEl)

  })
}
</code></pre>
<p>The above code shows the uses of the <code>apply()</code> method in a real world application.</p>
<p>Now, let's explain the code.</p>
<p>The line <code>const newMovieEl = document.createElement('li');</code> creates a new <code>&lt;li&gt;</code> element using <code>document.createElement('li')</code>, with the new element stored in the constant <code>newMovieEl</code>.</p>
<p>The line <code>const {info} = movie;</code>uses destructuring assignment to extract the <code>info</code> property from the movie object.</p>
<p>The line <code>const {formatted} = movie</code>uses destructuring assignment to extract the <code>formatted</code> method from the movie object.</p>
<p>The line <code>let text = formatted.apply(movie) + '-';</code>shows how to use the <code>apply()</code> method in an application.</p>
<p>Invoking the <code>formatted</code> function directly will not give the required result, as the function of <code>this</code> in that context is the window object.</p>
<p>By using the <code>apply</code> method on the <code>formatted</code> function, the <code>apply()</code> method allows the context of  <code>this</code> to change from the window object to <code>movie</code> object.</p>
<p>As said above, in JavaScript, the <code>apply()</code> method takes arguments as an array (or array-like object), and executes the function instantly.</p>
<p>The line <code>for (const key in info) {if (key !== 'title') {text = text +</code> ${key}: ${info[key]}<code>}</code>iterates over each key in the info object and checks if the current key is not equal to <code>title</code>.</p>
<p>It then appends the key-value pair to the text string.</p>
<p>The line <code>newMovieEl.textContent = text movieList.append(newMovieEl)</code> sets the text content of the newly created list item element to the generated text, and appends the newly created list item element to the parent element with the id <code>movieList</code>.</p>
<h2 id="heading-what-is-the-bind-method-in-javascript">What is the <code>bind()</code> Method in JavaScript?</h2>
<p>The <code>bind()</code> method creates a new function that has its <code>this</code> keyword set to the provided value and does not immediately call the function.</p>
<p>It is available on all JavaScript functions and is used to permanently set the <code>this</code> context for a function.</p>
<p>The difference between the <code>call()</code>, <code>apply()</code>, and <code>bind()</code> methods is that, the <code>bind()</code> method creates a new function with a bound <code>this</code>,  while both <code>call()</code> and <code>apply()</code> are one time-time-use methods that don't create a new function.</p>
<p>The <code>bind()</code> method doesn't immediately call the function, but both <code>call()</code> and <code>apply()</code> call the function instantly.</p>
<p>Let's look at the syntax for the <code>bind()</code> method:</p>
<pre><code class="lang-javascript">functionName.bind(thisArg[, arg1[, arg2[, ...]]])
</code></pre>
<p>The <code>thisArg</code> represents the value to be passed as <code>this</code> value whenever the function gets executed, and the <code>arg1, arg2, ...</code> are the arguments bound to the function when it gets invoked.</p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> player = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Rooney"</span>,
  <span class="hljs-attr">jerseyNumber</span>: <span class="hljs-number">10</span>,
  <span class="hljs-attr">introduction</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-built_in">this</span>.name + <span class="hljs-string">"wears Jersey number "</span> + <span class="hljs-built_in">this</span>.jerseyNumber + <span class="hljs-string">"."</span>);
  },
};
<span class="hljs-keyword">const</span> player2 = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Jimmy "</span>,
  <span class="hljs-attr">jerseyNumber</span>: <span class="hljs-number">18</span>,
};

<span class="hljs-keyword">let</span> result = player.introduction.bind(player2);

result(); <span class="hljs-comment">// Jimmy wears Jersey number 18.</span>
</code></pre>
<p>In the above code, when you call <code>result()</code>, it prints <code>Jimmy wears Jersey number 18</code>. This is possible because the <code>this</code> keyword inside the introduction method is bound to the <code>player2</code> object.</p>
<p>It is also possible to use the <code>bind()</code> method with more than one argument.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> player = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Rooney"</span>,
  <span class="hljs-attr">jerseyNumber</span>: <span class="hljs-number">10</span>,
  <span class="hljs-attr">introduction</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">goals, country</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> wears Jersey number <span class="hljs-subst">${<span class="hljs-built_in">this</span>.jerseyNumber}</span>, he plays for <span class="hljs-subst">${country}</span>, and he has scored <span class="hljs-subst">${goals}</span> goals`</span>,
    );
  },
};
<span class="hljs-keyword">const</span> player2 = {
  <span class="hljs-attr">name</span>: <span class="hljs-string">"Jimmy "</span>,
  <span class="hljs-attr">jerseyNumber</span>: <span class="hljs-number">18</span>,
};

<span class="hljs-keyword">let</span> result = player.introduction.bind(player2, <span class="hljs-number">87</span>, <span class="hljs-string">"Nigeria"</span>);

result(); <span class="hljs-comment">// Jimmy  wears Jersey number 18, he plays for Nigeria, and he has scored 87 goals</span>
</code></pre>
<p>In the above example, two parameter were passed: <code>thisArg</code> and <code>arg1</code>. Then the <code>player2</code> object is bound to the <code>introduction</code> method which has two parameters: <code>goals</code> and <code>country</code>.</p>
<h3 id="heading-how-to-use-the-bind-method-in-a-real-world-application">How to Use the bind() Method in a Real World Application</h3>
<p>For a proper understanding of how to use the <code>bind()</code> method in a real-world application, there's a need to show the application without the <code>bind()</code> method.</p>
<p>The unconventional calculator is the name of the application we will be building for this exercise.</p>
<div class="embed-wrapper"><iframe height="300" style="width:100%" src="https://codepen.io/kamal90/embed/qBwRWwX?default-tab=js" title="Embedded content" loading="lazy">
  See the Pen <a href="https://codepen.io/kamal90/pen/qBwRWwX">
  Untitled</a> by kamaldeeen (<a href="https://codepen.io/kamal90">@kamal90</a>)
  on <a href="https://codepen.io">CodePen</a>.
</iframe></div>

<p>Let's break down the code.</p>
<p>The above code creates a simple unconventional calculator with the aim of performing basic aritmhemetic operations (addition, subtraction, division, and multiplication).</p>
<p>It takes the user's input, updates the displayed result, and logs calculations.</p>
<ul>
<li>The <code>outputResult(answer, text)</code> function updates the result and the calculation text.</li>
<li>The <code>getUserInput()</code> function retrieves the user's input from the input field.</li>
<li>The task of the <code>writeToLog(operationidentifier, older, olderTwo, newResult)</code> is to format the calculation string for an output.</li>
<li>The <code>createLog(operationidentifier, older, olderTwo, newResult)</code> function creates a log object for the calculation, and stores it in an array.</li>
<li>The <code>createOutput(conditional)</code> performs the core calculation logic based on the provided operation. Operations like <code>add()</code>, <code>subtract()</code>, <code>divide()</code>, and <code>multiply()</code> trigger calculations for their respective operations.</li>
</ul>
<p>Here is the code with the <code>bind()</code> function<strong>:</strong></p>
<div class="embed-wrapper"><iframe height="300" style="width:100%" src="https://codepen.io/kamal90/embed/MWRjXWg?default-tab=js" title="Embedded content" loading="lazy">
  See the Pen <a href="https://codepen.io/kamal90/pen/MWRjXWg">
  Unconventional Calculator</a> by kamaldeeen (<a href="https://codepen.io/kamal90">@kamal90</a>)
  on <a href="https://codepen.io">CodePen</a>.
</iframe></div>

<p>The above code creates simple calculator functionality in JavaScript.</p>
<p>The code takes an input from the user, performs calculations based on button clicks, updates the UI with the results, and maintains a log of past calculations.</p>
<p>Let's break down the JavaScript code in the following sections.</p>
<h4 id="heading-select-all-the-html-elements">Select all the HTML elements</h4>
<p>The code selects all the HTML elements using their IDs.</p>
<p>The <code>addButton</code> , <code>subtractButton</code>, <code>divideButton</code>, and <code>multiplyButton</code>  are elements to display the calculation history.</p>
<p>The <code>result</code> is the element to display the current result and the <code>inputNumber</code>  is an input field for user input.</p>
<h4 id="heading-create-functions-for-output-and-user-input">Create functions for output and user input</h4>
<p>The <code>outputResult (answer, text)</code> function displays the provided answer in the <code>result</code> element and the text in the <code>calculation</code> element.</p>
<p><code>getUserInput()</code> function gets the value entered in the <code>inputNumber</code> field and converts it to an integer.</p>
<h4 id="heading-create-variables-for-calculation-and-logging">Create variables for calculation and logging</h4>
<p><code>defaultResult</code> is a constant set to <code>0</code>, used as the initial result.</p>
<p><code>currentResult</code> is a variable for storing the current result of calculations.</p>
<p><code>logEntries</code> is an array that stores log entries for calculation history.</p>
<p>For logging functions, the <code>writeToLog(prevResult, operand, original)</code> function updates the UI with the calculation description and calls the <code>outputResult</code> function.</p>
<p>The <code>createLog (operationidentifier, older, olderTwo, newResult)</code> function creates a log entry object and pushes it to the <code>logEntries</code> array.</p>
<h4 id="heading-create-calculation-function">Create calculation function</h4>
<p>The <code>calculate (operation)</code> takes an operation string as input ( <code>ADD</code> , <code>SUBTRACT</code>, <code>DIVIDE</code>, or <code>MULTIPLY</code>). It performs calculations based on the following operations:</p>
<p>It adds for <code>ADD</code>, subtracts for <code>SUBTRACT</code>, divides for <code>DIVIDE</code>, multiplies for <code>MULTIPLY</code>.</p>
<p>The <code>writeToLog</code> and <code>createLog</code> functions are called to log the calculation.</p>
<h4 id="heading-create-event-listeners-for-buttons">Create event listeners for buttons</h4>
<p>The <code>addButton.addEventListener('click',calculate.bind(this, 'ADD')</code> assigns an event listener to the <code>addButton</code>.</p>
<p>Similar event listeners are assigned to the <code>subtractButton</code>, <code>divideButton</code>, and <code>multiplyButton</code> for their respective operations.</p>
<p>The code snippet indicates that the <code>calculate</code> function will be executed whenever a button is clicked. The function is bound with the <code>bind()</code> method, and arguments such as <code>ADD</code>, <code>SUBTRACT</code>, <code>MULTIPLY</code>, and <code>DIVIDE</code> are passed to the <code>calculate</code> function.</p>
<h2 id="heading-why-were-the-call-apply-and-bind-methods-introduced-to-javascript">Why were the <code>call()</code>, <code>apply()</code>, and <code>bind()</code> Methods Introduced to JavaScript?</h2>
<p>With these methods, JavaScript applications are more dynamic and adaptable. It affords the programmer more control over how the function is executed.</p>
<p>It is generally hard to have a full grasp of the <code>this</code> keyword in JavaScript. Hence, the introduction of the <code>call()</code>, <code>apply()</code>, and <code>bind()</code> methods gives programmers more control over this quirky subject.</p>
<p>Say you are a versatile footballer who can comfortably play in different positions on the field. In a regular football match, your coach assigns a specific wing for you (the function) and you play according to the coach's instructions (the function's code), and the other footballers you are on the pitch with (the arguments).</p>
<p>With the <code>call()</code> method, your coach can temporarily put you in a different position on the pitch (set the <code>this</code> value) for a specific match. This lets you use your footballing skills even on the wing you wouldn't normally play.</p>
<p>With the <code>apply()</code> method, it is like having a whole football tactics (arguments) full of different technical fouls, delay tactics, and many more. The coach can throw the entire tactics at you, and you can use them all (function execution with a specific context) for the match.</p>
<p>With the <code>bind()</code> method, imagine your coach creating a special understudy role ( <code>bound()</code> function) just for you. This understudy role always has a specific wing on the pitch (predefined <code>this</code>) ready, so you can seamlessly step in and deliver the instructions (function execution) whenever needed.</p>
<h2 id="heading-what-are-the-differences-between-the-call-apply-and-bind-methods">What are the Differences Between the <code>call()</code>, <code>apply()</code>, and <code>bind()</code> Methods?</h2>
<p>When it comes to handling arguments:</p>
<ul>
<li>The <code>call()</code> method accepts arguments individually as a comma separated list.</li>
<li>With the <code>apply()</code> method, the arguments are accepted as an array-like or an array object.</li>
<li>The <code>bind()</code> method can pass in additional arguments when the new function is invoked.</li>
</ul>
<p>When it comes to invocation and execution:</p>
<ul>
<li>The <code>call()</code> method invokes the function immediately with the specific individual arguments and the specified <code>this</code> value, and it accepts argument one by one.</li>
<li>The <code>apply()</code> method just like the <code>call()</code> method invokes the function instantly, but with difference being that it accepts arguments as an array or array like object.</li>
<li>The <code>bind()</code> method creates a new function with an optional arguments and a specified <code>this</code> value. It doesn'timmediatley invoke the function, as it bound the functuion for a later execution.</li>
</ul>
<h2 id="heading-why-use-the-call-apply-and-bind-methods-in-javascript">Why Use the <code>call()</code>, <code>apply()</code>, and <code>bind()</code> Methods in Javascript?</h2>
<p>The <code>call()</code>, <code>apply()</code>, and <code>bind()</code> methods deal extensively with how to control the context of a function ( <code>this</code> keyword) and arguments when it's called.</p>
<p>There are several benefits attached to using these methods in JavaScript:</p>
<ul>
<li><strong>Change the value of the <code>this</code> keyword</strong>: The <code>this</code> keyword refers to the object that calls a certain function. With the help of these methods, you can explicitly set the value of <code>this</code> keyword to something else.</li>
<li><strong>Event Handling</strong>: Both the <code>call()</code> and <code>apply()</code> methods can ensure that the handler is executed with the correct context and arguments, even if its definition space is different from the invocation space.</li>
<li><strong>Flexible arguments</strong>: These methods take arguments in a different way. The <code>call()</code> method takes an individual argument, the <code>apply()</code> method takes an argument as an array, and the <code>bind()</code> method allows for pre-setting some arguments for later use.</li>
<li><strong>Partial function</strong>: The <code>bind()</code> method creates a new function made up of a preset context and optional initial arguments. This is very useful for partial applications, where certain arguments are fixed ahead of time, with others to be provided at a later stage.</li>
<li><strong>Borrowing Functions</strong>: These methods use a function from a new object to another set of object entirely.</li>
</ul>
<p>In a nutshell, they give you enough breathing space over how functions are executed in JavaScript.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you learned about how to implicitly (based on context) and explicitly (by using the <code>call()</code>, <code>apply()</code>, and <code>bind()</code> methods) determine the value of <code>this</code> keyword.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Compare Two Dates in JavaScript – Techniques, Methods, and Best Practices ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript, you can use the date object to work effectively with dates, times, and time zones within an application.  Date objects help you efficiently manipulate data, handle various date-related tasks, and perform some calculations when creating... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/compare-two-dates-in-javascript/</link>
                <guid isPermaLink="false">66d0395e5ea8b15c90716658</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kamaldeen Lawal ]]>
                </dc:creator>
                <pubDate>Mon, 12 Feb 2024 17:57:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Python-Data-Types--2-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript, you can use the date object to work effectively with dates, times, and time zones within an application. </p>
<p>Date objects help you efficiently manipulate data, handle various date-related tasks, and perform some calculations when creating real-world applications.</p>
<p>In this article, we will learn about the following topics:</p>
<ul>
<li><a class="post-section-overview" href="#heading-overview-of-date-comparison">Overview of Date Comparison</a></li>
<li><a class="post-section-overview" href="#heading-importance-of-date-comparison-in-javascript">Importance of Date Comparison in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-date-objects-in-javascript">Date Objects in JavaScript</a></li>
<li><a class="post-section-overview" href="#how-to-create-date-objects">How to Create Date Objects</a></li>
<li><a class="post-section-overview" href="#heading-basics-of-date-comparison">Basics of Date Comparison</a></li>
<li><a class="post-section-overview" href="#heading-how-to-compare-dates-with-comparison-operators">How to Compare Dates with Comparison Operators</a></li>
<li><a class="post-section-overview" href="#heading-how-to-compare-dates-with-the-gettime-method">How to Compare Dates with the</a> <a class="post-section-overview" href="#comparing-dates-with-gettime-method"><code>getTime()</code> Method</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-valueof-method">How to Use the <code>valueOf()</code> Method</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-the-toisostring-method">How to Use the <code>toISOString()</code> Method</a></li>
<li><a class="post-section-overview" href="#heading-challenges-of-comparing-dates-in-javascript">Challenges of Comparing Dates in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></li>
</ul>
<h2 id="heading-overview-of-date-comparison">Overview of Date Comparison</h2>
<p>In JavaScript, the date comparison involves evaluating two dates to determine if one date is earlier, later, or the same as the other. </p>
<p>There are various ways to compare dates, which include (but are not limited to) comparison operators ( <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>, <code>&gt;=</code>) and methods such as <code>getTime()</code> and <code>valueOf()</code>. </p>
<h2 id="heading-importance-of-date-comparison-in-javascript">Importance of Date Comparison in JavaScript</h2>
<p>Date comparison in JavaScript is a important for processing and organizing time-related data, and time-sensitive functionalities in web applications. It's crucial in applications for dealing with data filtering, scheduling, and event handling based on time. </p>
<p>In JavaScript, understanding date comparison techniques allows you to build robust and seamless applications that can withstand various time-related scenarios.</p>
<p>To get going, here are some reasons that date comparison is a key concept to know in JavaScript:</p>
<ul>
<li><strong>Filtering of Data</strong>: Date comparison is crucial in applications where time-sensitive data like transaction records and logs, filtering, and retrieving information are integral parts of the application.</li>
<li><strong>Event Scheduling</strong>: It is easy to determine the status of an event with date comparison. It helps in organizing events, reminders, and tasks.</li>
<li><strong>Arithmetic</strong>: In JavaScript, date comparison facilitates simple arithmetic, such as adding and subtracting time intervals, performing date manipulations, and calculating the duration between two dates.</li>
<li><strong>Conditional Logic</strong>: With date comparison, you can use conditional logic based on time-related condition to trigger an action if a certain event is approaching.</li>
<li><strong>User Experience</strong>: Date comparison enhances the reliability of an application by ensuring that time-related functionalities are working perfectly.</li>
</ul>
<h2 id="heading-date-objects-in-javascript">Date Objects in JavaScript</h2>
<p>In JavaScript, date objects are a very important concept to know. You use them to work with times and dates and provide ways to manipulate, format, and represent dates and times in numerous formats.</p>
<h3 id="heading-how-to-create-a-date-object">How to Create a Date Object</h3>
<p>There are several methods to create a date object in JavaScript. Some of the ways are as follows:</p>
<h4 id="heading-using-the-new-keyword">Using the <code>new</code> keyword</h4>
<pre><code class="lang-javascipt">let currentDate = new Date();
console.log(currentDate)


//OUTPUT.. Tue Feb 06 2024 00:28:59 GMT-0800 (Pacific Standard Time)
</code></pre>
<p>In the code above, the Date constructor was called without passing any parameter. This means it returns a date object with the current date and time as values.</p>
<h4 id="heading-using-date-datestring">Using <code>Date</code> (<code>dateString</code>)</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> current = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">"February 6, 2025 10:25:00"</span>);

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


<span class="hljs-comment">// OUTPUT .. Thu Feb 06 2025 10:25:00 GMT-0800 (Pacific Standard Time)</span>
</code></pre>
<p>In the above code, the <code>Date</code> constructor was called by passing a specific date, and time as a parameter to create a custom date object. The key point to note here is that the parameters are in string format.</p>
<h4 id="heading-using-year-month-day-hours-minutes-seconds-amp-milliseconds">Using year, month, day, hours, minutes, seconds, &amp; milliseconds</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> current = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">2024</span>, <span class="hljs-number">1</span>, <span class="hljs-number">6</span>, <span class="hljs-number">12</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>);

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

<span class="hljs-comment">// OUTPUT... Tue Feb 06 2024 12:00:00 GMT-0800 (Pacific Standard Time)</span>
</code></pre>
<p>In the above code, a <code>Date</code> constructor with <strong>year, month, day, hours, minutes, seconds, and milliseconds</strong> was called to create a custom object with a specific time and date.</p>
<h4 id="heading-dates-with-timestamps">Dates with timestamps</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> timestamp = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-number">14852959902</span>)
<span class="hljs-built_in">console</span>.log(timestamp)

<span class="hljs-comment">// OUTPUT ... Sun Jun 21 1970 14:49:19 GMT-0700 (Pacific Daylight Time)</span>
</code></pre>
<p>Although creating a date with timestamp is the least popular, it's still one of the methods of creating a date.</p>
<p>A timestamp is the total milliseconds that have elapsed since January 1, 1970. </p>
<h2 id="heading-basics-of-date-comparison">Basics of Date Comparison</h2>
<p>In JavaScript, you can compare dates using different methods, like the comparison operators and the built-in <code>Date</code> methods.</p>
<h3 id="heading-how-to-compare-dates-with-comparison-operators">How to Compare Dates with Comparison Operators</h3>
<p>In JavaScript, you can use comparison operators like <code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>, <code>&gt;=</code>, and <code>!=</code> for comparing dates. JavaScript internally converts the dates (milliseconds since January 1, 1970) to their respective corresponding timestamps.</p>
<p>The below code shows a date comparison using the the comparison operators:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//  Create a two  date objects</span>

<span class="hljs-keyword">const</span> firstDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2024-01-07'</span>)
<span class="hljs-keyword">const</span> secondDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2023-11-09'</span>)

<span class="hljs-comment">//  Look for comparison among the trio using the comparison operators</span>

<span class="hljs-built_in">console</span>.log(firstDate &lt; secondDate) <span class="hljs-comment">// false (firstDate is later than secondDate)</span>
<span class="hljs-built_in">console</span>.log(firstDate &gt; secondDate) <span class="hljs-comment">// true (firstDate is earlier than secondDate)</span>
<span class="hljs-built_in">console</span>.log(firstDate &gt;= secondDate) <span class="hljs-comment">// false (firstDate is earlier than or equal to secondDate)</span>
<span class="hljs-built_in">console</span>.log(firstDate &lt;= secondDate) <span class="hljs-comment">// true (firstDate is later than or equal to secondDate)</span>
<span class="hljs-built_in">console</span>.log(firstDate == secondDate) <span class="hljs-comment">// false (firstDate is not  equal to secondDate)</span>
<span class="hljs-built_in">console</span>.log(firstDate != secondDate) <span class="hljs-comment">// true (firstDate is not to equal secondDate)</span>
</code></pre>
<p>The code output shows that the<code>firstDate</code> is later than the <code>secondDate</code> in the first comparison. In the context of dates, between two dates, <code>later</code> is  the date that occurs after another in time. </p>
<p>The second comparison shows that <code>firstDate</code> is earlier than the <code>secondDate</code>.  In the context of dates, between two dates, <code>earlier</code> refers to the date that comes first in time.</p>
<p>The output for the third comparison shows that <code>firstDate</code> is earlier than or equal to the <code>secondDate</code>.</p>
<p>The code output for the third comparison shows that <code>firstDate</code> is later than or equal to the <code>secondDate</code>.</p>
<p>The fifth comparison shows that <code>firstDate</code> is not equal to the <code>secondDate</code>.</p>
<p>And the last comparison displayed that <code>firstDate</code> is not equal to the <code>secondDate</code>.</p>
<p>It's important to note that comparison operators in JavaScript are based on the Coordinated Universal Time (UTC).</p>
<p>If you want to compare dates based on their actual date and time values (including year, month, day, hours, minutes, seconds, and milliseconds), you may need to extract these components and compare them individually.</p>
<p>The code below shows how to compare two dates based on their respective components.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> firstDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2024-02-05'</span>);
<span class="hljs-keyword">const</span> secondDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2024-02-05'</span>);

<span class="hljs-comment">// Extract year, month, and day components of both dates</span>

<span class="hljs-keyword">const</span> firstYear = firstDate.getFullYear();
<span class="hljs-keyword">const</span> firstMonth = firstDate.getMonth();
<span class="hljs-keyword">const</span> firstDay = firstDate.getDate();
<span class="hljs-keyword">const</span> secondYear = secondDate.getFullYear();
<span class="hljs-keyword">const</span> secondMonth = secondDate.getMonth();
<span class="hljs-keyword">const</span> secondDay = secondDate.getDate();

<span class="hljs-comment">// Compare both date components</span>

<span class="hljs-keyword">let</span> result;
<span class="hljs-keyword">switch</span> (<span class="hljs-literal">true</span>) {
  <span class="hljs-keyword">case</span> firstYear === secondYear &amp;&amp; firstMonth === secondMonth &amp;&amp; firstDay === secondDay:
    result = <span class="hljs-string">"The dates are equal."</span>;
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">case</span> firstYear &lt; secondYear || (firstYear === secondYear &amp;&amp; firstMonth &lt; secondMonth) || (firstYear === secondYear &amp;&amp; firstMonth === secondMonth &amp;&amp; firstDay &lt; secondDay):
    result = <span class="hljs-string">"firstDate is earlier than secondDate."</span>;
    <span class="hljs-keyword">break</span>;
  <span class="hljs-keyword">default</span>:
    result = <span class="hljs-string">"firstdate is later than secondDate."</span>;
}
<span class="hljs-built_in">console</span>.log(result);
</code></pre>
<p>The breakdown of the above code is as follows:</p>
<ul>
<li>Creating Date Objects: Two objects <code>firstDate</code> and <code>secondDate</code> initialized with the same date were created.</li>
<li>With <code>getFullYear()</code>, <code>getMonth()</code>, and <code>getDate()</code> methods, the code extracts the year, month, and day components from each date.</li>
<li>Comparison between the dates components using the switch case statement. The code was evaluated based on the <code>true</code> <code>boolean</code> value, with each case checking various conditions to ascertain relationship between the two dates.</li>
<li>The result gets logged into the console.</li>
</ul>
<p>In summary, to determine if two date objects are equal based on their values like year, month, and day, the code compares them using a switch case statement to handle the multiple comparison scenarios. </p>
<h3 id="heading-how-to-compare-dates-with-the-gettime-method">How to Compare Dates with the <code>getTime()</code> Method</h3>
<p>The <code>getTime()</code> method is useful for comparing dates to the millisecond. It's important to remember that the <code>getTime()</code> performs a numerical comparison between dates, and returns the time-value since January 1, 1970.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Create two Date objects</span>
<span class="hljs-keyword">const</span> firstDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2025-01-01'</span>);
<span class="hljs-keyword">const</span> secondDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2024-01-02'</span>);

<span class="hljs-comment">// Get the time in milliseconds for each date</span>
<span class="hljs-keyword">const</span> firstTime = firstDate.getTime();
<span class="hljs-keyword">const</span> secondTime = secondDate.getTime();

<span class="hljs-comment">// Compare the time values</span>
<span class="hljs-keyword">if</span> (firstTime &lt; secondTime) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'firstDate is earlier than secondDate'</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (firstTime &gt; secondTime) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'firstDate is later than secondDate'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'firstDate are  secondDate'</span>);
}

<span class="hljs-comment">//OUTPUT....firstDate is later than secondDate</span>
</code></pre>
<p>In the code above:</p>
<ul>
<li>The two date objects are the <code>firstDate</code> and the <code>secondDate</code>, with both representing different dates.</li>
<li>The <code>getTime()</code> method was used to get the time of both elements in milliseconds.</li>
<li>The standard comparison operators (<code>&lt;</code>, <code>&gt;</code>, <code>===</code>)  were used to determine their relationship.</li>
<li>The output of the above code was <code>firstDate</code> is later than <code>secondDate</code>, because the <code>secondDate</code> comes before the <code>firstDate</code>.</li>
</ul>
<h3 id="heading-how-to-use-the-valueof-method">How to Use the <code>valueOf()</code> Method</h3>
<p>In JavaScript, the <code>valueOf()</code> method is automatically called behind the scenes to return the primitive value of the specified object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> word = <span class="hljs-keyword">new</span> <span class="hljs-built_in">String</span>(<span class="hljs-string">"Hello!"</span>);
<span class="hljs-built_in">console</span>.log(word); <span class="hljs-comment">// Output: [String: 'Hello!']</span>
<span class="hljs-built_in">console</span>.log(str.valueOf()); <span class="hljs-comment">// Output: 'Hello!'</span>

<span class="hljs-keyword">var</span> number = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Number</span>(<span class="hljs-number">10</span>);
<span class="hljs-built_in">console</span>.log(number); <span class="hljs-comment">// Output: [Number: 10]</span>
<span class="hljs-built_in">console</span>.log(num.valueOf()); <span class="hljs-comment">// Output: 10</span>
</code></pre>
<p>In the above example, the <code>valueOf()</code> method of both the string and number object returns the string and number values it represents.</p>
<p>The <code>valueOf()</code> method, however, returns a timestamp (milliseconds since the Unix Epoch), which makes dates comparison easier.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
<span class="hljs-keyword">const</span> date1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();

<span class="hljs-keyword">if</span> (date.valueOf() &lt; date1.valueOf()) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'date is earlier than date1'</span>)
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (date.valueOf() &gt; date1.valueOf()) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'date is later  than date1'</span>)
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'date and date1 are same'</span>)
}

<span class="hljs-comment">// OUTPUT ... date and date1 are same</span>
</code></pre>
<p>The output shows that both dates object are same.</p>
<h3 id="heading-how-to-use-the-toisostring-method">How to Use the <code>toISOString()</code> Method</h3>
<p>In JavaScript, the <code>toISOString()</code> method is for converting a <code>Date</code> object to string representation into a simplified extended ISO 8601 format which is always 24 to 27 characters long. The characters are <code>YYYY-MM-DDTHH:mm:ss.sssZ</code> or <code>±YYYYYY-MM-DDTHH:mm:ss.sssZ</code>, respectively.</p>
<p>The method provides a standardized way of representing dates as strings when you use it to manipulate or compare dates. Converting two dates into ISO strings through <code>toISOString()</code> is beneficial, because it makes the comparison seamless by ensuring both dates are in the same format.</p>
<p>You can use the standard string comparison operators like <code>===</code>, <code>&lt;</code>, <code>&gt;</code> to compare the ISO strings.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Create two Date objects</span>
<span class="hljs-keyword">const</span> firstDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2024-02-06T12:00:00'</span>);
<span class="hljs-keyword">const</span> secondDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2024-02-07T12:00:00'</span>);

<span class="hljs-comment">// Convert the dates to ISO strings</span>
<span class="hljs-keyword">const</span> firstISODate = firstDate.toISOString();
<span class="hljs-keyword">const</span> secondISODate = secondDate.toISOString();


<span class="hljs-comment">// Compare the two ISO strings</span>
<span class="hljs-keyword">if</span> (firstISODate === secondISODate) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"The dates are equal."</span>);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (firstISODate &lt; secondISODate) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"firstDate is before secondDate."</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"firstDate is after secondDate."</span>);
}
<span class="hljs-comment">// OUTPUT ....firstDate is before secondDate.</span>
</code></pre>
<p>The code above shows that the dates were converted into ISO strings, and directly compares both strings to determine their relative status. It ensures ease of comparison and consistency.</p>
<h2 id="heading-challenges-of-comparing-dates-in-javascript">Challenges of Comparing Dates in JavaScript</h2>
<p>Being aware of possible issues and their solutions can help you ensure accuracy and consistency when comparing dates in JavaScript.</p>
<p>Some of the known issues are listed below:</p>
<h3 id="heading-comparison-operators">Comparison Operators</h3>
<p><code>getTime()</code> numerical values should be the only comparing metrics when using comparison operators. The method does not inherently handle time zone conversions, meaning you must ensure time are normalized to a common time zone before using <code>getTime()</code>.</p>
<p>In JavaScript, the <code>date</code> object allows you to create invalid dates (like February 30th). You should use <code>getTime()</code> to prevent unexpected behavior after validating the dates.</p>
<p><strong>How to address the issue:</strong></p>
<ul>
<li><strong>Validate Dates</strong>: Validating dates must be the first step to ensure the date are valid before performing any comparison.</li>
<li><strong>Normalize Timezones</strong>: Before using the <code>getTime()</code> method, you should ensure that dates are normalized to a common timezone.</li>
<li><strong>Precision Needs</strong>: Confirm if  <code>getUTCFullYear()</code>, <code>getUTCMonth()</code>, and <code>getUTCDate()</code> precision will be necessary for your comparison requirement. If not, use the <code>getTime()</code> method.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> firstDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2024-02-01'</span>);
<span class="hljs-keyword">const</span> secondDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2024-02-03'</span>);

<span class="hljs-keyword">if</span> (firstDate.getTime() &lt; secondDate.getTime()) {
  <span class="hljs-comment">// firstDate is earlier than secondDATE</span>
}
</code></pre>
<h3 id="heading-timezone-difference">Timezone Difference</h3>
<p>Ensure you are comparing dates in the same timezone or with UTC and not the user's local timezone. Using local time zones can lead to discrepancies when comparing dates across different time zones or when working with dates from different sources.</p>
<p>In certain timezones, Daylight Saving time mode may be the adopted time format. In this case, the local time may be adjusted forward or backward. This adjustment can affect the duration between two dates and cause unexpected results.</p>
<p><strong>How to address the issue:</strong></p>
<ul>
<li>Normalize the Timezone: convert all dates to a standard timezone, that is UTC (Coordinated Universal Time), before comparison. This ensures consistency across the board. </li>
<li>Communication: Ensure the timezone information is communicated and standardized when working with dates obtained from multiple sources. This helps to ensure consistent interpretation of dates.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> firstDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2024-02-02T12:00:00Z'</span>); <span class="hljs-comment">// UTC Date</span>
<span class="hljs-keyword">const</span> secondDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(); <span class="hljs-comment">// Current local date</span>

<span class="hljs-comment">// Compare dates in UTC to avoid timezone issues</span>
<span class="hljs-keyword">if</span> (firstDate.toISOString() === secondDate.toISOString()) {
  <span class="hljs-comment">// Dates are equal</span>
}
</code></pre>
<h3 id="heading-precision">Precision</h3>
<p>In JavaScript, time is represented in milliseconds since the Unix epoch (January 1, 1970). This is crucial when comparing a date that has an associated time, as you may encounter issues with precision.</p>
<p><strong>How to address the issue:</strong></p>
<ul>
<li><strong>Quality Control</strong>: Regular inspections, testing, and validation of measurement systems and procedures can help correct errors in measurement process.</li>
<li><strong>Calibration</strong>: Regular calibration of instruments and equipment helps maintain accuracy and precision in measurements. Calibration involves comparing measurements taken by a device to known standards to ensure accuracy and reliability.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> firstDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2023-02-06'</span>);
<span class="hljs-keyword">const</span> secondDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'2022-02-06'</span>);

<span class="hljs-comment">// This might not always be true due to time information</span>
<span class="hljs-keyword">if</span> (firstDate === secondDate) {
  <span class="hljs-comment">// Dates are not necessarily equal</span>
}
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this tutorial, you learned about date comparison and why it's important to understand how to do it in JavaScript. We talked about date objects and how to create one, as well as the basics of date comparison, and method of comparing dates.</p>
<p>We also looked at some of the issues likely to be encountered while comparing dates in JavaScript.</p>
<p>Happy Reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Data Types in Python – Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ In Python, a data type communicates with the interpreter about how the programmer intends to use the data and information stored. The classification of data specifies the type of value a variable can hold. In Python programming, you don't need to exp... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-data-types-in-python/</link>
                <guid isPermaLink="false">66d03963a30d09f91d49b77d</guid>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kamaldeen Lawal ]]>
                </dc:creator>
                <pubDate>Fri, 09 Feb 2024 15:15:55 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/Python-Data-Types.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In Python, a data type communicates with the interpreter about how the programmer intends to use the data and information stored. The classification of data specifies the type of value a variable can hold.</p>
<p>In Python programming, you don't need to explicitly declare the data type of your variable. Instead, Python, as a dynamically typed language, determines the data type of your variable according to the assigned value.</p>
<p>A solid understanding of data types in Python is crucial as it allows programmers to write concise code. Python has several built-in data types like the sequence, numeric, mapping, set, none, and Boolean types of data.</p>
<p>This article will discuss the following topics:</p>
<ul>
<li><a class="post-section-overview" href="#heading-numeric-data-types-in-python">Numeric Data Types in Python</a></li>
<li><a class="post-section-overview" href="#heading-sequence-data-types-in-python">Sequence Data Types in Python</a></li>
<li><a class="post-section-overview" href="#heading-mapping-data-type-in-python">Mapping Data Type in Python</a></li>
<li><a class="post-section-overview" href="#heading-set-data-type-in-python">Set Data Type in Python</a></li>
<li><a class="post-section-overview" href="#heading-none-data-type-in-python">None Data Type in Python</a></li>
<li><a class="post-section-overview" href="#heading-boolean-data-type-in-python">Boolean Data Type in Python</a></li>
<li><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></li>
</ul>
<h2 id="heading-numeric-data-types-in-python">Numeric Data Types in Python</h2>
<p>Have you ever thought about working with numerical values with Python? If yes, numeric data types are used to represent any numerical values. </p>
<p>There are three main numeric data types in Python: integers, floating-point numbers, and the complex numbers.</p>
<h3 id="heading-integer-data-type-in-python">Integer Data Type in Python</h3>
<p>In Python, integers are known as <code>int</code>. They are a built-in data type for whole numbers. <code>int</code> can represent any size of integers without overflow errors because they can either be positive, zero, or negative.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Python Integer</span>
a = <span class="hljs-number">7</span>
y = <span class="hljs-number">-1</span>
c = <span class="hljs-number">0</span>

print(a)  <span class="hljs-comment"># Output: 7</span>
print(y)  <span class="hljs-comment"># Output: -1</span>
print(c)  <span class="hljs-comment"># Output: 0</span>
</code></pre>
<p>Numerous arithmetic calculations like addition, subtraction, multiplication, modulus, integer division, exponentiation, and division can be performed with integers.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Addition Operation +</span>

addition = <span class="hljs-number">8</span> + <span class="hljs-number">3</span>
print(<span class="hljs-string">"Addition:"</span>, addition)  <span class="hljs-comment"># Output: 11</span>

<span class="hljs-comment"># Subtraction operation -</span>
subtraction = <span class="hljs-number">9</span> - <span class="hljs-number">4</span>
print(<span class="hljs-string">"Subtraction:"</span>, subtraction)  <span class="hljs-comment"># Output: 5</span>

<span class="hljs-comment"># Multiplication operation *</span>
multiplication = <span class="hljs-number">10</span> * <span class="hljs-number">2</span>
print(<span class="hljs-string">"Multiplication:"</span>, multiplication)  <span class="hljs-comment"># Output: 20</span>

<span class="hljs-comment"># Division operation /</span>
division = <span class="hljs-number">10</span> / <span class="hljs-number">6</span>
print(<span class="hljs-string">"Division:"</span>, division)  <span class="hljs-comment"># Output: 1.6666666666666667</span>

<span class="hljs-comment"># Integer Division operation //</span>
integer_division = <span class="hljs-number">10</span> // <span class="hljs-number">2</span>
print(<span class="hljs-string">"Integer Division:"</span>, integer_division)  <span class="hljs-comment"># Output: 5</span>

<span class="hljs-comment"># Modulus operation %</span>
modulus = <span class="hljs-number">10</span> % <span class="hljs-number">5</span>
print(<span class="hljs-string">"Modulus:"</span>, modulus)  <span class="hljs-comment"># Output: 0</span>

<span class="hljs-comment"># Exponentiation operation **</span>
exponentiation = <span class="hljs-number">2</span> ** <span class="hljs-number">6</span>
print(<span class="hljs-string">"Exponentiation:"</span>, exponentiation)  <span class="hljs-comment"># Output: 64</span>
</code></pre>
<h3 id="heading-floating-point-data-type-in-python">Floating-point Data Type in Python</h3>
<p>In Python, <code>float</code> can represent both whole numbers and fractions. They are used for approximating real numbers. Hence, they are not precise when dealing with a very small or a very large numbers.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Python Float</span>
b = <span class="hljs-number">2.47</span>
y = <span class="hljs-number">-0.1</span>
k = <span class="hljs-number">5.0</span>

print(b)  <span class="hljs-comment"># Output: 2.47</span>
print(y)  <span class="hljs-comment"># Output: -0.1</span>
print(k)  <span class="hljs-comment"># Output: 5.0</span>
</code></pre>
<p>Floating-point arithmetic calculations like addition, subtraction, multiplication, modulus, integer division, exponentiation, and division are performed using floating-point numbers. The float is any number with a decimal point.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Addition Operation</span>

a = <span class="hljs-number">3.5</span>
b = <span class="hljs-number">2.1</span>
print(a + b) <span class="hljs-comment"># Output will be 5.3</span>

 <span class="hljs-comment"># Subtraction Operation</span>
c = <span class="hljs-number">5.5</span>
d = <span class="hljs-number">2.2</span>
print(c - d) <span class="hljs-comment"># Output will be 3.3</span>

<span class="hljs-comment"># Multiplication operation</span>

e = <span class="hljs-number">4.0</span>
f = <span class="hljs-number">2.5</span>
print(e * f)  <span class="hljs-comment"># Output will be 10.0</span>

<span class="hljs-comment"># Division Operation</span>
g= <span class="hljs-number">10.0</span>
h = <span class="hljs-number">7.0</span>
print(g / h) <span class="hljs-comment"># Output will be 1.4285714285714286</span>

<span class="hljs-comment"># Exponential Operation </span>
i = <span class="hljs-number">2.0</span>
j = <span class="hljs-number">3.0</span>
print(i * j)<span class="hljs-comment"># Output will be 6.0</span>

<span class="hljs-comment"># Modulus operation</span>
k = <span class="hljs-number">10.5</span>
l = <span class="hljs-number">4.0</span>
print(k % l) <span class="hljs-comment"># Output will be 2.5</span>

<span class="hljs-comment"># integer division Operation</span>
m = <span class="hljs-number">10.5</span>
n = <span class="hljs-number">3.0</span>
print(k // l) <span class="hljs-comment"># Output will be 2.0</span>
</code></pre>
<p><strong>Note:</strong> In Python 3, by default, dividing two integers returns a floating-point result.</p>
<h3 id="heading-complex-data-type-in-python">Complex Data Type in Python</h3>
<p><code>complex</code> numbers are popularly used in engineering, physics, and mathematics to model the real and imaginary components. The numbers take the form of <code>a + bj</code>, where <code>a</code> and <code>b</code> are real numbers, and <code>j</code> represents the imaginary unit, defined as the square root of -1.</p>
<pre><code class="lang-python">z1 = <span class="hljs-number">8</span> + <span class="hljs-number">2j</span>  <span class="hljs-comment"># Creates a complex number 8 + 2j</span>
z2 = <span class="hljs-number">-9</span> - <span class="hljs-number">6j</span> <span class="hljs-comment"># Creates a complex number -9 - 6j</span>
</code></pre>
<p>Python can perform various arithmetic calculations like addition, subtraction, multiplication, and division with complex number.</p>
<pre><code class="lang-python">z2 = complex(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>)
z4 = complex(<span class="hljs-number">-1</span>, <span class="hljs-number">6</span>)

<span class="hljs-comment"># Addition Operation</span>
sum_z = z2 + z4  <span class="hljs-comment"># Result: 3 - 1 + (2 + 6)j = 2 + 8j</span>

<span class="hljs-comment"># Subtraction</span>
diff_z = z2 - z4  <span class="hljs-comment"># Result: 3 - (-1) + (2 - 6)j = 4 - 4j</span>

<span class="hljs-comment"># Multiplication</span>
prod_z = z2 * z4 

<span class="hljs-comment"># Result: (3 * -1 - 2 * 6) + (3 * 6 + 2 * -1)j = (-15+16j)</span>

<span class="hljs-comment"># Division</span>
div_z = z2 / z4 
<span class="hljs-comment"># Result:(0.24324324324324323-0.5405405405405406j)</span>
</code></pre>
<h2 id="heading-sequence-data-types-in-python">Sequence Data Types in Python</h2>
<p>In Python, there are several sequence data types used to represent data collections in a specific order. They are as follows:</p>
<h3 id="heading-list-data-type-in-python">List Data Type in Python</h3>
<p>Lists are defined using square brackets <code>[]</code> with comma-separated elements. They are a mutable, built-in data structure for storing item collections. The mutability feature of <code>[]</code> means it's modifiable after creation.</p>
<p>Lists are a widely used data structures in Python because they support various operations and offer flexibility.</p>
<p>The element inside a list can be of any data type, list included.</p>
<pre><code class="lang-python"><span class="hljs-comment"># List creation</span>

the_list = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]


<span class="hljs-comment"># creating a mixed data list</span>
multiple_data_list = [<span class="hljs-number">1</span>, <span class="hljs-string">'hi'</span>, <span class="hljs-number">2.57</span>, <span class="hljs-literal">False</span>]



print(the_list[<span class="hljs-number">0</span>])   <span class="hljs-comment"># Output: 1</span>
print(multiple_data_list[<span class="hljs-number">2</span>])  <span class="hljs-comment"># Output:2.57</span>


<span class="hljs-comment"># Mutable feature of list</span>

the_list[<span class="hljs-number">0</span>] = <span class="hljs-number">10</span>          <span class="hljs-comment"># Modify the first element</span>
the_list.append(<span class="hljs-number">9</span>)        <span class="hljs-comment"># Append a new element</span>
the_list.extend([<span class="hljs-number">5</span>, <span class="hljs-number">4</span>])   <span class="hljs-comment"># Extend the list with another list</span>
the_list.remove(<span class="hljs-number">2</span>)        <span class="hljs-comment"># Remove an element by value</span>
<span class="hljs-keyword">del</span> the_list[<span class="hljs-number">0</span>]           <span class="hljs-comment"># Remove an element by index</span>
</code></pre>
<h3 id="heading-tuple-data-type-in-python">Tuple Data Type in Python</h3>
<p>In Python, a tuple is an immutable built-in data type for storing an ordered collection of elements. </p>
<p>Tuples are created using parentheses <code>()</code>. Just like lists, Tuples have comma-separated elements.</p>
<p>A tuple requires a comma after the element to differentiate it from a parenthesized expression, even if it contains single element. The immutability feature of tuples implies that you cannot change them after creation.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Empty tuple</span>
zilch_tuple = ()   

 <span class="hljs-comment"># Tuple with a single element            </span>
single_tuple = (<span class="hljs-number">1</span>,)  

 <span class="hljs-comment"># Tuple with multiple elements </span>
multiple_tuple = (<span class="hljs-number">1</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">3</span>, <span class="hljs-number">5</span>) 

<span class="hljs-comment"># Tuple immutability</span>

single_slice[<span class="hljs-number">0</span>] = <span class="hljs-number">5</span>

print(tuple_slice) <span class="hljs-comment"># TypeError: 'tuple' object does not support item assignment</span>


<span class="hljs-comment"># Different elements tuples </span>
mixed_tuple = (<span class="hljs-number">1</span>, <span class="hljs-string">'hello'</span>, <span class="hljs-number">3.14</span>, <span class="hljs-literal">True</span>) 

 <span class="hljs-comment"># Nested tuple </span>

nested_tuple = (<span class="hljs-string">'Orange'</span>, (<span class="hljs-string">'banana'</span>, <span class="hljs-string">'Pineapple'</span>), [<span class="hljs-string">"he"</span>, <span class="hljs-string">'she'</span>, <span class="hljs-string">'them'</span>]) 


 <span class="hljs-comment"># Concatenate tuples</span>

add_tuple = multiple_tuple + (<span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>)  <span class="hljs-comment"># Output: (1, 8, 9, 4, 3, 5, 7, 8)</span>

<span class="hljs-comment"># Create a slice of the tuple</span>
tuple_slice = add_tuple[<span class="hljs-number">1</span>:<span class="hljs-number">3</span>]     <span class="hljs-comment"># Output: (8, 9)</span>
</code></pre>
<h3 id="heading-string-data-type-in-python">String Data Type in Python</h3>
<p>A string enclosed in either single <code>(')</code> or a double quote <code>(")</code> is an immutable sequence of characters used to represent textual data.</p>
<p>Python allows you to perform operations like, indexing, slicing, and concatenation on strings.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Creaating a String with both single and double quote</span>

single_string = <span class="hljs-string">'Hello!'</span>
double_string = <span class="hljs-string">"Python Programming!"</span>

<span class="hljs-comment"># Outputting the result </span>

print(single_string[<span class="hljs-number">0</span>])    <span class="hljs-comment"># Output: 'H'</span>
print(double_string[<span class="hljs-number">-1</span>])   <span class="hljs-comment"># Output: '!'</span>


print(single_string[<span class="hljs-number">0</span>:<span class="hljs-number">5</span>])    <span class="hljs-comment"># Output: 'Hello'</span>
print(double_string[::<span class="hljs-number">2</span>])    <span class="hljs-comment"># Output: 'Pto rgamn!'</span>

<span class="hljs-comment"># Concatenate the two strings</span>

concatenate_string = single_string + <span class="hljs-string">' '</span> + double_string
print(concatenate_string)   <span class="hljs-comment"># Output: 'Hello! Python Programming'</span>


<span class="hljs-comment"># Some popular string methods like the upper,lower,find,replace, split and strip.</span>

print(single_string.upper())              <span class="hljs-comment"># Output: 'HELLO!'</span>
print(double_string.lower())              <span class="hljs-comment"># Output: 'python programming!'</span>
print(single_string.find(<span class="hljs-string">'World'</span>))        <span class="hljs-comment"># Output: -1</span>
print(double_string.replace(<span class="hljs-string">'Python'</span>, <span class="hljs-string">'Java'</span>))  <span class="hljs-comment"># Output: 'Java Programming'</span>
print(single_string.split(<span class="hljs-string">','</span>))           <span class="hljs-comment"># Output: ['Hello!']</span>
print(double_string.strip())              <span class="hljs-comment"># Output: 'Python Programming!'</span>
</code></pre>
<h3 id="heading-range-data-type-in-python">Range Data Type in Python</h3>
<p>The <code>range</code> function is used to iterate over elements in a list. By executing a task repeatedly, the <code>range</code> generates indices for the data structure.</p>
<p>The syntax for a <code>range</code> function is as follows:</p>
<pre><code class="lang-python">range(start, stop, step)
</code></pre>
<p>The <code>start</code> represents a starting value if, when omitted, the range starts from 0, while <code>stop</code> is the number that indicates that the range should stop generating numbers.</p>
<p>The <code>step</code> being the last value, specifies the increment or step between each different number in the sequence. The default value for this parameter is 1.</p>
<p>The <code>range</code> function returns an immutable series of numbers.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Generating a number from 0 to 10</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">11</span>):
    print(i)  <span class="hljs-comment"># OUTPUT..... 0,1,2,3,4,5,6,7,8,9,10</span>


<span class="hljs-comment"># Generate a number from 1 to 19.</span>
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">1</span>, <span class="hljs-number">20</span>):
    print(i) <span class="hljs-comment"># OUTPUT.....1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19</span>


<span class="hljs-comment"># Generating numbers from 0 to 10 with a step of 2:</span>

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">0</span>, <span class="hljs-number">21</span>, <span class="hljs-number">2</span>):
    print(i)  <span class="hljs-comment"># OUTPUT.... 0,2,4,6,8,10,12,14,16,18,20</span>


<span class="hljs-comment"># Generate a list of numbers using the list function in conjuction with range:</span>

new_list = list(range(<span class="hljs-number">15</span>))
print(new_list)  <span class="hljs-comment"># Output: [0, 1, 2, 3, 4,5,6,7,8,9,10,11,12,13,14]</span>
</code></pre>
<h2 id="heading-mapping-data-type-in-python">Mapping Data Type in Python</h2>
<p>In Python, the dictionary <code>dict</code> is the primary data type for storing a collection of key-value pairs. </p>
<p>The <code>dict</code> is widely used in Python for different functions, such as mapping between related information, representing a set of data records, and storing configurations. </p>
<p>We can create a <code>dict</code> in Python with either the curly braces <code>{}</code> or the <code>dict()</code> constructor.</p>
<p>Some of the characteristics of a dictionary are as follows:</p>
<ul>
<li><strong>Key-Value Pairs</strong>: A <code>dict</code> consists of a key associated with a specific value in a key-value pair. The function of the key is to look up the corresponding value in the dictionary.</li>
<li><strong>Uniqueness</strong>: Duplicate keys are not allowed in <code>dict</code>. Assigning a new value to an existing key will only replace the old value associated with that key.</li>
<li><strong>Key Immutability</strong>: The immutability nature of the keys ensures that keys remain "hashable" and consistent. Hence, keys in dictionary must be immutable. Some examples of immutable data types include integers, strings, and tuples.</li>
<li><strong>Flexible Values</strong>: Any data type including but not limited to lists, tuples, strings, numbers and even dictionaries can be associated with keys in a dictionary.</li>
</ul>
<pre><code class="lang-python">person = {
    <span class="hljs-string">"name"</span>: <span class="hljs-string">"Kamaldeen"</span>,
    <span class="hljs-string">"age"</span>: <span class="hljs-number">32</span>,
    <span class="hljs-string">"city"</span>: <span class="hljs-string">"Nigeria"</span>
}
</code></pre>
<p>In the code above, the keys are  the <code>"name"</code>, <code>"age"</code>, and <code>"city"</code>  while their corresponding values are  <code>"kamaldeen"</code>, <code>32</code>, and <code>"Nigeria"</code>.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Accessing values by key:</span>

print(person[<span class="hljs-string">"name"</span>])  <span class="hljs-comment"># Output: Kamaldeen</span>

<span class="hljs-comment"># Modifying values</span>

person[<span class="hljs-string">"age"</span>] = <span class="hljs-number">35</span>  <span class="hljs-comment"># Output: {'name': 'Kamaldeen', 'age': 35, 'city':</span>
<span class="hljs-string">'Nigeria'</span>}

<span class="hljs-comment"># Adding a new key-value paie</span>

person[<span class="hljs-string">"job"</span>] = <span class="hljs-string">"Engineer"</span>  <span class="hljs-comment"># Output: {'name': 'Kamaldeen', 'age': 32, 'city': 'Nigeria', 'job': 'Engineer'}</span>

<span class="hljs-comment"># Check if name is in person dictionary</span>

<span class="hljs-keyword">if</span> <span class="hljs-string">"name"</span> <span class="hljs-keyword">in</span> person:
    print(<span class="hljs-string">"Name is present in the dictionary."</span>) <span class="hljs-comment"># Output:Name is present in the dictionary</span>
</code></pre>
<h2 id="heading-set-data-type-in-python">Set Data Type in Python</h2>
<p>In Python, a <code>set</code> is a built-in data type that represents a collection of unique elements with no particular order. </p>
<p>The elements in the <code>set</code> are immutable, but the <code>set</code> itself  is mutable. Sets can be defined using curly braces <code>{}</code> with comma-separated elements or by the <code>set()</code> constructor. They gets used for mathematical operations like unions, intersections, and differences.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Creating curly braces set</span>
curly_set = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>, <span class="hljs-number">4</span>, <span class="hljs-number">9</span>}

<span class="hljs-comment"># Creating  set() function set</span>
func_set = set([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>, <span class="hljs-number">9</span>, <span class="hljs-number">5</span>])
</code></pre>
<p>Some of the characteristics are:</p>
<ul>
<li><strong>No defined order</strong>: In a <code>set</code>, there's no defined order because the elements are unordered.</li>
<li><strong>Uniqueness</strong>: Sets are unique in nature, because they do not allow duplicate elements.</li>
<li><strong>Mutability</strong>: Sets allow you to update either by adding or removing elements after creation.</li>
<li><strong>Elements Immutability</strong>: Mutable elements like <code>lists</code> cannot be an element of a set, because elements within a set must be immutable. Therefore, immutable data types like floats, integers , tuples and string can be used instead.</li>
</ul>
<h3 id="heading-set-operation">Set Operation</h3>
<p>Python supports mathematical operations like union, intersection, difference, and more for sets.</p>
<h4 id="heading-union-operation-using-sets-in-python">Union Operation Using Sets in Python</h4>
<p>The union mathematical operation of two sets joins all unique elements from both sets.</p>
<pre><code class="lang-python">first_set = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>}
second_set = {<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}

union_set = first_set | second_set  <span class="hljs-comment"># Using the '|' operator</span>
<span class="hljs-comment"># Output: {1, 2, 3, 4, 5}</span>

<span class="hljs-comment"># or</span>

union_method = first_set.union(second_set)  <span class="hljs-comment"># Using the union() method</span>

<span class="hljs-comment"># Output: {1, 2, 3, 4, 5}</span>
</code></pre>
<p>The union can be created with either the <code>|</code> or the <code>union()</code> method.</p>
<h4 id="heading-intersection-operation-using-sets-in-python">Intersection Operation using Sets in Python</h4>
<p>In Python, the intersection is a mathematical operation of two sets that prints the common elements only.</p>
<pre><code class="lang-python">first_set = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>}
second_set = {<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}

union_set = first_set &amp; second_set  <span class="hljs-comment"># Using the '&amp;' operator</span>
<span class="hljs-comment"># Output: {3}</span>

<span class="hljs-comment"># or</span>

union_method = first_set.intersection(second_set)  <span class="hljs-comment"># Using the union() method</span>
<span class="hljs-comment"># Output: {3}</span>

print(union_set)
print(union_method)
</code></pre>
<p>The intersection can be created with either the <code>&amp;</code> or the <code>intersection()</code> method.</p>
<h4 id="heading-difference-operation-using-sets-in-python">Difference Operation using Sets in Python</h4>
<p>In Python, the difference mathematical operation between two sets occurs when an element is present in the first, but not in the second.</p>
<pre><code class="lang-python">first_set = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>}
second_set = {<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}

union_set = first_set - second_set  <span class="hljs-comment"># Using the '-' operator</span>

<span class="hljs-comment"># or</span>

union_method = first_set.difference(second_set)  <span class="hljs-comment"># Using the difference() method</span>


print(union_set)
print(union_method)
</code></pre>
<p>The difference can be created with either by the <code>-</code> or the <code>difference()</code>method.</p>
<h4 id="heading-add-operation-using-sets-in-python">Add Operation using Sets in Python</h4>
<p>The <code>add()</code> method of sets is used to add a single element to the set collection, while the <code>update()</code> method is for adding multiple element.</p>
<pre><code class="lang-python">first_set = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>}
second_set = {<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}

<span class="hljs-comment"># Add with add method</span>
first_set.add(<span class="hljs-number">4</span>)

<span class="hljs-comment"># Update with update method </span>
second_set.update({<span class="hljs-number">4</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">7</span>})

print(first_set) <span class="hljs-comment"># Output: {1, 2, 3, 4}</span>
print(second_set)  <span class="hljs-comment"># OUtput: {3, 4, 5, 7, 8, 9}</span>
</code></pre>
<h4 id="heading-remove-operation-using-sets-in-python">Remove Operation using Sets in Python</h4>
<p>In Python, the function of the <code>remove()</code> method in sets is to remove a specific element if it exists. The <code>discard()</code> method is also used  for removing an element if it exists.</p>
<p>The only difference is that <code>discard()</code> won't raise an error if the element doesn't exist, but <code>remove()</code> will raise a <code>KeyError</code>.</p>
<pre><code class="lang-python">first_set = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>}
second_set = {<span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}

first_set.remove(<span class="hljs-number">5</span>) <span class="hljs-comment"># Output:KeyError: 5</span>
second_set.discard(<span class="hljs-number">4</span>)  <span class="hljs-comment"># Output:KeyError: {3, 5}</span>

print(first_set)
print(second_set)
</code></pre>
<h4 id="heading-frozenset-operation-using-sets-in-python">Frozenset Operation using Sets in Python</h4>
<p>The <code>frozenset</code> is a built-in immutable set. It gets defined like a regular set with <code>{}</code>, but its element cannot be changed or modified after creation.</p>
<pre><code class="lang-python"><span class="hljs-comment"># Creating a frozenset</span>

frozen_set = frozenset([<span class="hljs-number">7</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">1</span>, <span class="hljs-number">5</span>])

<span class="hljs-comment"># Frozensets are immutable.</span>

 frozen_set.add(<span class="hljs-number">6</span>)  <span class="hljs-comment"># An AttributeError will be raised</span>

<span class="hljs-comment"># Elements of a frozenset cannot be changed once it's created</span>

frozen_set[<span class="hljs-number">0</span>] = <span class="hljs-number">10</span>  <span class="hljs-comment"># TypeError will  be raised</span>

<span class="hljs-comment"># You can perform set operations like union, intersection, and difference on the frozenset</span>
</code></pre>
<h2 id="heading-none-data-type-in-python">None Data Type in Python</h2>
<p>In Python, the <code>None</code> data type represents the absence of a value or a null value.</p>
<p>It indicates the function does not a have a return value or the expression lacks a meaningful value.</p>
<p>Some key takeaways from the None data type:</p>
<ul>
<li><strong>Type</strong>: <code>None</code> is called the <code>NoneType</code> data type in Python.</li>
<li><strong>Return Value</strong>: <code>None</code> is the default return value for a function without a value.</li>
<li><strong>Default Value</strong>: We can use <code>None</code> as a default argument in the function definition.</li>
</ul>
<pre><code class="lang-python"><span class="hljs-comment"># Initializing z with None, indicating that it does not currently hold any meaningful value.</span>

z = <span class="hljs-literal">None</span>
print(z)  <span class="hljs-comment"># Output: None</span>


y = <span class="hljs-literal">None</span>
<span class="hljs-keyword">if</span> y <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
    print(<span class="hljs-string">"The Value of y is:"</span> <span class="hljs-string">"x is None"</span>)

<span class="hljs-comment"># Output: The Value of y is :y is None</span>


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">pair</span>(<span class="hljs-params">y=None</span>):</span>
    <span class="hljs-keyword">if</span> y <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
        print(<span class="hljs-string">"y is None"</span>)

pair()  <span class="hljs-comment"># Output: y is None</span>


<span class="hljs-comment"># The greeting() function prints a message if a name is provided, otherwise it greets a stranger, but since the function does not return any value explicitly, it returns None by default.</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">greeting</span>(<span class="hljs-params">name</span>):</span>
    <span class="hljs-keyword">if</span> name:
        print(<span class="hljs-string">"Hi, "</span> + name)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">"Hi, Stranger"</span>)

result = greeting(<span class="hljs-string">"Kamaldeen"</span>)  <span class="hljs-comment"># Output: Hello, Kamaldeen</span>
print(result)  <span class="hljs-comment"># Output: None</span>
</code></pre>
<h2 id="heading-boolean-data-type-in-python">Boolean Data Type in Python</h2>
<p>In Python, there are only two values used for comparisons and logical operation when using the <code>boolean</code> data type. They are the <code>True</code> and <code>False</code> values.</p>
<p>The <code>boolean</code> values are the result that arises from the comparison operators such as the equal (<code>==</code>), the not equal (<code>!=</code>), the greater than (<code>&gt;</code>), the less than (<code>&lt;</code>), the greater than or equal to (<code>&gt;=</code>), and the less than or equal to (<code>&lt;=</code>).</p>
<pre><code class="lang-python">a = <span class="hljs-number">10</span>
b = <span class="hljs-number">15</span>

<span class="hljs-comment"># Comparison operators</span>

print(a == b)  <span class="hljs-comment"># False</span>
print(a &lt; b)   <span class="hljs-comment"># True</span>

<span class="hljs-comment"># Logical operators</span>

print(a &lt; <span class="hljs-number">10</span> <span class="hljs-keyword">and</span> b &gt; <span class="hljs-number">5</span>)  <span class="hljs-comment"># False</span>
print(a &lt; <span class="hljs-number">3</span> <span class="hljs-keyword">or</span> b&gt; <span class="hljs-number">20</span>)   <span class="hljs-comment"># False</span>
print(<span class="hljs-keyword">not</span>(a == b))        <span class="hljs-comment"># True</span>

<span class="hljs-comment"># Control Flow</span>

age = <span class="hljs-number">75</span>

<span class="hljs-keyword">if</span> age &gt;= <span class="hljs-number">18</span>:
    print(<span class="hljs-string">"You are an adult."</span>)
<span class="hljs-keyword">else</span>:
    print(<span class="hljs-string">"You are a minor."</span>)

<span class="hljs-comment"># Functions return</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">is_even</span>(<span class="hljs-params">number</span>):</span>
    <span class="hljs-keyword">return</span> number % <span class="hljs-number">2</span> == <span class="hljs-number">0</span>

print(is_even(<span class="hljs-number">10</span>))  <span class="hljs-comment"># True</span>
print(is_even(<span class="hljs-number">7</span>))  <span class="hljs-comment"># False</span>
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this tutorial, you learned about the various data types in Python.</p>
<p>We talked about several built-in data types like the sequence, mapping, set, none, and Boolean types.</p>
<p>Happy reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use the JavaScript insertAdjacentHTML() method for Efficient DOM Manipulation ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript, developers need to be able to dynamically update a page without replacing the entire content. A traditional method like innerHTML can cause performance issues, because these methods tend to replace the entire content of an element. The... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-insertadjacenthtml-method-efficient-dom-manipulation/</link>
                <guid isPermaLink="false">66d03966871ae63f179f6be9</guid>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kamaldeen Lawal ]]>
                </dc:creator>
                <pubDate>Wed, 07 Feb 2024 16:28:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/The-JavaScript-insertAdjacentHTML---Method.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript, developers need to be able to dynamically update a page without replacing the entire content. A traditional method like <code>innerHTML</code> can cause performance issues, because these methods tend to replace the entire content of an element.</p>
<p>The <code>insertAdjacentHTML()</code> method leads to better performance because you use it to dynamically insert new HTML content without affecting the existing content.</p>
<p>In this tutorial, we'll cover the following:</p>
<ul>
<li><a class="post-section-overview" href="#heading-introduction-to-the-insertadjacenthtml-method">Introduction to the <code>insertAdjacentHTML()</code> method</a></li>
<li><a class="post-section-overview" href="#heading-syntax-of-the-insertadjacenthtml-method">Syntax of the <code>insertAdjacentHTML()</code> method</a></li>
<li><a class="post-section-overview" href="#placement-options-in-insertadjacenthtml-method">Placement options in the</a> <a class="post-section-overview" href="#placement-options-in-insertadjacenthtml-method"><code>insertAdjacentHTML()</code> method</a></li>
<li><a class="post-section-overview" href="#browser-support-for-the-inneradjacenthtml-method">Browser support for the <code>insertAdjacentHTML()</code> method</a></li>
<li><a class="post-section-overview" href="#best-practices-for-using-theinsertadjacenthtml-method">Best Practices for using the</a> <a class="post-section-overview" href="#best-practices-for-using-theinsertadjacenthtml-method"><code>insertAdjacentHTML()</code> method</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-introduction-to-the-insertadjacenthtml-method">Introduction to the <code>insertAdjacentHTML()</code> method</h2>
<p>The <code>insertAdjacentHTML()</code> method provides an efficient way to manipulate web page structure without replacing all the content of an element. It's also the go-to method for inserting HTML elements or text elements into a specific position.</p>
<p><code>insertAdjacentHTML</code> is a method in JavaScript that allows you to insert HTML elements or text into a specific position relative to a given element in the DOM (Document Object Model). This method provides flexibility in manipulating the structure of a web page dynamically.</p>
<h2 id="heading-syntax-of-the-insertadjacenthtml-method">Syntax of the <code>insertAdjacentHTML()</code> method</h2>
<p>Here's what the syntax of the <code>insertAdjacentHTML()</code> method looks like:</p>
<pre><code class="lang-javascript">HTMLelement.insertAdjacentHTML(position, element);
</code></pre>
<p>The <code>insertAdjacentHTML</code> method takes two parameters:</p>
<ol>
<li><p><strong>position:</strong> This parameter is a string representation of where the new HTML should be inserted in relation to the <code>targetElement</code>. It must match one of the following strings:</p>
</li>
<li><p><code>**"beforebegin"**</code>: The <code>beforebegin</code> string value of the <code>insertAdjacentHTML()</code> method inserts the HTML element immediately before the specified element in the <code>DOM</code>.</p>
</li>
<li><code>**"afterbegin"**</code>: The <code>afterbegin</code> string value of the<code>insertAdjacentHTML()</code> method inserts the HTML element inside the <code>targetElement</code>, just before its first child.</li>
<li><code>**"beforeend"**</code>: The <code>beforeend</code> is a string value of  the <code>insertAdjacentHTML()</code> method that  inserts an HTML element inside the <code>targetElement</code>, after its last child.</li>
<li><p><code>**"afterend"**</code>: The <code>afterend</code> string value of the <code>insertAdjacentHTML()</code> method inserts an HTML element immediately after the specified element in the <code>DOM</code>.</p>
</li>
<li><p><strong>element:</strong> The element to be inserted into the <code>DOM</code> tree.</p>
</li>
</ol>
<h2 id="heading-placement-options-in-the-insertadjacenthtml-method">Placement Options in the <code>insertAdjacentHTML()</code> Method</h2>
<p>Now that you've seen the four possible parameters of the <code>insertAdjacentHTML()</code> method, let's see how they work with code.</p>
<ul>
<li><code>beforebegin</code>: Here's an example using the <code>beforebegin</code> parameter in code:</li>
</ul>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> targetElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'h1'</span>);
targetElement.insertAdjacentHTML(<span class="hljs-string">'beforebegin'</span>, <span class="hljs-string">'&lt;h2&gt;Lawal&lt;/h2&gt;'</span>);
</code></pre>
<p>Here's the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/beforebegin.png" alt="beforebegin" width="600" height="400" loading="lazy">
<em>beforebegin</em></p>
<p>Recall that the <code>beforebegin</code> string value of the <code>insertAdjacentHTML()</code> method inserts the HTML element immediately before the specified element in the <code>DOM</code>.</p>
<p>In the above code result, our newly inserted HTML element <code>h3</code> got inserted before our <code>targetElement</code> <code>h2</code>. I styleed our <code>targetElement</code> by adding a border to it for easy illustration.</p>
<ul>
<li><code>afterbegin</code>: here's an example of using the <code>afterbegin</code> parameter in code:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> targetElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'h1'</span>);
targetElement.insertAdjacentHTML(<span class="hljs-string">'afterbegin'</span>, <span class="hljs-string">'&lt;h2&gt;Lawal&lt;/h2&gt;'</span>);
</code></pre>
<p>And here's the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/afterbegin.png" alt="afterbegin" width="600" height="400" loading="lazy">
<em>afterbegin</em></p>
<p>As defined above, the <code>afterbegin</code> string value of the <code>insertAdjacentHTML()</code> method inserts the HTML element inside the <code>targetElement</code>, just before its first child.</p>
<p>By checking the output of our code, you may realize that our newly inserted HTML element <code>h3</code> got inserted inside our <code>targetElement</code> <code>h2</code>. Again, I styled our <code>targetElement</code> by adding a border to it for easy illustration.</p>
<ul>
<li><code>beforeend</code>: here's an example of using <code>beforeend</code> in code:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> targetElement = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'h1'</span>);
targetElement.insertAdjacentHTML(<span class="hljs-string">'beforeend'</span>, <span class="hljs-string">'&lt;h2&gt;Lawal&lt;/h2&gt;'</span>);
</code></pre>
<p>And here's the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/beforeend.png" alt="beforeend" width="600" height="400" loading="lazy">
<em>beforeend</em></p>
<p>The general definition of <code>beforeend</code> is that it's a string value of the <code>insertAdjacentHTML()</code> method that inserts an HTML element inside the <code>targetElement</code>, after its last child.</p>
<p>From the code result, our newly inserted <code>HTML</code> element <code>h3</code> got inserted inside our <code>targetElement</code> <code>h2</code> after its child. I styled our <code>targetElement</code> by adding a border to it for easy illustration.</p>
<ul>
<li><code>afterend</code>: here's an example of using <code>aferend</code> in code:</li>
</ul>
<pre><code class="lang-javscript">const targetElement = document.querySelector('h1');
targetElement.insertAdjacentHTML('afterend', '&lt;h2&gt;Lawal&lt;/h2&gt;');
</code></pre>
<p>And here's the output:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/afterend.png" alt="afterend" width="600" height="400" loading="lazy">
<em>afterend</em></p>
<p>As you now know, <code>afterend</code>  is a string value of the <code>insertAdjacentHTML()</code> method that inserts an <code>HTML</code> element immediately after the specified element in the <code>DOM</code>.</p>
<p>In the above code, our newly inserted HTML element <code>h3</code> got inserted immediately after our <code>targetElement</code> <code>h2</code>. I styled our <code>targetElement</code> by adding a border to it for easy illustration.</p>
<h2 id="heading-browser-support-for-the-insertadjacenthtml-method">Browser Support for the <code>insertAdjacentHTML()</code> Method</h2>
<p>The <code>insertAdjacentHTML()</code> method is a widely supported method that can be relied upon for your <code>DOM</code> manipulation needs across different modern browsers. </p>
<p>To see the browsers that support this method, check out the summary below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/browser-compat.png" alt="browser compatibility" width="600" height="400" loading="lazy">
<em>browser compatibility</em></p>
<ol>
<li><strong>Edge</strong>: Supported across all versions.</li>
<li><strong>Chrome</strong>: Supported across all versions.</li>
<li><strong>Opera</strong>: Supported across all versions.</li>
<li><strong>Safari</strong>: Supported across all versions, except version 3.1-3.2</li>
<li><strong>Firefox</strong>: Supported across all versions, except version 2-7</li>
</ol>
<h2 id="heading-best-practices-for-using-the-insertadjacenthtml-method">Best Practices for Using the <code>insertAdjacentHTML()</code> Method</h2>
<p>To effectively use the <code>insertAdjacentHTML()</code> method, here are some best practices to follow:</p>
<h3 id="heading-understand-the-method">Understand the method</h3>
<p>Understanding how the method works helps you specify the position to insert your HTML content. Understand the various positions and choose appropriately based on your requirements.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Inserting the HTML content after the target element</span>
<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'div'</span>).insertAdjacentHTML(<span class="hljs-string">'afterend'</span>, <span class="hljs-string">'&lt;div&gt;New content before the target element&lt;/div&gt;'</span>);
</code></pre>
<h3 id="heading-use-it-sparingly">Use it sparingly</h3>
<p>Overusing dynamic HTML element insertion methods is bad for code maintenance.</p>
<p>For a simple application, a direct <code>DOM</code> manipulation will do the job.</p>
<pre><code class="lang-javascript">/ Consider Using <span class="hljs-built_in">this</span>:
<span class="hljs-keyword">let</span> newElement = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
newElement.textContent = <span class="hljs-string">'New element'</span>;
element.appendChild(newElement);


<span class="hljs-comment">// Instead of this:</span>
element.insertAdjacentHTML(<span class="hljs-string">'beforeend'</span>, <span class="hljs-string">'&lt;div&gt;New element&lt;/div&gt;'</span>);
</code></pre>
<h3 id="heading-be-conscious-of-performance">Be conscious of performance</h3>
<p>If you frequently insert large amounts of HTML content, manipulating the <code>DOM</code> can be expensive for performance. Try to minimize <code>DOM</code> updates, especially in performance scenarios:</p>
<pre><code class="lang-javascript">

<span class="hljs-comment">// Consider using batch insertion:</span>
<span class="hljs-keyword">let</span> section = <span class="hljs-string">''</span>;
data.forEach(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> {
  section += <span class="hljs-string">`&lt;div&gt;<span class="hljs-subst">${item}</span>&lt;/div&gt;`</span>;
});
element.insertAdjacentHTML(<span class="hljs-string">'beforeend'</span>, section);


<span class="hljs-comment">// Instead of inserting one by one in a loop:</span>
data.forEach(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> {
  element.insertAdjacentHTML(<span class="hljs-string">'beforeend'</span>, <span class="hljs-string">`&lt;div&gt;<span class="hljs-subst">${item}</span>&lt;/div&gt;`</span>);
});
</code></pre>
<h3 id="heading-handling-errors">Handling errors</h3>
<p>When using the <code>insertAdjacentHTML()</code> method, if the HTML content you're trying to insert is invalid, the method may throw an error. Use try-catch blocks to handle these situations appropriately. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> div  = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'div'</span>);

<span class="hljs-keyword">try</span> {
    <span class="hljs-comment">// Check if the value of div is true</span>
    <span class="hljs-keyword">if</span> (div.insertAdjacentHTML) {
        div.insertAdjacentHTML(<span class="hljs-string">'beforeend'</span>, <span class="hljs-string">'&lt;div&gt;New Element&lt;/div&gt;'</span>);
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'insertAdjacentHTML is not supported.'</span>);
    }
} <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-comment">// Handling the error</span>

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


    <span class="hljs-comment">// Alternate code</span>
    div.innerHTML += <span class="hljs-string">'&lt;div&gt;Fallback: New Element&lt;/div&gt;'</span>;
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you learned about the syntax and placement options of the <code>insertAdjacentHTML()</code> method. We also looked at browser compatibility, and some best practices while using the <code>insertAdjacentHTML()</code> method.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Event Bubbling and Event Capturing in JavaScript – Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ If you want to improve your JavaScript code, you should understand how event bubbling and event capturing work. The ability to consistently run your code when certain events happen is crucial.  In this tutorial, you’ll learn about the following topic... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/event-bubbling-and-event-capturing-in-javascript/</link>
                <guid isPermaLink="false">66d03961c1024fe75b758f71</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kamaldeen Lawal ]]>
                </dc:creator>
                <pubDate>Tue, 17 Oct 2023 21:26:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/10/Event-Bubbling-and-Event-Capturing-in-JavaScript-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you want to improve your JavaScript code, you should understand how event bubbling and event capturing work. The ability to consistently run your code when certain events happen is crucial. </p>
<p>In this tutorial, you’ll learn about the following topics:</p>
<ul>
<li><a class="post-section-overview" href="#heading-what-are-events-in-javascript">What are Events in JavaScript</a>?</li>
<li><a class="post-section-overview" href="#heading-what-are-event-handlers">What are Event Handlers</a>?</li>
<li><a class="post-section-overview" href="#heading-event-flow-in-the-dom">Event Flow in the DOM</a></li>
<li><a class="post-section-overview" href="#heading-what-is-event-bubbling">What is Event Bubbling</a>?</li>
<li><a class="post-section-overview" href="#heading-what-is-event-capturing">What is Event Capturing</a>?</li>
<li><a class="post-section-overview" href="#how-does-event-stoppropagation-work">How Does event.stopPropagation Work</a>?</li>
<li><a class="post-section-overview" href="#heading-what-is-event-delegation">What is Event Delegation</a>?</li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-are-events-in-javascript">What are Events in JavaScript?</h2>
<p>Events do not only exist in JavaScript but in all programming languages. The primary idea behind events in JavaScript is the ability to run code when a certain event happens. This could be a user clicking a button or any other events you might think of that could trigger some code to run. </p>
<p>Although there’s a distinct difference between events on the browser and server side of JavaScript, the core idea remains the same. </p>
<p>As events transport data, an object is created and given as an argument to the function you set as an event handler. When events occur in JavaScript, an object that contains information about that event gets created. This object will then be passed as an argument to the event handler function. This gives you easy access to the event data and makes it easy to respond as well.  </p>
<p>Here's a more detailed explanation:</p>
<ul>
<li>An event can be called by different actions. Examples are clicks, mouse movements, and time intervals.</li>
<li>Javascript creates an event object whenever an event occurs. This object has properties and methods, and provides details about the event.</li>
<li>You can set a function that will be executed whenever the event occurs with event handlers in JavaScript. </li>
<li>The event object is automatically created whenever the event is triggered. This object is therefore passed as an argument to the event handler function.</li>
</ul>
<p>Let's see what this looks like in code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'check'</span>)


button.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Event type: '</span> + e.type);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Target element: '</span> + e.target);
});


<span class="hljs-comment">//  The answer</span>

<span class="hljs-comment">// Event type: click</span>
<span class="hljs-comment">// Target element: [object HTMLButtonElement]</span>
</code></pre>
<h4 id="heading-code-explanation">Code Explanation:</h4>
<p>The above is a snippet of JavaScript code.</p>
<p>The function provided as the event handler gets called whenever the click event occurs on the button element. It then receives the event object as the event parameter, which allows for easy access to the properties and data related to the click event.</p>
<p>By gaining access to this event object within the event handler, you can customize your response based on the event data and properties.</p>
<p>There is specific informatioon available inside the event object based on the type of event that occured. For the click event in our example, the included details are the <code>event.target</code> and the <code>event.type</code>.</p>
<h2 id="heading-what-are-event-handlers">What Are Event Handlers?</h2>
<p>Event handlers are like a special all-purpose remote control that can perform certain actions like changing channels on your TV, increasing the temperature of your AC, and changing the state of your lighting in your home. But they need a professional to handle a special button attached to it. </p>
<p>The above analogy explains the concepts of event handling in JavaScript. The remote control represents the application you are using. The HTML element-like button on the application is the special button attached to the remote. And the professional that handles the special button is the JavaScript. </p>
<p>Event handling in JavaScript makes applications and webpages responsive and interactive. They do this by defining and managing events and performing specific actions whenever those events occur. </p>
<p>An event handler is any function or method specifically define to respond to a specific event in JavaScript. It is also responsible for the execution of code when a particular event occurs. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'check'</span>)


button.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Event'</span>, e.target)
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Button click'</span>)
});


<span class="hljs-comment">//  The answer</span>

<span class="hljs-comment">// Event &lt;button id=​"check"&gt;​Check Order​&lt;/button&gt;​</span>
<span class="hljs-comment">// Button click</span>
</code></pre>
<h5 id="heading-code-explanation-1">Code Explanation:</h5>
<p>The above is a snippet of JavaScript code.</p>
<p>A click event handler is attached to the button element. When the button gets clicked, it logs the something to the console.</p>
<p>When an event occurs, an event object is created by the browser. This object is then passed as an argument to the event handler function. With this, data and properties within the event object can be accessed.</p>
<p>As you hopefully now understand, event handlers are a key part of creating dynamic web applications.</p>
<h2 id="heading-event-flow-in-the-dom">Event Flow in the DOM</h2>
<p>Events are generally processed in three phases in the DOM. They are the capturing, the target, and the bubbling phase. </p>
<h3 id="heading-the-capturing-phase">The capturing phase</h3>
<p>The first phase is the <strong>capturing phase</strong>, which occurs when an element nested in various elements gets clicked. Right before the click reaches its final destination, the click event of each of its parent elements must be triggered. This phase trickles down from the top of the DOM tree to the target element.</p>
<h3 id="heading-the-target-phase">The target phase</h3>
<p>The <strong>target phase</strong> is the second phase that begins immediately after the capturing phase ends. This phase is basically the end of the capturing and the beginning of the bubbling phase. </p>
<p>The target element is the element where the event originally occurred. For example, if you submit a form on a web page, the form element is the target element for the submit event. In the case where there is an event handler on a button on a webpage, the button is the target element for the event handler. </p>
<p>Event handlers registered on the button element are considered to be the target element during this phase.</p>
<h3 id="heading-the-bubbling-phase">The bubbling phase</h3>
<p>The <strong>bubbling phase</strong>, which is the last phase, is the reverse of the capturing phase. In this phase, the event bubbles up the target element through its parent element, the ancestor, to the global window object. By default, all events you add with <code>addEventListener</code> are in the bubble phase.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/bubbling-and-capturing2.png" alt="Event Flow in JavaScript" width="600" height="400" loading="lazy">
<em>Event Flow Process</em></p>
<h2 id="heading-what-is-event-bubbling">What is Event Bubbling?</h2>
<p>Event bubbling, as I mentioned above, is the phase where the event bubbles up from the target element all the way to the global window object. </p>
<p>When an event "bubbles up" in the <code>DOM</code> event flow context, this refers to a phase in event flow where an event which traditionally occurs after the target phase continues to propagate from the target element to the root of the document through the <code>DOM</code> hierarchy.</p>
<h4 id="heading-how-event-bubbling-works">How event bubbling works</h4>
<p>The event starts to bubble up through the <code>DOM</code> hierarchy after it has been processed at the target element. The event then travels from the target element to the root of the document. It passes through all ancestor elements according to how they are nested in the bubbling phase.</p>
<p>During an event handler's execution phase, any event handlers registered on ancestor elements get executed. This allows for easy capture of events at various stages of the <code>DOM</code> hierarchy. </p>
<p>This action can be stopped using the <code>stopPropagation()</code> method on the event object. It's useful when you aim to prevent event handlers from the ancestor elements gettomg triggered.</p>
<p>With bubbling, events can be handled in a hierarchical manner. By setting an event handler on the parent element or container, you can handle events from multiple child elements.</p>
<p>Event bubbling allows for an easier implementation of event delegation.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/bubbling-and-capturing3.png" alt="Event Bubbling" width="600" height="400" loading="lazy"></p>
<p>Here's an example of how it works, which I'll explain below:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Practice<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Bubbling and Capturing phase<span class="hljs-tag">&lt;/<span class="hljs-name">h1</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">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child"</span>&gt;</span>click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> parent = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"div"</span>);
      <span class="hljs-keyword">const</span> child = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".child"</span>);

      parent.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"clicked parent"</span>);
      });

      child.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"clicked child"</span>);
      });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>



<span class="hljs-comment">&lt;!-- 

         RESULTS OF THE ABOVE CODE

         index.html:25 clicked child
         index.html:21 clicked parent

 --&gt;</span>
</code></pre>
<h4 id="heading-code-explanation-2">Code Explanation:</h4>
<p>The above is a snippet of HTML and JavaScript code.</p>
<p>Inside the body element, we have the <code>h1</code>, <code>div</code>, and the <code>button</code> element. The div is the parent element of the button element. We gave a class name of child for the button element.</p>
<p>In the JavaScript section, we created variables for both the parent and child elements. Then we added event listeners to both the parent and child elements.</p>
<p>Thus, when the button gets clicked, the clicked child is first invoked. This means that the function within the parent element executes after the function within the child element.</p>
<h2 id="heading-what-is-event-capturing">What is Event Capturing?</h2>
<p>Event capturing occurs when a nested element gets clicked. The click event of its parent elements must be triggered before the click of the nested element. This phase trickles down from the top of the <code>DOM</code> tree to the target element.  </p>
<p>Event capturing can't happen until the third argument of <code>addEventListener</code> is set to the <code>Boolean</code> value of true as shown below (default value is false).  </p>
<p>Whenever the third argument of <code>addEventListener</code> is set to <code>true</code>, event handlers are automatically triggered in the capturing phase. With this, the event handler attached to an ancestor element will be executed first when an event occurs on a nested element within the <code>DOM</code> hierarchy. This is unlike the default, where event handlers are triggered during the bubbling phase.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/10/bubbling-and-capturing4.png" alt="Event Capturing" width="600" height="400" loading="lazy">
<em>Event Capturing</em></p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Practice<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Bubbling and Capturing phase<span class="hljs-tag">&lt;/<span class="hljs-name">h1</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">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"child"</span>&gt;</span>click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> parent = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"div"</span>);
      <span class="hljs-keyword">const</span> child = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".child"</span>);

      parent.addEventListener(
        <span class="hljs-string">"click"</span>,
        <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
          <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"clicked parent"</span>);
        },
        <span class="hljs-literal">true</span>
      );

      child.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"clicked child"</span>);
      });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>

<span class="hljs-comment">&lt;!-- 

       RESULTS OF THE ABOVE CODE

      index.html:25 clicked parent
      index.html:21 clicked child

 --&gt;</span>
</code></pre>
<h4 id="heading-code-explanation-3">Code Explanation:</h4>
<p>The above is a snippet of HTML and JavaScript code. Inside the body element, we have the <code>h1</code>, <code>div</code>, and the <code>button</code> element.</p>
<p>The div is the parent element of the button element. We gave a class name of child to the button element.</p>
<p>In the JavaScript section, we created variables for both the parent and child elements. We added event listeners to both the parent and child elements as well.</p>
<p>In the parent element, we set the <code>Boolean</code> value to "true" for the third argument. The default value is false.</p>
<p>Thus, when the button gets clicked, the clicked parent was first invoked. This means that the function within the parent element executes before the function within the child element.</p>
<h2 id="heading-how-does-the-eventstoppropagation-method-work">How Does the <code>event.stopPropagation</code> Method Work?</h2>
<p>By default, all event handlers are registered in the bubbling phase (from the target element to all its ancestor elements). This default configuration can be modified by adding the <code>event.stopPropagation</code> method to the target element.</p>
<p>As its name suggests, the <code>Event.stopPropagation</code> method stops propagation. Any other listener for the same type of event on some ancestor element will not trigger their event listener for the event.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Practice<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Bubbling and Capturing phase<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Kamal<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>Lawal<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>Olaide<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>Ayinde<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">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> parent = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"ul"</span>);
      <span class="hljs-keyword">const</span> li = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"li"</span>);

      parent.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"clicked parent"</span>);
      });

      li.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">list</span>) </span>{
        list.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
          event.stopPropagation();
          event.target.classList.toggle(<span class="hljs-string">"highlight"</span>);
        });
      });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Unlike the default, <code>event.stopPropagation</code> will prevent the parent element <code>ul</code> from showing in the console. Note that the <code>event.stopPropagation</code> method can also be used in the capturing phase.</p>
<h2 id="heading-what-is-event-delegation">What is Event Delegation?</h2>
<p>Imagine your office without a manger. This office is likely going to be less efficient than one with a manager. Managers don't do or oversee every task individually – instead, they will delegate responsibilities to their employees. This delegation allows the manager to efficiently manage the workload, and then step in if something goes wrong.</p>
<p>Event delegation in JavaScript is similar to the above example, as it makes it easier to manage and handle events on multiple child elements. It takes advantage of the <code>DOM</code> (Document Object Model) bubbling event. This means setting event listeners on ancestor elements allows you to handle events efficiently. Unlike setting event listeners on individual elements that trigger the events. Recall that in the bubbling phase, the events on the child element rise to their parent element.</p>
<p>Check the below code to help you understand how this works:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Practice<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Orange<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>Banana<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>Potato<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>Apple<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">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> li = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"li"</span>);

      li.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">list</span>) </span>{
        list.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
          alert(<span class="hljs-string">"Yes, I click"</span>);
        });
      });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In the above code, an event listener was added to each of the <code>listItems</code>. Then, whenever they get clicked, an alert pops up. Traditionally, this is not bad code, but it defeats the purpose of event delegation.  In the code below, you'll see the importance of event delegation.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Practice<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Bubbling and Capturing phase<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Kamal<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>Lawal<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>Olaide<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>Ayinde<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">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> ul = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"ul"</span>);

      ul.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        event.target.classList.toggle(<span class="hljs-string">"highlight"</span>);
      });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Unlike the initial code, the parent of the listItems <code>ul</code> will handle the event here. So the parent will delegate the logic we want to achieve to the child. Recall that the <code>listItems</code> bubbles up in the <code>DOM</code> tree.</p>
<p>But there are some situations where it will be almost impossible to delegate to a child element. For example, it's impossible if the child has a nested child element itself. In this case, it will be impossible to delegate to a child element.</p>
<p> Here's a code example that shows you why it may be impossible to delegate to a child element:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Practice<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Bubbling and Capturing phase<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Orange<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Kamal<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h2</span>&gt;</span>Apple<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lawal<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h2</span>&gt;</span>Banana<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Olaide<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> ul = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"ul"</span>);

      ul.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        event.target.classList.toggle(<span class="hljs-string">"highlight"</span>);
      });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>The above code will not produce the expected output. This is because in our code, we use <code>event.target</code>.</p>
<p>In JavaScript, <code>event.target</code> is the actual <code>DOM</code> element that gets clicked. In this instance, the three possible outcomes are the <code>li</code>, <code>h2</code>, and the <code>p</code>. The code below shows the solution to this problem:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Practice<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Bubbling and Capturing phase<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Orange<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Kamal<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h2</span>&gt;</span>Apple<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lawal<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">h2</span>&gt;</span>Banana<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Olaide<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">script</span>&gt;</span><span class="javascript">
      <span class="hljs-keyword">const</span> ul = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"ul"</span>);

      ul.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        event.target.closest(<span class="hljs-string">"li"</span>).classList.toggle(<span class="hljs-string">"highlight"</span>);
      });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>To get the expected result of selecting the listItem, we combine both the <code>DOM</code> traversal method with <code>event.target</code>.</p>
<p>The <code>closest</code> method is available on <code>DOM</code> objects. <code>closest</code> traverses up in the ancestry tree. You can select the closest element with any CSS selector by ID, tag, or classname. One interesting thing is that <code>closest</code> includes the element you call it on, in this case the <code>li</code>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Hopefully after reading this guide, you now have a clearer understanding of events, event handlers, and event flow in JavaScript. </p>
<p>You learned about how event capturing and bubbling work, and you should now understand the main concepts behind event delegation, too.</p>
<p>Thanks for reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Alternatives to Prettier – Popular Code Linting and Formatting Tools ]]>
                </title>
                <description>
                    <![CDATA[ Many programmers hate code formatting because it is tedious and time-consuming. You can spend hours making sure everything is perfect and well-indented.  This is why code formatters are so useful. A code formatter is a tool that formats code accordin... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/alternatives-to-prettier/</link>
                <guid isPermaLink="false">66d0395a386d35c4e3bb3c39</guid>
                
                    <category>
                        <![CDATA[ clean code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ eslint ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Prettier ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kamaldeen Lawal ]]>
                </dc:creator>
                <pubDate>Wed, 15 Mar 2023 17:43:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/Alternatives-to-Prettier.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Many programmers hate code formatting because it is tedious and time-consuming. You can spend hours making sure everything is perfect and well-indented. </p>
<p>This is why code formatters are so useful.</p>
<p>A code formatter is a tool that formats code according to certain standards. It makes it so you don't have to worry as much about code formatting. Instead, you can focus on writing good code. This save time and also reduces your stress.</p>
<p>In this guide, we will talk about the Prettier code formatter. We will also talk about alternatives to Prettier like JsFmt, StandardJS, EsLint + EditorConfig, and Beautifier. Hopefully you’ll take away something that you can use to improve your code formatting.</p>
<h2 id="heading-brief-overview-of-prettier">Brief Overview of Prettier</h2>
<p><a target="_blank" href="https://prettier.io/">Prettier</a> is a popular code formatter that can handle complex code structures and format your code in a readable way.</p>
<p>It operates on the principle of no configuration required and it's designed to produce readable, consistent code. </p>
<p>Prettier is an opinionated tool that encourages programmers to follow its formatting rules. It also parses the code and reprints it uniformly.</p>
<h2 id="heading-why-explore-alternatives-to-prettier">Why Explore Alternatives to Prettier?</h2>
<p>There are many advantages of using Prettier. But like every other tool, exploring alternatives is sometimes a good idea. Here are some of the reasons for exploring alternatives to Prettier:</p>
<ol>
<li><strong>Inflexible style guides</strong>: Prettier adopts a strict set of formatting rules, and does not allow for much customization. Some programmers want a tool with a lot of configurations available.</li>
<li><strong>Speed</strong>: Although Prettier is fast, you may need a tool that provides faster and better performance in large codebases or real-time formatting.</li>
<li><strong>Language support</strong>: Prettier may not support (or might offer inadequate support) for the language you use.</li>
<li><strong>More features</strong>: While Prettier is open source, you might prefer a paid code formatter that has more features and better integration with other tools.</li>
</ol>
<p>In the guide, we will talk about four alternatives to Prettier. They are:</p>
<ul>
<li>JsFmt</li>
<li>StandardJS</li>
<li>ESLint+EditorConfig</li>
<li>JS Beautifier</li>
</ul>
<h2 id="heading-jsfmt-overview">JsFmt Overview</h2>
<p><a target="_blank" href="https://rdio.github.io/jsfmt/">JsFmt</a> is a code formatter that uses esformatter as a formatting tool. It automatically reformats JavaScript code according to a set of predefined rules. It is available specifically to re-write, format, search, and validate JavaScript code.</p>
<p>To install JsFmt, run this command:</p>
<pre><code>npm install -g jsfmt
</code></pre><p>A .jsfmtrc file, which can either be a JSON or INI formatted file, can overwrite any of the esformatter formatting options.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"indent"</span>: <span class="hljs-number">4</span>,
  <span class="hljs-attr">"line_ending"</span>: <span class="hljs-string">"unix"</span>,
  <span class="hljs-attr">"quote"</span>: <span class="hljs-string">"single"</span>
}
</code></pre>
<p>In this example, we specified the spaces for indentation to be four, we chose line-ending to be unix, and we picked single as the quote style for strings.</p>
<p>You can use the jsfmt rewrite method to change values in your JavaScript code. Here's an example of how to do that:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> x = <span class="hljs-number">5</span>;
<span class="hljs-keyword">const</span> y = <span class="hljs-number">10</span>;
<span class="hljs-keyword">const</span> z = x + y;
<span class="hljs-built_in">console</span>.log(z);

<span class="hljs-comment">//  The output will change to the below code after writing:  npx jsfmt --rewrite '5 -&gt; 20' reduce.js</span>

<span class="hljs-keyword">const</span> x = <span class="hljs-number">20</span>;
<span class="hljs-keyword">const</span> y = <span class="hljs-number">10</span>;
<span class="hljs-keyword">const</span> z = x + y;
<span class="hljs-built_in">console</span>.log(z);
</code></pre>
<p>To learn more about JsFmt, you can read its documentation <a target="_blank" href="https://github.com/rdio/jsfmt">here</a>.</p>
<h3 id="heading-features-of-jsfmt">Features of JsFmt</h3>
<ol>
<li>Formating: JsFmt can format code according to a set of predefined rules.</li>
<li>Integrations: you can integrate JsFmt with popular code editors like Visual Studio Code, Sublime Text, and Atom, making it easy to format your code directly in your editor.</li>
<li>Command-line interface: JsFmt allows you to format your code as part of your build process or development workflow in the command line.</li>
</ol>
<h3 id="heading-jsfmt-formatting-rules">JsFmt Formatting Rules</h3>
<p>Some of the formatting rules adopted by JsFmt are as follows</p>
<ol>
<li>Set indent: With the <code>--indent</code> option, JsFmt indents your code with two spaces per level.</li>
<li>Quotes: In JsFmt, single quotes are the default for strings, but you can change this with the <code>--double-quote</code> option.</li>
<li>Wrapping: you can use <code>--linene-width</code> to change the default wrap lines setting in JsFmt.</li>
<li>Semicolons: JsFmt adds semicolons at the end of each statement by default. You can disable this using the <code>--no-semi</code> option.</li>
</ol>
<h3 id="heading-pros-of-jsfmt">Pros of JsFmt</h3>
<ol>
<li>Formatting, searching, and re-writing of JavaScript.</li>
<li>Customizable: JsFmt's flexibility makes it a popular choice for many development teams. It is a highly customizable tool that you can configure to match the specific requirements of a project.</li>
</ol>
<h3 id="heading-con-of-jsfmt">Con of JsFmt</h3>
<ol>
<li>Lack of flexibility: despite the fact that it's customizeable, certain parts of JsFmt may not always be configurable to match the needs of your project.</li>
</ol>
<h2 id="heading-standardjs-overview">StandardJS Overview</h2>
<p><a target="_blank" href="https://standardjs.com/">StandardJS</a> is an open-source, no configuration linter, formatter, and JavaScript style guide. It checks the code for probable errors with the linter. It also formats code automatically, and helps you write code that is easy to read and understand.</p>
<p>It is the most popular option, coming in at 27,905 stars on GitHub clean code linter. It is also a powerful tool for ensuring the quality and consistency of your JavaScript code.</p>
<p>You can either install it globally or locally on your machine. To install globally, use the first command, while the second command is for installing locally. Note that to install it, you must have Node and npm installed on your computer.</p>
<p>To install globally: <code>$ npm install standard --global</code></p>
<p>To install locally: <code>$ npm install standard --save-dev</code></p>
<p>Alternatively, you can add StandardJS to the package JSON.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"my-cool-package"</span>,
  <span class="hljs-attr">"devDependencies"</span>: {
    <span class="hljs-attr">"standard"</span>: <span class="hljs-string">"*"</span>
  },
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"standard &amp;&amp; node my-tests.js"</span>
  }
}
</code></pre>
<p>The styles are checked automatically when you run the command:</p>
<pre><code>npm test
</code></pre><p>To illustrate how it works, check the JavaScript code below:</p>
<pre><code class="lang-javascript!">let number = 10;
if (number == 10) {
  alert("yes");
} else {
  alert("no");
}

// The Output after running the npm test in the terminal

&gt; test
&gt; standard &amp;&amp; node my-tests.js

standard: Use JavaScript Standard Style (https://standardjs.com)
  C:\Users\hp\Desktop\pretier\Js\script.js:5:5: Parsing error: Unexpected token else (null)
</code></pre>
<p>StandardJS shows that the code has a parsing error.</p>
<p>To fix most issues, run the following code:</p>
<pre><code>standard --fix
</code></pre><h3 id="heading-features-of-standardjs">Features of StandardJS</h3>
<ol>
<li>Community: A community of contributors guides the development of StandardJS by providing bug fixes and new features.</li>
<li>Linting: StandardJS linting catches style issues and programmer errors early.</li>
<li>Automatic code formatting: StandardJS get rid of messy and inconsistent code.</li>
<li>Command line integration: It has a command-line interface for running linter checks and auto-formatting code.</li>
</ol>
<h3 id="heading-standardjs-formatting-rules">StandardJS Formatting Rules</h3>
<p>Some of the widely used StandardJS formatting rules are listed below:</p>
<ol>
<li>Indentation: StandardJS enforces a consistent indentation level of 2 spaces by default. To strictly implement this, you need to add the <code>--fix</code> option.</li>
<li>Line wrap: StandardJS doesn't enforce the rule of line length, but it recommends keeping lines shorter than 80 characters. Use <code>$ myfile.js | standard --stdin</code> to manually check the file length.</li>
<li>Semicolons: StandardJS recommends using semicolons for clarity and to avoid potential issues. But the tool doesn't enforce this. To enforce the use of semicolons, use this:</li>
</ol>
<pre><code class="lang-json">{
  <span class="hljs-attr">"extends"</span>: <span class="hljs-string">"standard"</span>
}
</code></pre>
<ol>
<li>Spaces around operators: StandardJS recommends using spaces around operators, such as + and -, but it doesn't enforce this rule.</li>
</ol>
<h3 id="heading-pros-of-standardjs">Pros of StandardJS</h3>
<ol>
<li>Zero configuration: No decisions to make. StandardJS is the easiest way to enforce code quality in your project.</li>
<li>Easy installation: StandardJS is easy to install, and you can use it with most editors and IDEs.</li>
<li>Enhances Productivity: StandardJS saves developers time and increases productivity by formatting code according to its rules.</li>
<li>Wide support: Most editors and IDEs support StandardJS using plugins and integrations.</li>
<li>Consistency: StandardJS promote consistency across projects by enforcing a strict set of coding rules.</li>
</ol>
<h3 id="heading-cons-of-standardjs">Cons of StandardJS</h3>
<ol>
<li>Opinionated: Some developers may find the tool too opinionated. If that's the case, you might prefer to use other linting tools that allow for more customization.</li>
<li>Limited flexibility: StandardJS enforces a strict set of rules and conventions, which some developers may feel restricted by and prefer a more customizable approach.</li>
</ol>
<h2 id="heading-eslint-editconfig-overview">ESLint + EditConfig Overview</h2>
<p><a target="_blank" href="https://eslint.org/">ESlint</a> provides configurable rules that you can tailor according to your specific project needs. It is one of the most popular JavaScript linter that analyzes programming errors, bugs, and suspicious constructs.</p>
<p>You can extend its functionality by adding plugins, which can provide custom parsers and extra rules.</p>
<p>You'll need Node installed on your before installing ESLint. To install it, use the command below:</p>
<pre><code>npm init @eslint/config
</code></pre><p>Alternatively, you can create this manually on your machine:</p>
<pre><code>npm install --save-dev eslint
</code></pre><p>For both installations, you need to have installed a package.json file. If not, run this command</p>
<pre><code>npx eslint --init
</code></pre><p>The command will ask a series of questions about your project, coding style, and preferences to generate your configuration file.</p>
<p>You can run ESLint on any of your directories or files with this command:</p>
<pre><code>npx eslint yourfile.js
</code></pre><p>Rules can be turned off and you can run the toolonly with basic syntax validation, as ESLint is configurable and flexible to your use case.</p>
<p>Once you have generated the configuration file, you can customize according to your needs. The configuration file is a JavaScript file that exports an object with the configuration settings.</p>
<p>For example, you can specify the rules you want, plugins to use, and environments for your code:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"rules"</span>: {
    <span class="hljs-attr">"semi"</span>: [<span class="hljs-string">"error"</span>, <span class="hljs-string">"always"</span>],
    <span class="hljs-attr">"quotes"</span>: [<span class="hljs-string">"error"</span>, <span class="hljs-string">"double"</span>],
    <span class="hljs-attr">"indent"</span>: [<span class="hljs-string">"error"</span>, <span class="hljs-number">4</span>]
  }
}
</code></pre>
<p>The semi, quotes, and indent are the names of the rules in ESLint, while the error level of the rule is the first value. There are only three outputs for the first values. They are:</p>
<ul>
<li>"off" or 0 - turn the rule off</li>
<li>"warn" or 1 - turn the rule on as a warning (doesn’t affect exit code)</li>
<li>"error" or 2 - turn the rule on as an error (exit code will be 1).</li>
</ul>
<pre><code class="lang-json">{
  <span class="hljs-attr">"env"</span>: {
    <span class="hljs-attr">"browser"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"es2021"</span>: <span class="hljs-literal">true</span>
  },
  <span class="hljs-attr">"extends"</span>: <span class="hljs-string">"eslint: recommended"</span>,
  <span class="hljs-attr">"overrides"</span>: [],
  <span class="hljs-attr">"parserOptions"</span>: {
    <span class="hljs-attr">"ecmaVersion"</span>: <span class="hljs-string">"latest"</span>
  },
  <span class="hljs-attr">"rules"</span>: {
    <span class="hljs-attr">"indent"</span>: [<span class="hljs-string">"error"</span>, <span class="hljs-number">4</span>],
    <span class="hljs-attr">"quotes"</span>: [<span class="hljs-string">"error"</span>, <span class="hljs-string">"single"</span>],
    <span class="hljs-attr">"semi"</span>: [<span class="hljs-string">"error"</span>, <span class="hljs-string">"never"</span>]
  }
}
</code></pre>
<p>In this example, you specify that your code should run in a browser environment. Enable ECMAScript 2018 syntax, and follow the ESLint rules. You've also enabled three specific rules: indent, quotes, and semi.</p>
<p>The indent rule determines that an alert error will be thrown if indentation is more than 4 spaces. Likewise if you use double-quotes instead of single, there will be an error. You also specified not to use semi-colons.</p>
<p>To fix most of the issues in ESLint, use this command:</p>
<pre><code>npx eslint yourfile.js --fix
</code></pre><p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>, <span class="hljs-number">78</span>, <span class="hljs-number">8</span>];
<span class="hljs-keyword">let</span> peoples = [<span class="hljs-string">"shola"</span>, <span class="hljs-string">"kamal"</span>];
<span class="hljs-built_in">console</span>.log(peoples);

<span class="hljs-comment">// The output</span>

 error  <span class="hljs-string">'numbers'</span> is assigned a value but never used  no-unused-vars
   error  Extra semicolon                               semi

✖ <span class="hljs-number">2</span> problems (<span class="hljs-number">2</span> errors, <span class="hljs-number">0</span> warnings)
  <span class="hljs-number">1</span> error and <span class="hljs-number">0</span> warnings potentially fixable <span class="hljs-keyword">with</span> the <span class="hljs-string">`--fix`</span> option.
</code></pre>
<h3 id="heading-editorconfig-overview">EditorConfig Overview</h3>
<p><a target="_blank" href="https://editorconfig.org/#file-format-details">EditorConfig</a> is an open-source file format. It provides standard ways of defining and maintaining coding styles in a project.</p>
<p>It maintains consistent coding styles which is especially useful when you have many developers working on the same project across various editors and IDEs. The tool consists of a collection of text editor plugins that enable editors to read the file format and adhere to defined styles.</p>
<p>You'll need to create a file named .editorconfig in the directory. EditorConfig plugins will look for the file in the directory of the opened file and on every parent directory.</p>
<p>Files are read from top to bottom, and a search for .editorconfig files will stop if the root file path is reached.</p>
<p>Creating an EditorConfig file is straightforward. Open a new file, and save it with .editorconfig as shown below.</p>
<p><img src="https://i.imgur.com/SHEafBl.png" alt="editorconfig file" width="237" height="34" loading="lazy"></p>
<p>Inside the .editorconfig file, the following wildcard patterns are used:</p>
<pre><code class="lang-javascript">root = <span class="hljs-literal">true</span>

[*]

indent_size = <span class="hljs-number">4</span>
indent_style = space
end_of_line = lf
insert_final_newline = <span class="hljs-literal">true</span>

 <span class="hljs-comment">// Set root to true: A search for .editorconfig files will stop if the root file path is reached or an EditorConfig file with root=true is found.</span>

 <span class="hljs-comment">//[*]: Except for path selectors, it matches any string of characters.</span>

 <span class="hljs-comment">//indent_size: Indent size is set to 4. </span>
 <span class="hljs-comment">//Indent_style: set to space</span>
 <span class="hljs-comment">//end_of_line: Set to lf</span>
<span class="hljs-comment">//insert_final_newline: Set to true</span>
</code></pre>
<p>To know more about the wildcards pattern, visit the <a target="_blank" href="https://editorconfig.org/#file-format-details">EditorConfig docs</a>.</p>
<p>Using ESLint and EditorConfig together can help to spot potential issues early. It also ensures that your code is consistent, maintainable, and of high quality.</p>
<p>The combination of ESLint and EDitorConfig saves you time on code maintenance and debugging.</p>
<h3 id="heading-features-of-eslint">Features of ESLint</h3>
<ol>
<li>Configurable: ESLint allows you to customize and add your own rules to the configuration file.</li>
<li>Support ECMAScript: ESLint ensures your code is compatible with the latest language features.</li>
<li>Supports many file formats: ESLint can analyze JavaScript code in a variety of file formats, including but not limited to .js, .jsx, and .vue.</li>
<li>Integration: ESLint integrates seamlessly with Webpack and Gulp, which are popular build tools.</li>
</ol>
<h3 id="heading-eslint-formatting-rules">ESLint Formatting Rules</h3>
<p>Some of the popular formatting rules in ESLint are listed below:</p>
<ol>
<li>Indentation: ESLint by default expects a four-space per level indent. But you can customize this using the popular <code>--fix</code> option.</li>
<li>Semicolons: ESLint enforces the use of semicolons at the end of each statement. This rule is set to "always" by default. Use the popular <code>--fix</code> option to reset it to "never".</li>
<li>Line wrap: Use the <code>max-len</code> rule to change the maximum line length from the default 80 to your preferred  value.</li>
<li>Quotes: The quotes rule can be changed from the default value of "single" to "double" using the <code>--fix</code> option.</li>
</ol>
<h3 id="heading-pros-of-eslint">Pros of ESLint</h3>
<ol>
<li>Saves time: ESLint saves time by reducing the amount of time spent on manual code reviews and debugging.</li>
<li>Active Community: ESLint has a wide and active community base that contributes to the development of the tool and its ecosystem.</li>
<li>Code analyzer: ESLint analyze your code to quickly find problems.</li>
<li>Consistency: ESLint helps in maintaining clean and readable code by enforcing a consistent coding style.</li>
</ol>
<h3 id="heading-cons-of-eslint">Cons of ESLint</h3>
<ol>
<li>Rule conflicts: With a large set of rules, ESLint rules can sometimes conflict with one another, resulting in more configuration and fine-tuning.</li>
<li>Steeper learning curve: ESLint has a pretty steep learning curve, as it has many rules and learning how to configure them can take time.</li>
<li>False positives: ESLint can sometimes flag code as problematic code even when it is correct, which can be frustrating for developers.</li>
</ol>
<h2 id="heading-overview-of-js-beautifier">Overview of JS Beautifier</h2>
<p><a target="_blank" href="https://beautifier.io/">JavaScript Beautifier</a>, also known as js-beautify, is an open-source, cross-platform command-line tool. It is a beautifier for re-formating and re-indenting bookmarklets, ugly JavaScript, and it partly deobfuscates scripts.</p>
<p>You can install JS beautifier both locally and globally.</p>
<p>Run <code>npm -g install js-beautify</code> to install globally, and <code>npm install js-beautify</code> to install locally.</p>
<p>You can configure it through the command line option.</p>
<p>After local installation, you can import and call the appropriate beautifier methods for JS, CSS, or HTML. An example of how to call the methods goes like this: beautify (<code>code</code>, <code>options</code>).</p>
<p>While <code>code</code> is the string of code to be beautified, <code>options</code> is an object with the settings you would like used to beautify the code. See the example below for a JavaScript script file:</p>
<pre><code>npx beautify(<span class="hljs-string">"script.js"</span>,{<span class="hljs-attr">indent_size</span>:<span class="hljs-number">4</span>})
</code></pre><p>You can also configure it through a configuration file:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"indent_size"</span>: <span class="hljs-number">4</span>,
  <span class="hljs-attr">"indent_char"</span>: <span class="hljs-string">" "</span>,
  <span class="hljs-attr">"indent_with_tabs"</span>: <span class="hljs-literal">false</span>,
  <span class="hljs-attr">"brace_style"</span>: <span class="hljs-string">"collapse"</span>
}
</code></pre>
<p>Create a file <code>.jsbeautifyrc</code> in the root directory of your project. This option will override the default option of JS beautifier. You can also use Beautifier on your web browser. Learn more about <a target="_blank" href="https://www.npmjs.com/package/js-beautify">JSbeautifer from its docs here</a>.</p>
<h3 id="heading-feature-of-js-beautifier">Feature of JS Beautifier</h3>
<ol>
<li>Formatting: You can customize JS Beautifier to fit your personal preferences and coding style because it offers varieties of formatting options, such as indentation size and braces style.</li>
<li>Online version: You can beautify JavaScript using JS Beautifier in your web browser, just as you can on the command line.</li>
</ol>
<h3 id="heading-js-beautifier-formatting-rules">JS Beautifier Formatting Rules</h3>
<ol>
<li>Indentation: The default identation in JS Beautifier is 4 spaces, but you can change it to 2 or 8 spaces, or use tabs instead. Use the <code>indent_size</code> option to specify the number of spaces to use for indentation.</li>
<li>Semicolons: You can change your semicolon settings in JS Beautifier with the <code>semicolon</code> option. You change this by alternating the value of the semicolon option between "true" or "false".</li>
<li>Line wrap: Use the <code>max_char</code> option to limit each line to 80 characters. You can set the value of the max_char to 80 or any other preferred  number.</li>
</ol>
<h3 id="heading-pros-of-js-beautifier">Pros of JS Beautifier</h3>
<ol>
<li>Time-saving: JS Beautifier saves time. It automates the many steps of formatting and organizing code.</li>
<li>Online presence: JS Beautifier's online presence is a game changer, as a lot of non-developers will be able to use it.</li>
<li>Detects errors: JS Beautifier helps catch small errors that can be difficult to spot otherwise.</li>
<li>Integration: JS Beautifier's compatibility with varieties of code editors and IDEs makes it a versatile tool.</li>
</ol>
<h3 id="heading-cons-of-js-beautifier">Cons of JS Beautifier</h3>
<ol>
<li>Complexity: Despite having an online version, JS Beautifier is somewhat complex for beginners.</li>
<li>Potential for over-formatting: In some cases, JS Beautifier may make the code harder to read because of over-formatting.</li>
</ol>
<h2 id="heading-results-from-all-the-formatting-tools">Results from all the Formatting Tools</h2>
<p>We'll use the code sample below to test how these four popular tools format code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">7</span>]

          <span class="hljs-keyword">let</span> peoples = [<span class="hljs-string">'kamal'</span>, <span class="hljs-string">'lawal'</span>, <span class="hljs-string">"shola"</span>, <span class="hljs-string">"olaide"</span>];
</code></pre>
<p>As you can see, this code isn't properly formatted. So let's try the tools to see how they help.</p>
<h3 id="heading-formatting-example-with-jsfmt">Formatting example with JsFmt</h3>
<p>Using the above code as a sample, the command <code>npx jsfmt --write "Your file"</code> will format the code to this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">7</span>]

<span class="hljs-keyword">let</span> peoples = [<span class="hljs-string">'kamal'</span>, <span class="hljs-string">'lawal'</span>, <span class="hljs-string">"shola"</span>, <span class="hljs-string">"olaide"</span>];
</code></pre>
<p>As you can see, there is a noticeable change in the code, and you can configure this to your desired taste.</p>
<h3 id="heading-formatting-example-with-standardjs">Formatting example with StandardJS</h3>
<p>By running the popular <code>npx standard--fix</code> command from the terminal, you will have the following result.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">7</span>]

<span class="hljs-keyword">const</span> peoples = [<span class="hljs-string">'kamal'</span>, <span class="hljs-string">'lawal'</span>, <span class="hljs-string">'shola'</span>, <span class="hljs-string">'olaide'</span>]
</code></pre>
<p>Notice the code was properly formatted, most especially the elements with double quotes within the <code>peoples</code> array.</p>
<h3 id="heading-formatting-example-with-eslint">Formatting example with ESLint</h3>
<p>Using the same code as above, the <code>npx eslint "Your file name --fix"</code> command will quickly format to this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">7</span>]

<span class="hljs-keyword">let</span> peoples = [<span class="hljs-string">'kamal'</span>,<span class="hljs-string">'lawal'</span>,<span class="hljs-string">'shola'</span>,<span class="hljs-string">'olaide'</span>]
</code></pre>
<p>You can also change the configuration of the tool, by changing the elements of the <code>peoples</code> array so they're inside double quotes:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">7</span>]

<span class="hljs-keyword">let</span> peoples = [<span class="hljs-string">"kamal"</span>,<span class="hljs-string">"lawal"</span>,<span class="hljs-string">"shola"</span>,<span class="hljs-string">"olaide"</span>];
</code></pre>
<p>You can do this by going to the .eslintrc file and manipulating the rules like this:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"quotes"</span>: [<span class="hljs-string">"error"</span>, <span class="hljs-string">"double"</span>],
  <span class="hljs-attr">"semi"</span>: [<span class="hljs-string">"off"</span>, <span class="hljs-string">"always"</span>]
}
</code></pre>
<h3 id="heading-formatting-example-with-js-beautifier">Formatting example with JS Beautifier</h3>
<p>Here's the result from JS Beautifier for the same code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">7</span>]
<span class="hljs-keyword">let</span> peoples = [<span class="hljs-string">'kamal'</span>, <span class="hljs-string">'lawal'</span>, <span class="hljs-string">"shola"</span>, <span class="hljs-string">"olaide"</span>];
</code></pre>
<p>You can configure it more from your JSON file if you wish.</p>
<p>Now you've seen these formatters in action!</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this guide, we talked about some alternatives to using Prettier. We discussed Jsfmt, ESlint, StandardJS, and JS Beautifier, as well as their features, pros, and cons.</p>
<p>I hope you are now more equipped to choose the right linter/formatter for your coding projects.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Set and Map in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ There are three major iterables available in JavaScript: Arrays, Maps, and Sets.  In this article, we will cover the following topics:  What is an Array? What is a Set? What is a Map? How to Create a Seta. How to Create a Set with a Value Properties... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/set-and-map-in-javascript/</link>
                <guid isPermaLink="false">66d0396c15ea3036a9539978</guid>
                
                    <category>
                        <![CDATA[ data structures ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kamaldeen Lawal ]]>
                </dc:creator>
                <pubDate>Fri, 10 Feb 2023 15:29:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/kamaldeenlawal94@gmail.com--1-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>There are three major iterables available in JavaScript: Arrays, Maps, and Sets. </p>
<p>In this article, we will cover the following topics: </p>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-an-array">What is an Array?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-set">What is a Set?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-a-map">What is a Map?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-set">How to Create a Set</a><br>a. <a class="post-section-overview" href="#heading-how-to-create-a-set-with-a-value">How to Create a Set with a Value</a></li>
<li><a class="post-section-overview" href="#heading-properties-and-methods-of-a-set">Properties and Methods of a Set</a><br>a. <a class="post-section-overview" href="#heading-how-to-use-the-add-method-in-a-set">How to use the <code>add</code> method in a set</a><br>b. <a class="post-section-overview" href="#heading-how-to-use-the-has-method-in-a-set">How to use the <code>has</code> method in a set</a><br>c. <a class="post-section-overview" href="#heading-how-to-use-the-delete-method-in-a-set">How to use the <code>delete</code> method in a set</a><br>d. <a class="post-section-overview" href="#heading-how-to-use-the-clear-method-in-a-set">How to use the <code>clear</code> method in a set</a><br>e. <a class="post-section-overview" href="#heading-how-to-use-the-entries-method-in-a-set">How to use the <code>entries</code> method in a set</a><br>f. <a class="post-section-overview" href="#heading-how-to-use-the-values-method-in-a-set">How to use the <code>values</code> method in a set</a><br>g. <a class="post-section-overview" href="#heading-how-to-use-the-size-property-in-a-set">How to use the <code>size</code> property in a set</a><br>h. <a class="post-section-overview" href="#heading-how-to-use-foreach-in-a-set">How to use <code>forEach</code> in a set</a><br>i. <a class="post-section-overview" href="#heading-how-to-use-a-set-to-get-unique-value-from-an-array">How to use a set to Get Unique Value from an Array.</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-a-map">How to Create a Map</a></li>
<li><a class="post-section-overview" href="#heading-properties-and-methods-of-map">Properties and Methods of Map</a><br>a. <a class="post-section-overview" href="#heading-how-to-get-values-from-the-map-object">How to Get Values from the Map Object</a><br>b. <a class="post-section-overview" href="#heading-how-to-add-data-with-the-set-method">How to Add Data with the <code>set</code> Method</a><br>c. <a class="post-section-overview" href="#heading-how-to-search-an-element-with-the-has-method">How to Search an Element with the <code>has</code> Method</a><br>d. <a class="post-section-overview" href="#heading-how-to-delete-an-element-with-the-delete-method">How to Delete an Element with the <code>delete</code> Method</a><br>e. <a class="post-section-overview" href="#heading-how-to-clear-all-elements-with-the-clear-method">How to Clear All Elements with the <code>clear</code> Method</a><br>f. <a class="post-section-overview" href="#heading-how-to-get-all-entries-in-a-map-with-the-entries-method">How to get all Entries in a Map with the <code>entries</code> Method</a><br>g. <a class="post-section-overview" href="#heading-how-to-get-all-keys-in-a-map-with-the-keys-method">How to Get All Keys in a Map with the <code>keys</code> Method</a><br>h. <a class="post-section-overview" href="#heading-how-to-get-all-values-in-a-map-with-the-values-method">How to Get All Values in a Map with the <code>values</code> Method</a><br>i. <a class="post-section-overview" href="#heading-how-to-enumerate-over-a-map">How to Enumerate Over a Map</a><br>j. <a class="post-section-overview" href="#heading-how-to-use-size-property-in-map">How to Use Size Property in Map</a></li>
<li><a class="post-section-overview" href="#heading-map-vs-object-whats-the-difference">Map vs Object – What's the Difference?</a></li>
<li><a class="post-section-overview" href="#heading-benefits-of-sets-over-arrays">Benefits of Sets over Arrays</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-is-an-array">What is an Array?</h2>
<p>An <strong>array</strong> is the most important and most commonly used iterable among the trio. We use it to store lists and connected data of any kind and length. </p>
<p>Arrays have a lot of special array methods. They also have zero-based indexing for accessing elements. You can have duplicate elements in an array, and the element order is guaranteed.</p>
<h2 id="heading-what-is-a-set">What is a Set?</h2>
<p>A <strong>set</strong> is a data structure used for storing data of any length and kind. Sets are iterables that have various special methods that are different from arrays. </p>
<p>Some of the characteristics of sets are that the order of elements is not guaranteed, you can't access elements by index, and you can't have duplicate elements. Sets are a great choice when you want to store data without duplicates.</p>
<h2 id="heading-what-is-a-map">What is a Map?</h2>
<p>A <strong>map</strong> is another data structure/container used to store key-value pairs of data of any kind and length. </p>
<p>Maps are similar to objects, but with maps, you can use anything as a key. An object, on the other hand, takes strings, symbols, and numbers as keys. </p>
<p>Maps are iterables and come with various methods. Some of the features of maps are that the order is guaranteed, and values can be duplicated (but keys can't).</p>
<p>Now we'll learn more about each of these iterables so you understand how to use them.</p>
<h2 id="heading-how-to-create-a-set">How to Create a Set</h2>
<p>Since we use sets to create unique values, an ID is a perfect example of something to create with a set. We can create a new set like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> ids = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>();
</code></pre>
<p>To create a set, you start with the <code>new</code> keyword along with <code>set</code>. In the above code, we created a set of ids which returns an empty set.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Set</span>(<span class="hljs-number">0</span>) {<span class="hljs-attr">size</span>: <span class="hljs-number">0</span>}
</code></pre>
<h3 id="heading-how-to-create-a-set-with-a-value">How to Create a Set with a Value</h3>
<p>You initialize the set with an iterable by creating a set with some initial value. An iterable such as an array, set, or nodelist can be passed to the set. The example below shows a set created from an array of 4 elements.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> ids = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-number">3</span>,<span class="hljs-number">6</span>,<span class="hljs-number">9</span>,<span class="hljs-number">7</span>]);
<span class="hljs-built_in">console</span>.log(ids);
</code></pre>
<p>The output will be like this:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Set</span>(<span class="hljs-number">4</span>) {<span class="hljs-number">3</span>,<span class="hljs-number">6</span>,<span class="hljs-number">9</span>,<span class="hljs-number">7</span>}
</code></pre>
<p>From the result, the code returns a set with 4 elements.</p>
<h2 id="heading-properties-and-methods-of-a-set">Properties and Methods of a Set</h2>
<p><strong>Sets</strong> have several methods and a properties that you can use to retrieve, add, delete, check, and clear all the elements in the set. We will talk about all these methods and properties, and how to use them while working with the set.</p>
<h3 id="heading-how-to-use-the-add-method-in-a-set">How to use the <code>add</code> method in a set</h3>
<p>We use the <code>add</code> method to add elements to the set. Create a set of fruits with 4 elements, it works like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruits = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-string">'apple'</span>.<span class="hljs-string">'mango'</span>]);
fruits.add(<span class="hljs-string">'banana'</span>);
<span class="hljs-built_in">console</span>.log(fruits)
</code></pre>
<p>From the above code, banana was added to the set with the help of the add method which gives us this result:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Set</span>(<span class="hljs-number">3</span>) {<span class="hljs-string">'apple'</span>. <span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span>}
</code></pre>
<p>Sets store unique elements, which means that adding another banana to the set won’t be accepted.</p>
<h3 id="heading-how-to-use-the-has-method-in-a-set">How to use the <code>has</code> method in a set</h3>
<p>To check if an element is contained in a set, you'll use the <code>has</code> method. In the code below, we'll check if a fruit set with various elements contained a specific <code>banana</code> element.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruits = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-string">'apple'</span>,<span class="hljs-string">'mango'</span>]);
<span class="hljs-built_in">console</span>.log(fruits.has(<span class="hljs-string">'banana'</span>));
</code></pre>
<p>This method will return false, because the element searched for is banana, which is not in the set. If it had been present, we would've gotten true back.</p>
<h3 id="heading-how-to-use-the-delete-method-in-a-set">How to use the <code>delete</code> method in a set</h3>
<p>You delete an item from a set using the "delete" method. The example below shows the "delete" method being used on a set of fruits containing 3 elements to delete one of the elements.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruits = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-string">'apple'</span>,<span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span>]);
fruits.delete(<span class="hljs-string">'apple'</span>);
<span class="hljs-built_in">console</span>.log(fruits);
</code></pre>
<p>The code prints out a new set of 2 elemets. If you try deleting an element that is not in the set, it ignores it.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Set</span>(<span class="hljs-number">2</span>) {<span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span>};
</code></pre>
<h3 id="heading-how-to-use-the-clear-method-in-a-set">How to use the <code>clear</code> method in a set</h3>
<p>The clear method is used to clear all the elements in the set. With a set of fruits containing 3 elements, we use the delete method to delete one of the elements.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruits = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-string">'apple'</span>,<span class="hljs-string">'mango'</span>, <span class="hljs-string">'banana'</span>]);
fruits.clear(<span class="hljs-string">'apple'</span>);
<span class="hljs-built_in">console</span>.log(fruits);
</code></pre>
<p>The code prints out a new set of 0 elements, as the clear method will return a set without any elements.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Set</span>(<span class="hljs-number">0</span>) {<span class="hljs-attr">size</span> : <span class="hljs-number">0</span>};
</code></pre>
<h3 id="heading-how-to-use-the-entries-method-in-a-set">How to use the <code>entries</code> method in a set</h3>
<p>You can retrieve all elements in a set using the "entries" method, which returns an iterable. You can then use a for loop or for-of loop to loop through the values. </p>
<p>The example below shows the creation of a set of fruits containing 5 elements, followed by the use of the "entries" method to loop through all elements of the array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruits = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-number">100</span>,<span class="hljs-number">160</span>, <span class="hljs-number">200</span>,<span class="hljs-number">400</span>,<span class="hljs-number">300</span>]);
<span class="hljs-keyword">for</span>( <span class="hljs-keyword">const</span> fruit <span class="hljs-keyword">of</span> fruits.entries()){
    <span class="hljs-built_in">console</span>.log(fruit);
}
</code></pre>
<p>It returns an iterable of arrays, each with two elements.</p>
<pre><code class="lang-javascript">(<span class="hljs-number">2</span>) {<span class="hljs-number">100</span>, <span class="hljs-number">100</span>}
(<span class="hljs-number">2</span>) {<span class="hljs-number">160</span>, <span class="hljs-number">160</span>}
(<span class="hljs-number">2</span>) {<span class="hljs-number">200</span>, <span class="hljs-number">200</span>}
(<span class="hljs-number">2</span>) {<span class="hljs-number">400</span>, <span class="hljs-number">400</span>}
(<span class="hljs-number">2</span>) {<span class="hljs-number">300</span>, <span class="hljs-number">300</span>}
</code></pre>
<h3 id="heading-how-to-use-the-values-method-in-a-set">How to use the <code>values</code> method in a set</h3>
<p>You retrieve the values in a set by using the "values" method, which returns an iterable. You can then use a for loop or for-of loop to loop through the values. </p>
<p>The example below shows the creation of a set of fruits with 4 elements and the use of the "values" method to loop through the elements with a for-of loop.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruits = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-number">100</span>,<span class="hljs-number">160</span>, <span class="hljs-number">200</span>,<span class="hljs-number">300</span>]);
<span class="hljs-keyword">for</span>( <span class="hljs-keyword">const</span> fruit <span class="hljs-keyword">of</span> fruits.values()){
    <span class="hljs-built_in">console</span>.log(fruit);
}
</code></pre>
<p>It returns an iterable, each with a single value:</p>
<pre><code class="lang-javascript"><span class="hljs-number">100</span>
<span class="hljs-number">160</span>
<span class="hljs-number">200</span>
<span class="hljs-number">300</span>
</code></pre>
<h3 id="heading-how-to-use-the-size-property-in-a-set">How to use the <code>size</code> property in a set</h3>
<p>You use the <code>size</code> property to determine the size of the set by returning the number of elements in it. To demonstrate this, we'll create a set of fruits that contains 3 elements.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruits = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-string">'apple'</span>,<span class="hljs-string">'mango'</span>,<span class="hljs-string">'banana'</span>]);
<span class="hljs-built_in">console</span>.log(fruits.size);
</code></pre>
<p>The above code will return 3 as the size of the fruit set.</p>
<pre><code class="lang-javascript"><span class="hljs-number">3</span>
</code></pre>
<h3 id="heading-how-to-use-foreach-in-a-set">How to use <code>forEach</code> in a set</h3>
<p>You can easily enumerate a set by using "forEach." The example below shows the creation of a set of fruits with some elements, followed by the use of "forEach" to print each element of the set.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruits = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>([<span class="hljs-number">100</span>,<span class="hljs-number">160</span>, <span class="hljs-number">200</span>,<span class="hljs-number">400</span>,<span class="hljs-number">300</span>]);
fruits.forEach(<span class="hljs-function">(<span class="hljs-params">fruit</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(fruit)
});
</code></pre>
<p>The code prints each element of the set like this:</p>
<pre><code class="lang-javascript"><span class="hljs-number">100</span>
<span class="hljs-number">160</span>
<span class="hljs-number">200</span>
<span class="hljs-number">400</span>
<span class="hljs-number">300</span>
</code></pre>
<h3 id="heading-how-to-use-a-set-to-get-unique-value-from-an-array">How to use a set to Get Unique Value from an Array.</h3>
<p>You can remove duplicate values from an array by using a set. The example below shows the creation of an array of duplicated numbers, followed by passing the array into a set to get all unique numbers, free from duplicates.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">1</span>,<span class="hljs-number">6</span>,<span class="hljs-number">8</span>,<span class="hljs-number">2</span>,<span class="hljs-number">5</span>,<span class="hljs-number">9</span>,<span class="hljs-number">2</span>,<span class="hljs-number">0</span>,<span class="hljs-number">9</span>,<span class="hljs-number">7</span>,<span class="hljs-number">6</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>,<span class="hljs-number">6</span>,<span class="hljs-number">7</span>,<span class="hljs-number">8</span>,<span class="hljs-number">4</span>,<span class="hljs-number">2</span>,<span class="hljs-number">1</span>,<span class="hljs-number">5</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">0</span>,<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>,<span class="hljs-number">3</span>,<span class="hljs-number">2</span>,<span class="hljs-number">6</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">6</span>];

<span class="hljs-keyword">const</span> numbers1 = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Set</span>(numbers);
<span class="hljs-built_in">console</span>.log(numbers1);
</code></pre>
<p>The above code shows an array of numbers with different duplicated numbers. The array was then passed on to the set of numbers and the output is shown below.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Set</span>(<span class="hljs-number">10</span>) {<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">6</span>,<span class="hljs-number">8</span>,<span class="hljs-number">5</span>,<span class="hljs-number">9</span>,<span class="hljs-number">0</span>,<span class="hljs-number">7</span>,<span class="hljs-number">3</span>};
</code></pre>
<p>The code above shows that the set has removed all the duplicated numbers and now has a size of 10.</p>
<p>As you can see, set is a data structure that helps you manage unique values.</p>
<h2 id="heading-how-to-create-a-map">How to Create a Map</h2>
<p>You create a map by starting with the "new" keyword followed by "map." The example below shows the creation of a map of a player, which returns an empty map. You can create a new map like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> player = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();
<span class="hljs-built_in">console</span>.log(player);
</code></pre>
<p>And it returns a map with an empty value.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Map</span>(<span class="hljs-number">0</span>) {<span class="hljs-attr">size</span> : <span class="hljs-number">0</span>}
</code></pre>
<p>You can also create a map using a constructor initialized with an array of arrays. Each array in the array is one key-value pair, and the key can be of any type. The example below shows the creation of a map of two arrays using the constructor.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> player = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[<span class="hljs-string">'key'</span>,<span class="hljs-string">'value'</span>],[<span class="hljs-string">'lawal'</span>,<span class="hljs-string">'kamal'</span>]]);
<span class="hljs-built_in">console</span>.log(player);
</code></pre>
<p>The above code returns a map with two elements:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Map</span>(<span class="hljs-number">2</span>) { <span class="hljs-string">'key'</span> =&gt; <span class="hljs-string">'value'</span>, <span class="hljs-string">'lawal'</span> =&gt; <span class="hljs-string">'kamal'</span>}
</code></pre>
<p><code>key</code> and <code>lawal</code> are the keys of the map, while <code>value</code> and <code>kamal</code> are the values.</p>
<h2 id="heading-properties-and-methods-of-map">Properties and Methods of Map</h2>
<p><strong>Map</strong> has several methods and properties that we can use to retrieve, add, delete, search, and clear all the elements in the map. </p>
<p>We will talk about all these methods and properties, and how to use them while working with map.</p>
<h3 id="heading-how-to-get-values-from-the-map-object">How to Get Values from the Map Object</h3>
<p>Extracting data from map is easy using the get method. Let's create an object of player1 with name and age properties. Then, the player1 object will be use as key in map. It works like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> player1 = { <span class="hljs-attr">name</span>: <span class="hljs-string">'kamal'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">30</span>};

<span class="hljs-keyword">const</span> playerData = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[player1, [{<span class="hljs-attr">date</span>:<span class="hljs-string">'today'</span>,<span class="hljs-attr">price</span> :<span class="hljs-number">400</span>}]]]);
 <span class="hljs-built_in">console</span>.log(playerData);
</code></pre>
<p>In the above code, you can see that we used the <code>player1</code> object as a key in a Map in playerData. By using the get method, you can extract values from the player1 used as a key in the Map.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Map</span>(<span class="hljs-number">1</span>)
</code></pre>
<p>It returns a map of size 1. The map contains a key which is the player1 that we created above.</p>
<pre><code class="lang-javascript">key :{ <span class="hljs-attr">name</span> : <span class="hljs-string">'kamal'</span>, <span class="hljs-attr">age</span> : <span class="hljs-number">30</span>}
</code></pre>
<p>And it returns a value, which was an array of a single object that contains a date and price.</p>
<pre><code class="lang-javascript"><span class="hljs-number">0</span>: {<span class="hljs-attr">date</span>:<span class="hljs-string">'today'</span>, <span class="hljs-attr">price</span>:<span class="hljs-number">400</span>}
</code></pre>
<h3 id="heading-how-to-add-data-with-the-set-method">How to Add Data with the <code>set</code> Method</h3>
<p>You can add data to the Map after you create it with the help of the set method as shown below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> player = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

player.set(<span class="hljs-string">'kamal'</span>,<span class="hljs-string">'lawal'</span>);

<span class="hljs-built_in">console</span>.log(player);
</code></pre>
<p>We added the key-value pair <code>kamal</code> and <code>lawal</code> to an empty map with the set method. The set method is where you set a key-value pair. The key has to be the first option and the value has to be the last. Both the key and values can be of any type of data.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Map</span>(<span class="hljs-number">1</span>) {<span class="hljs-string">'kamal'</span> =&gt; <span class="hljs-string">'lawal'</span>}
</code></pre>
<h3 id="heading-how-to-search-an-element-with-the-has-method">How to Search an Element with the <code>has</code> Method</h3>
<p>The <code>has</code> method returns true if the map contains keys that match the search term. We can create a map of <code>player</code> with two key-value pairs as shown below.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> player = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[<span class="hljs-string">'key'</span>,<span class="hljs-string">'value'</span>],[<span class="hljs-string">'small'</span>,<span class="hljs-string">'medium'</span>]]);

<span class="hljs-built_in">console</span>.log(player.has(<span class="hljs-string">'small'</span>));
</code></pre>
<p>The code will print true because the search term (<code>small</code>) is present in the map as a key.</p>
<pre><code class="lang-javascript"><span class="hljs-literal">true</span>
</code></pre>
<p>But it will print false if the search term (<code>medium</code>) is present in the map not as a key but as a value.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> player = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[<span class="hljs-string">'key'</span>,<span class="hljs-string">'value'</span>],[<span class="hljs-string">'small'</span>,<span class="hljs-string">'medium'</span>]]);

<span class="hljs-built_in">console</span>.log(player.has(<span class="hljs-string">'medium'</span>));

<span class="hljs-comment">// output will be false, the searched term, (medium) is not a key but value</span>
</code></pre>
<h3 id="heading-how-to-delete-an-element-with-the-delete-method"><strong>How to Delete an Element with the <code>delete</code> Method</strong></h3>
<p>We use the delete method to delete a specific element. Delete works if the searched term matches a key in an element. In this case, we're deleting <code>small</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> player = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[<span class="hljs-string">'key'</span>,<span class="hljs-string">'value'</span>],[<span class="hljs-string">'small'</span>,<span class="hljs-string">'medium'</span>]]);

player.delete(<span class="hljs-string">'small'</span>);

<span class="hljs-built_in">console</span>.log(player);
</code></pre>
<p>The code will delete the key-value pair of <code>small</code> and <code>medium</code>. But, it won't work if the search term is not a key in the map.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> player = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[<span class="hljs-string">'key'</span>,<span class="hljs-string">'value'</span>],[<span class="hljs-string">'small'</span>,<span class="hljs-string">'medium'</span>]]);

player.delete(<span class="hljs-string">'value'</span>);

<span class="hljs-built_in">console</span>.log(player);
<span class="hljs-comment">// It won't work, because the search term is a value in the map</span>
</code></pre>
<h3 id="heading-how-to-clear-all-elements-with-the-clear-method">How to Clear All Elements with the <code>clear</code> Method</h3>
<p>To clear all elements of a map, we'll use the clear method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> player = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[<span class="hljs-string">'key'</span>,<span class="hljs-string">'value'</span>],[<span class="hljs-string">'small'</span>,<span class="hljs-string">'medium'</span>]]);
player.clear();

<span class="hljs-built_in">console</span>.log(player);
</code></pre>
<p>The code will print an empty map as its output.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Map</span>(<span class="hljs-number">0</span>) { <span class="hljs-attr">size</span> : <span class="hljs-number">0</span>}
</code></pre>
<h3 id="heading-how-to-get-all-entries-in-a-map-with-the-entries-method">How to get all Entries in a Map with the <code>entries</code> Method</h3>
<p>The entries method is one of the Map methods you can use with for or for-of loops directly because it returns <code>MapIterator</code>. </p>
<h4 id="heading-what-is-a-mapiterator">What is a MapIterator?</h4>
<p>A MapIterator is an iterator returned by the <code>entries()</code> method of a JavaScript Map object. It returns an array-like object of key-value pairs, with each pair represented as an array containing 2 elements. The <code>MapIterator</code> can be used in a <code>for...of</code> loop to iterate over all key-value pairs in a Map object.</p>
<p>With <code>entries</code>, you can get all the data, both the key and value of a map.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> player = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[<span class="hljs-string">'key'</span>,<span class="hljs-string">'value'</span>],[<span class="hljs-string">'small'</span>,<span class="hljs-string">'medium'</span>],[<span class="hljs-string">'fruit'</span>,<span class="hljs-string">'another'</span>]]);

<span class="hljs-built_in">console</span>.log(player.entries());
</code></pre>
<p>The values of all the keys and values will be logged as shown below:</p>
<pre><code class="lang-javascript">MapIterator {<span class="hljs-string">'key'</span> =&gt; <span class="hljs-string">'value'</span>, <span class="hljs-string">'small'</span>=&gt; <span class="hljs-string">'medium'</span>, <span class="hljs-string">'fruit'</span> =&gt; <span class="hljs-string">'another'</span>}
</code></pre>
<h3 id="heading-how-to-get-all-keys-in-a-map-with-the-keys-method">How to Get All Keys in a Map with the <code>keys</code> Method</h3>
<p>Aside from the <code>entries</code> method, the <code>keys</code> method also returns a <code>MapIterator</code>. With the keys method, you can get all the keys of a map, and it also runs a for or for-of loop:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> players = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[<span class="hljs-string">'key'</span>,<span class="hljs-string">'value'</span>],[<span class="hljs-string">'small'</span>,<span class="hljs-string">'medium'</span>],[<span class="hljs-string">'fruit'</span>,<span class="hljs-string">'another'</span>]]);

<span class="hljs-keyword">for</span>(<span class="hljs-keyword">const</span> player <span class="hljs-keyword">of</span> players.keys()){
  <span class="hljs-built_in">console</span>.log(player);
}
</code></pre>
<p>This will print all the keys in the map as an output, like this:</p>
<pre><code class="lang-javascript">key
small
fruit
</code></pre>
<h3 id="heading-how-to-get-all-values-in-a-map-with-the-values-method">How to Get All Values in a Map with the <code>values</code> Method</h3>
<p>The <code>values</code> method is the last map method that returns a <code>MapIterator</code> and you can run a for or for-of loop directly on it. This is the method you should use when getting only values in the map is the priority.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> players = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[<span class="hljs-string">'key'</span>,<span class="hljs-string">'value'</span>],[<span class="hljs-string">'small'</span>,<span class="hljs-string">'medium'</span>],[<span class="hljs-string">'fruit'</span>,<span class="hljs-string">'another'</span>]]);

<span class="hljs-keyword">for</span>(<span class="hljs-keyword">const</span> player <span class="hljs-keyword">of</span> players.values()){
  <span class="hljs-built_in">console</span>.log(player);
}
</code></pre>
<p>The output of the above code will be this:</p>
<pre><code class="lang-javascript">value
medium
another
</code></pre>
<h3 id="heading-how-to-enumerate-over-a-map">How to Enumerate Over a Map</h3>
<p>For easy iteration in maps, you can use the popular <code>forEach</code> method as shown below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> players = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[<span class="hljs-string">'key'</span>,<span class="hljs-string">'value'</span>],[<span class="hljs-string">'small'</span>,<span class="hljs-string">'medium'</span>],[<span class="hljs-string">'fruit'</span>,<span class="hljs-string">'another'</span>]]);

players.forEach(<span class="hljs-function">(<span class="hljs-params">key, value</span>) =&gt;</span>{
  <span class="hljs-keyword">const</span> message = <span class="hljs-string">`I want to be remeembered as the best <span class="hljs-subst">${key}</span> pair <span class="hljs-subst">${value}</span>`</span>;
    <span class="hljs-built_in">console</span>.log(message)
})
</code></pre>
<p>The above code will print this as the output of the iteration:</p>
<pre><code class="lang-javascript">I want to be remembered <span class="hljs-keyword">as</span> the best value pair key
I want to be remembered <span class="hljs-keyword">as</span> the best medium pair small
I want to be remembered <span class="hljs-keyword">as</span> the best another pair fruit
</code></pre>
<h3 id="heading-how-to-use-size-property-in-map">How to Use Size Property in Map</h3>
<p>You can use the property size to determine the size of the map by returning the number of elements in it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> player = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>([[<span class="hljs-string">'key'</span>, <span class="hljs-string">'value'</span>],[<span class="hljs-string">'small'</span>,<span class="hljs-string">'medium'</span>],[<span class="hljs-string">'fruit'</span>,<span class="hljs-string">'another'</span>]]);

<span class="hljs-built_in">console</span>.log(player.size);
</code></pre>
<p>This will print out 3 as the size of the map.</p>
<h3 id="heading-map-vs-object-whats-the-difference">Map vs Object – What's the Difference?</h3>
<p>As you can see, a map is similar to an object which raises the question – when should you use each one?</p>
<p>When to use map:</p>
<ol>
<li>With map, you can use any type (and values) as keys.</li>
<li>Map provides better performance for large quantities of data.</li>
<li>Use a map for better performance when adding and removing data frequently.</li>
</ol>
<p>When to use an object:</p>
<ol>
<li>Objects can only use numbers, strings, and symbols as keys.</li>
<li>Objects are perfect for small to medium-sized sets of data.</li>
<li>Objects have better performance and are easier to create.</li>
</ol>
<h3 id="heading-benefits-of-sets-over-arrays">Benefits of Sets over Arrays</h3>
<p>Arrays and sets are both data structures used for storing collections of elements. But sets have a slight edge over arrays because of:</p>
<ul>
<li>Uniqueness: With a set, duplicates are removed to reduce the size of the data structure (unlike an array which stores duplicates).</li>
<li>Manipulating collections: It is easy to combine a set with other sets to perform various operations like intersections, unions, and differences.</li>
<li>Performance: Because of the implementation using hash tables, set offers faster lookups and membership tests.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you learned about the relationship between arrays, sets, and maps. </p>
<p>We created, modified, and deleted elements in maps and sets. We compared maps and objects, and lastly, we talked about the benefits of sets over arrays.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are Objects in JavaScript? ]]>
                </title>
                <description>
                    <![CDATA[ Objects are important data structures in JavaScript. This is partly because arrays are objects in JavaScript, and you'll use them all the time. Objects are super important for grouping data and functionalities, so you can do a lot with an object in J... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/objects-in-javascript/</link>
                <guid isPermaLink="false">66d0396964be048ac359a350</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kamaldeen Lawal ]]>
                </dc:creator>
                <pubDate>Wed, 08 Feb 2023 19:23:29 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/Your-paragraph-text.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Objects are important data structures in JavaScript. This is partly because arrays are objects in JavaScript, and you'll use them all the time.</p>
<p>Objects are super important for grouping data and functionalities, so you can do a lot with an object in JavaScript. The DOM node, and any DOM node created with <code>createElement</code> are examples of an object in JavaScript. </p>
<p>In this article, we will cover all the following about objects:</p>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-a-javascript-object">What is a JavaScript Object?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-an-object-in-javascript">How to Create an Object in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-how-to-add-properties-in-an-object">How to Add Properties in an Object</a></li>
<li><a class="post-section-overview" href="#heading-why-let-keyword-over-dot-notation">Why <code>let</code> Keyword Over dot Notation?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-modify-properties-in-an-object">How to Modify Properties in an Object</a></li>
<li><a class="post-section-overview" href="#heading-how-to-delete-properties-in-an-object">How to Delete Properties in an Object</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-special-keys-in-objects">How to Use Special Keys in Objects</a></li>
<li><a class="post-section-overview" href="#heading-how-to-access-properties-with-square-brackets">How to Access Properties with Square Brackets</a></li>
<li><a class="post-section-overview" href="#heading-how-to-dynamically-set-properties">How to Dynamically Set Properties</a></li>
<li><a class="post-section-overview" href="#heading-method-shorthand-syntax">Method Shorthand Syntax</a></li>
<li><a class="post-section-overview" href="#heading-advantages-of-using-object-short-methods-over-regular-methods">Advantages of Using Object Short Methods over Regular Methods.</a></li>
<li><a class="post-section-overview" href="#heading-object-spread-operator">Object Spread Operator</a></li>
<li><a class="post-section-overview" href="#heading-object-destructuring">Object Destructuring</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/p/f8c8e52f-7c90-4e0c-b2ac-0bb498e15fb3/How%20to%20Use%20the%20this%20Keyword%20in%20JavaScript">How to Use the <code>this</code> Keyword in JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-is-a-javascript-object">What is a JavaScript Object?</h2>
<p>Objects in everyday life have properties and “method” actions. Take, for instance, a fan. It's an object with properties such as make, color, or model, and actions it can perform such as cooling rooms and controlling humidity.</p>
<p>As explained above, objects in JavaScript are core data structures that comprise properties and methods. While methods are functions/actions an object can perform (such as driving and cooling rooms with real life objects like cars and fans), properties are characteristics of an object such as its name and value. </p>
<p>Objects let you group related data together and split code into logical pieces. In JavaScript, we have primitive values and reference values. Number, Boolean, Null, Undefined, String, and Symbol are primitive values, while objects like DOM nodes, Arrays, and so on are reference values.</p>
<p>In both real life and JavaScript, you can use objects in different ways depending on their properties and methods. We'll learn more about JavaScript objects now.</p>
<h2 id="heading-how-to-create-an-object-in-javascript">How to Create an Object in JavaScript</h2>
<p>We'll use the code below as an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">name</span>:<span class="hljs-string">'kamal'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  <span class="hljs-attr">friends</span>:[
     <span class="hljs-string">'Shola'</span>,<span class="hljs-string">'Ade'</span>,<span class="hljs-string">'Ibraheem'</span>
  ],
  <span class="hljs-attr">greet</span>:<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    alert(<span class="hljs-string">'Hello World'</span>)
  }
}
</code></pre>
<p>In the above code, we have a <code>person</code> object that we created with curly braces. The object has key-value pairs. You can store key-value pairs in a JavaScript object, associating each key with a unique value. </p>
<p>These key-value pairs allow you to retrieve values using the associated keys. For instance, the above object represents a person with properties like "name", "age"," friends", and a function "greet". Each property becomes a key-value pair with the property name as the key and the property value as the value. Both properties and methods are created inside the object.</p>
<p>To create a key in an object, you don't need a let or const keyword. Because objects are dynamic, you can add or change properties without declaring a variable. Rather, you start with your preferred name, a colon, and then your value. </p>
<p>We created an array of <code>friends</code> inside the object to show we can have an object inside of an object. We created a method (which is a function) inside of an object with <code>greet</code> as the key.</p>
<h3 id="heading-how-to-add-properties-in-an-object">How to Add Properties in an Object</h3>
<p>There are two major approaches to adding properties to an object in JavaScript. The first is to create a brand-new object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> person = {
  <span class="hljs-attr">name</span>:<span class="hljs-string">'kamal'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  <span class="hljs-attr">friends</span>:[
     <span class="hljs-string">'Shola'</span>,<span class="hljs-string">'Ade'</span>,<span class="hljs-string">'Ibraheem'</span>
  ],
  <span class="hljs-attr">greet</span>:<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    alert(<span class="hljs-string">'Hello World'</span>)
  }
}
 person = {
  <span class="hljs-attr">name</span>:<span class="hljs-string">'kamal'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  <span class="hljs-attr">friends</span>:[
     <span class="hljs-string">'Shola'</span>,<span class="hljs-string">'Ade'</span>,<span class="hljs-string">'Ibraheem'</span>
  ],
  <span class="hljs-attr">greet</span>:<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    alert(<span class="hljs-string">'Hello World'</span>)
  },
  <span class="hljs-attr">isAdmin</span>:<span class="hljs-literal">true</span>
}
</code></pre>
<p>With the above code, we created the first person object using the <code>let</code> keyword, allowing us to reassign it to a new value. We then added the "isAdmin" property to the person object. If you run <code>console.log(person)</code>, you will see that "isAdmin" is now part of the object's properties.</p>
<p>The second approach is to add properties using dot notation.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">name</span>:<span class="hljs-string">'kamal'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  <span class="hljs-attr">friends</span>:[
     <span class="hljs-string">'Shola'</span>,<span class="hljs-string">'Ade'</span>,<span class="hljs-string">'Ibraheem'</span>
  ],
  <span class="hljs-attr">greet</span>:<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    alert(<span class="hljs-string">'Hello World'</span>)
  }
}
person.isAdmin = <span class="hljs-literal">true</span>;
</code></pre>
<p>With dot notation, you can access properties that an object has not added before. For example, if the person object doesn't have an "isAdmin" property, accessing it will return "undefined". </p>
<p>You can add the "isAdmin" property to the person object using dot notation, and you can also overwrite any property by assigning a new value to it. This approach is shorter and simpler compared to other methods.</p>
<h3 id="heading-why-let-keyword-over-dot-notation">Why <code>let</code> Keyword Over dot Notation?</h3>
<p>The choice between using the <code>let</code> keyword and dot notation depends on whether you need to create a new object reference or modify an existing one.</p>
<p>You would use the <code>let</code> keyword to create a new object when you need to create a new reference to an object, separate from any existing references to similar objects. </p>
<p>On the other hand, you would use dot notation to add or modify properties on an existing object reference. This is useful when you want to make changes to an object without creating a new reference. </p>
<h3 id="heading-how-to-modify-properties-in-an-object">How to Modify Properties in an Object</h3>
<p>You can also use dot notation to modify properties in an object. The below code shows that the property <code>name</code> with the pair value <code>kamal</code> will be changed to <code>lawal</code> when modified using dot notation.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">name</span>:<span class="hljs-string">'kamal'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  <span class="hljs-attr">friends</span>:[
     <span class="hljs-string">'Shola'</span>,<span class="hljs-string">'Ade'</span>,<span class="hljs-string">'Ibraheem'</span>
  ],
  <span class="hljs-attr">greet</span>:<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    alert(<span class="hljs-string">'Hello World'</span>)
  }
}
person.isAdmin = <span class="hljs-literal">true</span>;
person.name = <span class="hljs-string">'lawal'</span>;
<span class="hljs-built_in">console</span>.log(person);
</code></pre>
<h3 id="heading-how-to-delete-properties-in-an-object">How to Delete Properties in an Object</h3>
<p>It is very simple to delete a property in an object. JavaScript has a special keyword called "<strong>delete</strong>" that allows you to discard any properties you wish.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">name</span>:<span class="hljs-string">'kamal'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  <span class="hljs-attr">friends</span>:[
     <span class="hljs-string">'Shola'</span>,<span class="hljs-string">'Ade'</span>,<span class="hljs-string">'Ibraheem'</span>
  ],
  <span class="hljs-attr">greet</span>:<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    alert(<span class="hljs-string">'Hello World'</span>)
  }
}
person.isAdmin = <span class="hljs-literal">true</span>;
<span class="hljs-keyword">delete</span> person.friends;
<span class="hljs-built_in">console</span>.log(person);
</code></pre>
<p>The property <code>friends</code> will be deleted from the object with the above code.</p>
<h3 id="heading-how-to-use-special-keys-in-objects">How to Use Special Keys in Objects</h3>
<p>You can use anything as a key name that you can use as a variable name. But not every key name can serve as a variable name because keys are more flexible than variables.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> person = {
 <span class="hljs-attr">name</span>:<span class="hljs-string">'kamal'</span>,
 <span class="hljs-attr">age</span>:<span class="hljs-number">37</span>,
}
</code></pre>
<p>Suppose you want to use "last name" as a key instead of "name". JavaScript syntax does not allow two separate words in this naming convention. </p>
<p>But you can overcome this by using a special key in an object. JavaScript automatically converts any key you enter into a string, even the key "age". As a result, objects in JavaScript are a dictionary of string keys and values of any type.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> person = {
  last name:<span class="hljs-string">'kamal'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  <span class="hljs-attr">friends</span>:[
     <span class="hljs-string">'Shola'</span>,<span class="hljs-string">'Ade'</span>,<span class="hljs-string">'Ibraheem'</span>
  ],
  <span class="hljs-attr">greet</span>:<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    alert(<span class="hljs-string">'Hello World'</span>)
  }
}
</code></pre>
<p>To use "last name" as a key in the above code, you need to inform JavaScript that it is a key by enclosing it in quotes, either single or double quotes will work. Using a name that can also be used as a variable is recommended instead of this exception method of setting a key.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> person = {
  <span class="hljs-string">'last name'</span>:<span class="hljs-string">'kamal'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  <span class="hljs-attr">friends</span>:[
     <span class="hljs-string">'Shola'</span>,<span class="hljs-string">'Ade'</span>,<span class="hljs-string">'Ibraheem'</span>
  ],
  <span class="hljs-attr">greet</span>:<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    alert(<span class="hljs-string">'Hello World'</span>)
  }
}
</code></pre>
<p>Using single quotes to surround "last name" and using it as a key name is valid JavaScript code and will work properly.</p>
<h3 id="heading-how-to-access-properties-with-square-brackets">How to Access Properties with Square Brackets</h3>
<p>To add and modify properties in an object, you can use the object notation method. However, there is another method in JavaScript for accessing object properties, known as square bracket notation, which enables you to access a property created by a <strong>special key</strong> in JavaScript.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> person = {
  <span class="hljs-string">'last name'</span>:<span class="hljs-string">'kamal'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  <span class="hljs-attr">friends</span>:[
     <span class="hljs-string">'Shola'</span>,<span class="hljs-string">'Ade'</span>,<span class="hljs-string">'Ibraheem'</span>
  ],
}
<span class="hljs-comment">// console.log(person.last name); is not valid in JavaScript</span>
</code></pre>
<p>You cannot access the key name 'last name' using the dot notation method, but you can use the square bracket notation, which is available for any object. </p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(person[<span class="hljs-string">'last name'</span>]);
</code></pre>
<p>The above code will display the value of the last name key which is <code>kamal</code>. However, it is crucial to enclose your key within single or double quotes.</p>
<h3 id="heading-how-to-dynamically-set-properties">How to Dynamically Set Properties</h3>
<p>You can enable another dynamic feature with square brackets and objects in JavaScript. This works when you need to define a new property, especially when you don't know the property name. </p>
<p>For example, you won't know specific user input ahead of time. But, you'll need to add the property with that name to the object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> userName =<span class="hljs-string">'level'</span>;

<span class="hljs-keyword">let</span> person = {
 <span class="hljs-string">'first name'</span>:<span class="hljs-string">'kamal'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  [userName]: <span class="hljs-string">'see'</span>,
}
<span class="hljs-built_in">console</span>.log(person);
</code></pre>
<p>By not wrapping the <strong>userName</strong> in a square bracket, the property with the name userName will be added instead of the value stored inside it. Adding a square bracket to the <strong>userName</strong> will search and take the value stored in the variable as a key name and add it to a person object.</p>
<h3 id="heading-method-shorthand-syntax">Method Shorthand Syntax</h3>
<p>There is an alternative syntax you can use to define a method in a more efficient way. Traditionally, to create a method in an object, you need a key and a value, where you create the value as a method using the function keyword.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> person = {
  <span class="hljs-attr">name</span>:<span class="hljs-string">'jamaldeen'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  <span class="hljs-attr">hobbies</span>:[
     <span class="hljs-string">'reading'</span>,<span class="hljs-string">'playing'</span>,<span class="hljs-string">'sleeping'</span>
  ],
  <span class="hljs-attr">speek</span>:<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.hobbies
  }
}
<span class="hljs-built_in">console</span>.log(person.speak());
</code></pre>
<p>In the above code, the method is created with a function keyword after a colon. Alternatively, you could do this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> person = {
  <span class="hljs-attr">name</span>:<span class="hljs-string">'jamaldeen'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  <span class="hljs-attr">hobbies</span>:[
     <span class="hljs-string">'reading'</span>,<span class="hljs-string">'playing'</span>,<span class="hljs-string">'sleeping'</span>
  ],
  speek(){
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.hobbies
  }
}
<span class="hljs-built_in">console</span>.log(person.speak());
</code></pre>
<p>In JavaScript, creating a method with object short methods is a shorthand notation. Omitting the "function" keyword and the colon(:) before the function body is allowed using the short methods. </p>
<p>This is because with the short method syntax, the property is automatically defined as method, which renders the "function" keyword useless. </p>
<p>The code remains functional because the JavaScript engine recognizes the shorthand syntax and interprets it as a regular function definition. </p>
<h3 id="heading-advantages-of-using-object-short-methods-over-regular-methods">Advantages of Using Object Short Methods over Regular Methods.</h3>
<p>Some of the advantages of using object short methods over regular methods are as follows</p>
<ol>
<li>Conciseness: Unlike regular methods, object short methods allow you to write more compact and readable code.</li>
<li>Improved performance: Although, the performance of both object short methods and regular are similar, but the shorter syntax makes it easier to write and maintain your code.</li>
<li>Reusability: You can easily reuse object short methods in other objects.</li>
<li>Better organization: With object short methods, you can easily group related methods within an object and keep your code organized.</li>
</ol>
<p>While using object short methods is good, using regular methods may still be more appropriate. It's important to choose the right approach based on your particular requirements.</p>
<h3 id="heading-object-spread-operator">Object Spread Operator</h3>
<p>The object spread operator is a popular and powerful syntax in JavaScript. The spread operator takes all the key-value pairs of an object and copies the key name and value into a new object. </p>
<p>An object is a reference value, and if you want a copy of the object without pointing to the same property in memory, the spread operator is the answer.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> person = {
  <span class="hljs-attr">name</span>:<span class="hljs-string">'kamal'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  <span class="hljs-attr">hobbies</span>:[
     <span class="hljs-string">'reading'</span>,<span class="hljs-string">'playing'</span>,<span class="hljs-string">'sleeping'</span>
  ]
}
<span class="hljs-built_in">console</span>.log(person);
<span class="hljs-keyword">const</span> person2 ={...person};
<span class="hljs-built_in">console</span>.log(person2.age);
</code></pre>
<p>The syntax for object spread operator goes between the opening and closing brackets. Then there should be three dots and the object you want to spread into this object.</p>
<h3 id="heading-object-destructuring">Object Destructuring</h3>
<p>Object destructuring is an important feature in JavaScript that allows you to pull out values from an object and assign them to individual variables. </p>
<p>To perform object destructuring, you use a destructuring pattern on the left-hand side of an assignment statement, and the object that you want to extract values from on the right-hand side. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = { <span class="hljs-attr">name</span>: <span class="hljs-string">'lawal'</span>, <span class="hljs-attr">age</span>: <span class="hljs-number">39</span> };
<span class="hljs-keyword">const</span> { person, age } = person;
<span class="hljs-built_in">console</span>.log(name); <span class="hljs-comment">// 'lawal'</span>
<span class="hljs-built_in">console</span>.log(age); <span class="hljs-comment">// 39</span>
</code></pre>
<p>The <code>const</code> statement uses object destructuring to extract the <code>name</code> and <code>age</code> properties from the <code>person</code> object and assign them to two separate variables. This is a concise and efficient way to extract values from an object, especially when dealing with complex objects.</p>
<p>Object destructuring also enables you to provide default values, in case the property you want to extract does not exist in the object. You can also rename the variables being extracted using an alias, giving you greater control over the structure and naming of the extracted values.</p>
<h2 id="heading-how-to-use-the-this-keyword-in-javascript">How to Use the <code>this</code> Keyword in JavaScript</h2>
<p>What is the <code>this</code> keyword? <code>this</code> is a specific keyword in JavaScript which is most important when used inside of a function in an object. But you can use it anywhere in your code aside from the function body of an object. </p>
<p><code>this</code> is a powerful keyword used in referencing the current object in which it's used. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> person = {
  <span class="hljs-attr">name</span>:<span class="hljs-string">'kamal'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  <span class="hljs-attr">greet</span>:<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">`My name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>, and my age is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old`</span>;
  },
}
<span class="hljs-built_in">console</span>.log(person.greet());
<span class="hljs-comment">// My name is kamal, and my age is 30 years old.</span>
</code></pre>
<p>The code above demonstrates that the "this" keyword refers to the object containing the function, in this case the "person" object, and the result displays the output of the "greet" function. </p>
<p>Regardless of its location within an object, the <code>this</code> keyword always refers to the entity that executed the function in the code. Using <code>this</code> in different contexts within the code can produce distinct results. For instance:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> person = {
  <span class="hljs-attr">name</span>:<span class="hljs-string">'kamal'</span>,
  <span class="hljs-attr">age</span>:<span class="hljs-number">30</span>,
  <span class="hljs-attr">greet</span>:<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">`My name is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>, and my age is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old`</span>;
  },
}
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
</code></pre>
<p>The output of the code shows that the <code>this</code> keyword when console.logged will print a window object.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, we learned about the JavaScript object, how to create an object, and how modify/delete properties in an object.</p>
<p>We briefly talked about how important the spread operator and object destructuring are in JavaScript object as well as the popular <code>this</code> keyword and how to use it in JavaScript objects.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
