<?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[ Austin Asoluka - 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[ Austin Asoluka - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 17 May 2026 22:27:52 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/sleekcodes/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Variables and Data Types in JavaScript – Explained With Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ A variable is like a box where you can store data or a reference to data. In this article, you will learn how to create and use variables. You'll also learn about the different data types in JavaScript and how to use them. Let's get started! Table of... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-variables-and-data-types-in-javascript/</link>
                <guid isPermaLink="false">66c3499e4f7405e6476b019b</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ variables ]]>
                    </category>
                
                    <category>
                        <![CDATA[ beginner ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Austin Asoluka ]]>
                </dc:creator>
                <pubDate>Mon, 19 Aug 2024 13:33:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1723754441356/34416215-e12b-41ec-8c11-332d2c8214e1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A variable is like a box where you can store data or a reference to data.</p>
<p>In this article, you will learn how to create and use variables. You'll also learn about the different data types in JavaScript and how to use them.</p>
<p>Let's get started!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-example-1">What is a Variable? Example #1</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-example-2">What is a Variable? Example #2</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-a-variable-example-3">What is a Variable? Example #3</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-declare-a-variable">How to Declare a Variable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-variable-assignment-and-initialization">Variable Assignment and Initialization</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-call-a-variable">How to Call a Variable</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-name-variables">How to Name Variables</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-reserved-words-in-javascript">Reserved Words in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-rules-for-naming-variables-in-javascript">Rules for Naming Variables in JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-popular-variable-naming-conventions">Popular Variable Naming Conventions</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-variable-data-types">Variable Data Types</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-primitive-data-types">Primitive Data Types</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-reference-types-in-javascript">Reference types in JavaScript</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ul>
<h3 id="heading-what-is-a-variable-example-1">What is a Variable? Example #1</h3>
<p>When a child is born, they are given a name and throughout their life, they'll be referred to b<a class="post-section-overview" href="#reference-types-in-javascript">y</a> that name (unless the name gets changed at some point).</p>
<p>Have you seen anyone without a name? How were you able to call them?<br>In an ideal world, everyone should have a name or a unique way we can refer to them. In JavaScript, every variable has a name.</p>
<blockquote>
<p>Everyone must have a name or a way by which we can refer to them.</p>
</blockquote>
<h3 id="heading-what-is-a-variable-example-2"><strong>What is a Variable? Example #2</strong></h3>
<p>In a math equation, when we say <code>x = 1</code> it means, "anywhere you see <code>x</code>, you should replace it with <code>1</code>". In this case, <code>x</code> is a variable, while <code>1</code> is the value of it. That is: <code>x</code> points to <code>1</code>.</p>
<p>This means that without <code>x</code>, there will be no reference to <code>1</code>. There could be other occurrences of <code>1</code> in the equation but those will be different than the <code>1</code> which <code>x</code> was referring to. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/* The code below means x is 1 
 * So during execution, anywhere x appears after the line below, 
 * the complier replace x with 1.
 */</span>
<span class="hljs-keyword">let</span> x = <span class="hljs-number">1</span>;
<span class="hljs-keyword">let</span> y = <span class="hljs-number">1</span>; <span class="hljs-comment">// the value which y refers to is different from that of x</span>
<span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// This line will log 1 to the console.</span>
</code></pre>
<p>In the code snippet above, <code>x</code> refers to the value 1, and <code>y</code> It also refers to another value 1, but note that both values are distinct, just like you can have two different brands of bottled water even though they both contain water.</p>
<p>So, when we mention the variable name <code>x</code>, we get the value assigned to that variable.</p>
<h3 id="heading-what-is-a-variable-example-3"><strong>What is a Variable? Example #3</strong></h3>
<p>A variable can be conceptualized as a container. The variable's name serves as its identifier, its value represents the container's contents, and its type specifies the nature of those contents.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1690903992237/a783721f-1fbc-4c84-8df6-24a49e7dddb3.jpeg" alt="Bottle of water" class="image--center mx-auto" width="1280" height="851" loading="lazy"></p>
<p>A popular water brand here in Nigeria is known as "Eva".</p>
<p>Let's say you bought Eva water, took it home, and placed it amongst other water brands. You can easily say to someone, "Please get me the Eva water over there" and because of the name, it becomes easy for the person to identify and get exactly what you need.</p>
<p>Just as you can easily distinguish your Eva water from other water brands by its name, a variable is uniquely identified by its name within a program. While there may be multiple variables storing data, the specific name of a variable allows you to reference its contents precisely.</p>
<p>In JavaScript, values are assigned a name and anytime we need that value, we simply mention the name to which it was assigned. When the code executes, the name of that variable is replaced by the value it refers to.</p>
<p>In the case of the analogy above, the content of the bottle is water and the type is a liquid. But assuming we have a variable <code>x</code> which refers to the value <code>1</code>, the type of the variable is <code>number</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Add the line of code below to the previous code snippet to</span>
<span class="hljs-comment">// find out the data type of x;</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> x)
</code></pre>
<p>In the code snippet above, <code>number</code> is printed to the console because variable x holds the value <code>1</code> which is a number.</p>
<p><strong>Variables exist in our program to help us hold values and be able to refer to them whenever we need to</strong>. <strong>Anywhere a variable is mentioned, the value of that variable is what's being used for the computation at the time</strong>.</p>
<h2 id="heading-how-to-declare-a-variable">How to Declare a Variable</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score;
</code></pre>
<p>The program above declares/creates a variable called <code>score</code>.</p>
<p>In JavaScript, creating variables is that simple. The type of the variable is the type of the value stored in it. That is, if the variable <code>score</code> holds a value of <code>1</code>, the type for the <code>score</code> variable is <code>number</code>. So we can say, <code>score</code> is a number variable.</p>
<p>To create a variable, we have to do the following;</p>
<ol>
<li><p>Declare the variable using one of these keywords: <code>let</code>, <code>const</code> or <code>var</code>.</p>
</li>
<li><p>Determine a name to call the variable and write it on the same line as the keyword used in step 1.</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score; <span class="hljs-comment">// creates variable 'score'</span>
</code></pre>
<p>Notice that this time, we did not give it a value. We just simply created a container that will store something. For now, it is empty. Although it has no content at the moment, we'll surely provide content for it.</p>
<h2 id="heading-variable-assignment-and-initialization">Variable Assignment and Initialization</h2>
<p>We can assign a value to a variable by using the assignment (<code>=</code>) operator—the variable name to the left of it, and the value to the right.</p>
<pre><code class="lang-javascript">score = <span class="hljs-number">1</span>;
</code></pre>
<p>The code snipped above assigns <code>1</code> as the value of <code>score</code> (this is called <strong>variable assignment</strong>).</p>
<p>When we combine variable declaration and assignment in one operation, it is called <strong>variable initialization</strong>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score = <span class="hljs-number">1</span>;
</code></pre>
<p>As seen above, we declare the variable <code>score</code>, and immediately on the same line, assign the value <code>1</code> to it.</p>
<p>This means that we provided an initial value for the variable when it was created.</p>
<h2 id="heading-how-to-call-a-variable">How to Call a Variable</h2>
<p>If you want to use a variable for an operation at any time in your program, you can simply just "call" it. To <strong>call</strong> a variable is the same as <strong>mentioning</strong> or <strong>using</strong> it.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(score + <span class="hljs-number">1</span>) <span class="hljs-comment">// 2</span>
</code></pre>
<p>In the code snippet above, the variable <code>score</code> was <strong>used</strong> in the line of code. Therefore, It will be replaced with its actual value <code>1</code> during the code execution. This means we'd have <code>1 + 1</code> executed, resulting in <code>2</code>.</p>
<p>In the next section, let's learn how to properly name our variables in other to ensure our codes are neat and readable.</p>
<h2 id="heading-how-to-name-variables">How to Name Variables</h2>
<p>Just like naming a human or pet or labeling an object, we always put in much thought to ensure that the name tells a story and gives an idea of how we feel about the role of that pet, human, or object.</p>
<p>JavaScript is somewhat liberal when it comes to how variable naming can be done and also how long it could be.</p>
<p>For example, <code>pneumonoultramicroscopicsilicovolcanoconiosis</code> is a valid variable name in JavaScript even though it is long.</p>
<p>It is generally a good practice to give meaningful names to variables and they should be of a reasonable length.</p>
<p>Let your variables be simple and contextual. For example: <code>author</code>, <code>publishedDate</code>, <code>readTime</code>, <code>shouldCompress</code>, and so on.</p>
<p>It should be self-explanatory. Just avoid cryptic names where possible.</p>
<h3 id="heading-reserved-words-in-javascript">Reserved Words in JavaScript</h3>
<p>Even though we can create variables as we wish, some names are already being used within JavaScript to mean something specific. These names cannot be used by a developer to identify a variable. They are called reserved words.</p>
<p>For instance, the keyword <code>catch</code> is used to properly handle an error and prevent it from crashing an application. Hence, you cannot call a variable <code>catch</code> in your program.</p>
<p>Below are all the reserved words in JavaScript:</p>
<p><code>arguments</code> <code>await</code> <code>break</code> <code>case</code> <code>catch</code> <code>class</code> <code>const</code> <code>continue</code> <code>debugger</code> <code>default</code> <code>delete</code> <code>do</code> <code>else</code> <code>enum</code> <code>eval</code> <code>export</code> <code>extends</code> <code>false</code> <code>finally</code> <code>for</code> <code>function</code> <code>if</code> <code>implements</code> <code>import</code> <code>in</code> <code>Infinity</code> <code>instanceof</code> <code>interface</code> <code>let</code> <code>NaN</code> <code>new</code> <code>null</code> <code>package</code> <code>private</code> <code>protected</code> <code>public</code> <code>return</code> <code>static</code> <code>super</code> <code>switch</code> <code>this</code> <code>throw</code> <code>true</code> <code>try</code> <code>typeof</code> <code>undefined</code> <code>var</code> <code>void</code> <code>while</code> <code>with</code> <code>yield</code></p>
<p><strong>NOTE</strong>: You do not need to memorize these keywords. If you try to use them, you'll get an error and you'll learn to recognize and know them with experience.</p>
<p>Also, JavaScript has some rules that you must follow when naming variables as well as generally accepted conventions (best practices) that you should know about. Let's talk about them in the next section.</p>
<h3 id="heading-rules-for-naming-variables-in-javascript"><strong>Rules for Naming Variables in JavaScript</strong></h3>
<ul>
<li><p>Reserved words cannot be used as variable names.</p>
</li>
<li><p>The first letter of your variable name should be an alphabet, underscore (_), or a dollar sign ($). You cannot use a number as the first character of your variable name. Even though other kinds of special characters are allowed to start a variable name, as a way of good practice and avoiding complexities at the start, you should just always start with a letter. Using an underscore or dollar sign is symbolic by convention and we'll learn what they mean in the future.</p>
</li>
<li><p>The rest of the variable name may contain anything but symbols, punctuations, and reserved characters (+, -, *, and so on).</p>
</li>
<li><p>Variable names are case-sensitive. This means <code>Boy</code> and <code>boy</code> will be treated as different variables in your program.</p>
</li>
<li><p>A variable name can be as long as is necessary for it to make sense. There is no limit imposed by the language.</p>
</li>
<li><p>Spaces are not allowed in variable names.</p>
</li>
</ul>
<h3 id="heading-popular-variable-naming-conventions"><strong>Popular Variable Naming Conventions</strong></h3>
<ul>
<li><p>Variable names with multiple words should use <strong>camel casing.</strong> That is, the first word has to be all lowercase while the first letter of subsequent words should be uppercase: <code>studentRegistrationNumber</code></p>
</li>
<li><p>Use uppercase letters for constant variables: <code>const PI = 3.1432</code></p>
</li>
<li><p>If a constant variable is composed of multiple words, use snake casing (separation of words with an underscore): <code>const PROGRAM_NAME = "Vacation planner"</code></p>
</li>
<li><p>If a variable is meant to be private, prefix its name with an underscore: <code>let _memorySize = 2042</code>.<br>  <strong>Note</strong>: This is just to let the team (others working on the project) know that the author intends to use it as private. It doesn't prevent the value of the variable from being accessed (there are other ways to ensure this).</p>
</li>
<li><p>It is common practice to prefix Boolean variables with <code>is</code> or <code>has</code>: <code>let isMarked = true</code>.</p>
</li>
</ul>
<p>In the next section, we'll learn about different data types and how to work with them.</p>
<h2 id="heading-variable-data-types">Variable Data Types</h2>
<p>Data type simply means "type of data" 😉.</p>
<p>The word "data" in this context means a piece of information. We'll use the word "value<strong>"</strong> sometimes to mean data and vice versa.</p>
<p>In JavaScript, we store values of different types in variables. These values have different attributes/properties and the type of data a variable holds will determine the operations you can perform with that variable.</p>
<p>For example, if you have water (value) stored in a container (variable), you can use the water (value) to wash or drink, but if what is stored in the container are candies, you can eat them but you won't be able to use them for washing.</p>
<p>If you have a variable that holds numbers, you can use them to perform arithmetic operations. If the variable holds a Boolean, you cannot use it for arithmetic operations but it can be used for logical operations.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">The kind of value stored in the variable determines what you can do with it.</div>
</div>

<p>The data types in JavaScript are categorized into two primary groups, namely;</p>
<ul>
<li><p><strong>Primitive</strong>: Number, String, Boolean, Undefined, Null, BigInt, Symbol</p>
</li>
<li><p><strong>Reference</strong>: Object, Array, Function</p>
</li>
</ul>
<p>In this article, we will not talk about Symbols and BigInt to avoid complexities. The goal is to do our best to explain fundamental concepts to beginners in the most simple way possible.</p>
<p>Let's consider primitive data types.</p>
<h3 id="heading-primitive-data-types"><strong>Primitive Da</strong>ta Types</h3>
<p>Variables having these type of data are called primitives because they hold simple values. The word <a target="_blank" href="https://www.google.com/search?q=primitive&amp;rlz=1C5CHFA_enNG1050NG1050&amp;oq=primitive&amp;aqs=chrome..69i57j0i271.760j0j7&amp;sourceid=chrome&amp;ie=UTF-8">primitive</a> can be translated to mean non-complex.</p>
<p>Primitive values are usually a single unit like 1, "cup", null, undefined, true, and so on. Let's briefly consider how these data types are used and what kind of operations you can perform with them.</p>
<ul>
<li><strong>NUMBER:</strong> In JavaScript, all numbers are floating-point values. Whether they are numbers without decimal points like a whole number that can be negative, positive, zero, or values with a decimal point like 0.2, -0.5, 1, -2, 0. They are all of the <code>number</code> type.</li>
</ul>
<p>This type of value can be used in arithmetic operations like multiplication, division, subtraction, addition, modulus, and so on.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> score1 = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> score2 = <span class="hljs-number">5</span>;
<span class="hljs-keyword">let</span> averageScore = (score1 + score2) <span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(averageScore) <span class="hljs-comment">// 3.5</span>
</code></pre>
<p>To check the data type of a variable's value, use the <code>typeof</code> operator like this: <code>typeof variableName</code>. That is: <code>typeof score1</code></p>
<p>In the code snippet above, <code>score1</code> is a variable which holds a value of <code>2</code>, <code>score2</code> holds a value of <code>5</code>, while the <code>averageScore</code> variable stores the result from dividing the sum of <code>score1</code> and <code>score2</code> by <code>2</code>, which evaluates to <code>3.5</code>.</p>
<p>Using the <code>typeof</code> operator on the <code>score1</code> variable will return <code>number</code>.</p>
<p><strong>Exercise</strong>: Copy the code in the snippet above and run it in your code editor to see how it works for you. You can play around with the values and use the <code>typeof</code> operator to check the variables' data type.</p>
<p>When performing arithmetic operations, you may run into other Number types like <code>Infinity</code>, <code>-Infinity</code> and <code>NaN</code>.</p>
<p><strong>Infinity</strong> means something without any limit. One way to reach infinity is to divide a number by 0.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> result = <span class="hljs-number">12</span> / <span class="hljs-number">0</span>;

<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// Infinity</span>
</code></pre>
<p>In the code above, we divided <code>12</code> by <code>0</code> and logged the result to the console which prints out <code>Infinity</code>.</p>
<p><strong>Negative Infinity</strong> is used to denote a number that is less than any natural number. To arrive at negative infinity, copy the code in the snippet below and run it in your coding environment.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Number</span>.NEGATIVE_INFINITY) <span class="hljs-comment">// -Infinity</span>
</code></pre>
<p><strong>NaN</strong> means Not <strong>a</strong> Number. This will occur when you try to carry out an impossible mathematical operation as shown below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> result = <span class="hljs-string">"Ella"</span> / <span class="hljs-number">2</span>; <span class="hljs-comment">// Trying to divide a string with a number</span>
<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// NaN</span>
</code></pre>
<p>The first line in the code above tries to divide a string by a number and the result is <code>NaN</code>.</p>
<p>You will not often reach infinity or -Infinity as a beginner doing basic/intermediate stuff, but it is something you should be aware of so that you do not get worked up when you see it occur in your code (this is something you do not want to cram in your head). <code>NaN</code> is will occur more often than the others. When you see it, just know something is wrong with the operation you are trying to perform.</p>
<ul>
<li><strong>STRING:</strong> In JavaScript, a string is a collection of characters enclosed in quotes: <code>"Cathy"</code>.</li>
</ul>
<p>The snippet below shows how a string can be used in a JavaScript program:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> author = <span class="hljs-string">"Sleekcodes"</span>;
<span class="hljs-keyword">let</span> publishedDate = <span class="hljs-string">"14 August 2023"</span>;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Written by: "</span> + author); <span class="hljs-comment">// Written by: Sleekcodes</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Published on: "</span> + publishedDate); <span class="hljs-comment">// Published on: 14 August 2023"</span>
</code></pre>
<p>I am sure you noticed the + operator used with strings. When this occurs, the result is that the string on the right and that on the left will be joined together to become one. This is called string concatenation.</p>
<p>The code above is simply saying, "Create a variable called <code>author</code> and store the text <code>"sleekCodes"</code> as its value, create another variable <code>publishedDate</code> and store the text <code>"14 August 2023"</code> in it."</p>
<p>Then in line 4, we tell the JavaScript engine to log (print) the string "Written by: Sleekcodes<strong>"</strong> to the console. Line 5 also says log <strong>"</strong>Published on: 14 August 2023<strong>"</strong> to the console.</p>
<p>Notice that in the code above, during execution, <code>author</code> gets replaced with the value "Sleekcodes" and <code>publishedDate</code> gets replaced with "14 August 2023" where used.</p>
<p>Strings are used to depict or convey data in text/alphabetic format. A string can be made up of zero or more characters. A string that has no character in it is called an empty string. For example: <code>""</code>.</p>
<ul>
<li><strong>BOOLEAN</strong>: When we need to represent data in two possible states only like true/false, on/of, or yes/no, we use Boolean values. The value of a Boolean variable is either <code>true</code> or <code>false</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> isQualified = <span class="hljs-literal">true</span>

<span class="hljs-keyword">if</span> (isQualified) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Tola is qualified"</span>); <span class="hljs-comment">// Tola is qualified</span>
}
</code></pre>
<p>The code above will print the statement "Tola is qualified", because the value of the variable <code>isQualified</code> is true. That operation is a type of conditional operation. This is where Boolean values shine.</p>
<p><strong>Exercise</strong>: Change the value of <code>isQualified</code> to be <code>false</code> and observe what happens.</p>
<ul>
<li><strong>UNDEFINED</strong>: This is both a value and a data type. <code>undefined</code> is used to indicate that a variable has no defined value. For instance, when a variable is declared (<code>let age</code>), and you try to access its value, the result would be <code>undefined</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age; <span class="hljs-comment">// note that there is no value assigned to the variable here</span>

<span class="hljs-built_in">console</span>.log(age); <span class="hljs-comment">// undefined</span>
</code></pre>
<p>In the code snippet above, because age isn't given any explicit value, the compiler assigns the value <code>undefined</code> to the variable by default.</p>
<p><strong>Exercise</strong>: Use the <code>typeof</code> operator on the variable <code>age</code> and see what you get. Also, assign the value <code>undefined</code> to <code>age</code> and use the <code>typeof</code> operator on it again to see the result.</p>
<ul>
<li><strong>NULL</strong>: Null is a value we can assign to a variable to indicate that it has no value. It is used to represent "empty" or "unknown".</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> age = <span class="hljs-literal">null</span>;

<span class="hljs-built_in">console</span>.log(age); <span class="hljs-comment">// null</span>
</code></pre>
<p>As seen in the code snippet above, instead of letting the compiler assign <code>undefined</code> for us, we explicitly indicate that the variable has no value by assigning the value <code>null</code> to it.</p>
<p>This means <code>age</code> is empty or unknown.</p>
<p>People often get confused about the difference between <code>undefined</code> and <code>null</code>. One is the default value assigned to a variable without an explicit value, while the other (<code>null</code>) is a value assigned to a variable by the programmer deliberately to indicate that the variable is empty. As a rule of thumb, do not assign <code>undefined</code> to a variable, instead use <code>null</code> (the compiler auto-assigns <code>undefined</code> where needed).</p>
<p>Primitive data types have no complexity. They are plain and simple (a single value). This statement will make more sense when you read about how reference types work in the next section.</p>
<p>Consider the image below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691169563292/8cd6a8de-e6c5-46fe-8271-c2a522b6c663.png" alt="primitive types concept" class="image--center mx-auto" width="1782" height="1447" loading="lazy"></p>
<p><strong>Part A</strong> above is the code you write, while <strong>Part</strong> <strong>B</strong> is what happens when the code runs. For primitive data types, the value is simply assigned to the variable (it is straightforward).</p>
<p>Primitive values are passed by value (they generate no reference). Do not worry about what this means yet because we'll explain in the next section.</p>
<h2 id="heading-reference-types-in-javascript">Reference Types in JavaScript</h2>
<p>Reference data types are data passed by "reference". A thorough understanding of this statement is crucial throughout your career as a JavaScript developer, so do well to pay close attention to the concept we are about to learn.</p>
<p>Consider the image below carefully.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691062567476/e31e1bfe-6b85-418e-a88a-e19810f11839.png" alt="Reference types concept" class="image--center mx-auto" width="2338" height="1633" loading="lazy"></p>
<p>In the image above, <strong>part A</strong> is the code you write, while <strong>part B</strong> is what happens "behind the scenes".</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Use the image above to follow through with the following explanation.sa</div>
</div>

<p>When you create a variable whose data type is in the reference category (objects, functions, arrays), instead of the value being directly assigned to the variable, a reference is generated for the value and that reference is what gets assigned to the variable<strong>.</strong></p>
<p>The reference gets assigned to the variable, but it points to the actual value.</p>
<p>This means that when you try to use the variable anywhere, you are working with the reference to the actual value and anything done to the reference affects the actual value.</p>
<p>Think of it like a middleman between the actual value and the variable name.</p>
<p>Consider the example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> studentInfo = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">205</span>
}

<span class="hljs-keyword">let</span> staffInfo = studentInfo <span class="hljs-comment">//6. This means; assign the ref of studentInfo to staffInfo</span>

staffInfo.name = <span class="hljs-string">"Lorry Sante"</span> <span class="hljs-comment">//8. Change the value of name key in the reference which staffInfo holds.</span>

<span class="hljs-built_in">console</span>.log(studentInfo.name) <span class="hljs-comment">//9. Lorry Sante</span>
</code></pre>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>Try this:</strong> In line 7 and 8, log the value of <a target="_blank" href="http://studentInfo.name"><code>studentInfo.name</code></a> and <a target="_blank" href="http://staffInfo.name"><code>staffInfo.name</code></a> to the console to see what they are.</div>
</div>

<p>You should notice that, changing <code>name</code> in <code>staffInfo</code> object (line 8), causes the name in <code>studentInfo</code> object to change too (as seen in the output of line 9).</p>
<p>In fact, both variables are pointing to the same value technically (see image below);</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691069171621/a53d4f52-6b86-4581-85fc-57452cbc90be.png" alt="reference types variable storage " class="image--center mx-auto" width="1114" height="269" loading="lazy"></p>
<p>When we say that a variable is passed by reference<strong>,</strong> it means that anywhere that variable is used, you are interacting with a reference (that points) to its actual value.</p>
<p>So in the code snippet above, when <code>studentInfo</code> was assigned to <code>staffInfo</code>, we just made <code>staffInfo</code> to store the reference of the <code>studentInfo</code> variable, effectively saying that both <code>staffInfo</code> and <code>studentInfo</code> variables are pointing to the same value.</p>
<p>Therefore, if the reference generated for <code>studentInfo</code> is <code>000xx2</code> and it is true that during execution, variables are replaced by whatever they hold, then <code>staffInfo = studentInfo</code> would become <code>staffInfo = 000xx2</code> during execution, while <code>staffInfo.name</code> would become <code>000xx2.name</code>.</p>
<p>If we had written <code>studentInfo.name</code>, then during execution, it becomes <code>000xx2.name</code>, it should be clear now that both <code>studentInfo</code> and <code>staffInfo</code> holds references to one value. They are like different roads to one destination.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">If this is your first time learning this concept, you should repeat the section above before you proceed. It will become clearer and when we start operating with reference types, you'll be glad you read this article.</div>
</div>

<p>There are three main reference data types that you'll mostly come across in your journey as a JavaScript developer: Object, Array, and Function. Let's look into them one after the other.</p>
<ul>
<li><strong>OBJECT</strong>: An object is a data structure used to store complex data in key/value pairs. The variable created in the previous session has an object type like this:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> studentInfo = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">205</span>
}
</code></pre>
<p>You can see that it isn't primitive (simple). Unlike primitive types with just simple values, an object can be used to store different information which can be made up of even primitive and reference types.</p>
<p>Objects store data in key/value pairs like so: <code>{key: value}</code></p>
<p>In the code snippet above, <code>name</code> is key, while <code>"John Doe"</code> is its value. Also, <code>age</code> is key, while <code>205</code> is its value.</p>
<p>If you notice, both <code>name</code> and <code>age</code> have primitive values (string and number).</p>
<p>To access the value of an object, we use the object name, dot (.) notation, and the key whose value we want to access. For example: <code>objectName.key</code>.</p>
<p>Objects can also contain nested objects like so:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> studentInfo = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">205</span>,
    <span class="hljs-attr">beneficiary</span>: {
       <span class="hljs-attr">name</span>: <span class="hljs-string">"Tira Doe"</span>,
       <span class="hljs-attr">age</span>: <span class="hljs-number">200</span>,
       <span class="hljs-attr">relationship</span>: <span class="hljs-string">"Wife"</span>
    }
}
</code></pre>
<p>In the above example, the <code>studentInfo</code> object has a nested object called <code>beneficiary</code>. <code>beneficiary</code> is a key whose value is an object (reference type). Objects can still hold arrays and functions too.</p>
<p>Accessing the value associated with a key in an object within another object (nested object) is natural. We simply use dot notation. Like so: <code>parentObjectName.nestedObjectName.key</code></p>
<p>For example, to access the name of the beneficiary in <code>studentInfo</code> object above, we simply write <code>studentInfo.beneficiary.name</code>.</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">There's no limit to nesting objects in objects. However, ensure that nesting is necessary for what you want to achieve and too much nesting should be avoided for simplicity.</div>
</div>

<p>This is not all that you need to know about objects but it is a very sound way to start.</p>
<ul>
<li><strong>ARRAY</strong>: An array is a kind of object but stores data using automatically assigned indexes instead of keys.</li>
</ul>
<p>An array is created by writing a comma-separated list of values enclosed with square brackets: <code>[0, 1, 2, 3, "Tosin", "Mike", {name: "Abel Joe", age: 250}]</code></p>
<p>If you pay close attention to the values used in the array above, you'll notice that they are of different data types. Yes, arrays also allow you to store values of different types in one place but this is strongly discouraged (you shouldn't do it at all). The values in an array should all be of the same type<strong><em>.</em></strong></p>
<p>Example of a proper array: <code>let scores = [1, 3, 5, 6, 9, 12]</code></p>
<p>To access a value in an array, we simply specify the array name, followed by a square bracket <code>[]</code> without any space between the name and the bracket. Then inside the square bracket, provide the index of the value you wish to access. That is: <code>arrayName[index]</code>.</p>
<p>What's an index and how do we know what index refers to the value we want to access?</p>
<p>An index is simply a number automatically assigned to an array value<strong>.</strong> You can think of it as an address for values in the array. Arrays are <code>0</code> indexed (meaning they start counting from zero)<strong>.</strong></p>
<p>To determine the index of the value you wish to access, start counting from the start of the array and your count should start from 0.</p>
<p>Consider the image below;</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1691072847798/ca5bc276-f024-40eb-b69e-b8e31f17314f.png" alt="array and indexes" width="483" height="183" loading="lazy"></p>
<p>To access the value <code>80</code> in the <code>scores</code> array depicted in the image above, we simply write <code>scores[3]</code></p>
<p>There is a lot you can do with arrays as a JavaScript developer. For now, this is a simple introduction to the array data type.</p>
<ul>
<li><strong>FUNCTION</strong>: A function is a different kind of variable and it's declared differently (using the <code>function</code> keyword instead of <code>let</code>, <code>const</code> or <code>var</code>). It is a construct used to carry out a specific task.</li>
</ul>
<p>For example, if you need to add two numbers together multiple times within your code, it's best practice to create a dedicated function for this task. By reusing this function, you avoid redundant code and improve code maintainability compared to repeatedly writing the addition logic. Wait!!! You are not lost. The example below will confirm this 😊</p>
<p>Scenario 1 (without function):</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> num1 = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> num2 = <span class="hljs-number">3</span>;
<span class="hljs-keyword">let</span> result = num1 + num2;

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

<span class="hljs-keyword">let</span> num3 = <span class="hljs-number">3</span>;
<span class="hljs-keyword">let</span> num4 = <span class="hljs-number">8</span>;
<span class="hljs-keyword">let</span> result2 = num3 + num4;

<span class="hljs-built_in">console</span>.log(result2) <span class="hljs-comment">// 11</span>
</code></pre>
<p>Scenario 2 (with function):</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// function declaration.</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addNumbers</span> (<span class="hljs-params">num1, num2</span>) </span>{
    <span class="hljs-keyword">return</span> num1 + num2;
}

<span class="hljs-built_in">console</span>.log(addNumbers(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">// 5</span>
<span class="hljs-built_in">console</span>.log(addNumbers(<span class="hljs-number">3</span>, <span class="hljs-number">8</span>)); <span class="hljs-comment">// 11</span>
</code></pre>
<p>You will agree that, scenario 2 contains less code, looks neater, and even feels more natural.</p>
<p>Functions allow us write helpers that we can call to get a specific job done for us any time we want. We just have to tell it how to do the job once and call it anytime we need it to do that job (passing in any information required for the task as arguments) and it delivers.</p>
<p>Function Syntax:</p>
<p>To write a function, we use the <code>function</code> keyword, followed by the name of the function: <code>functionName</code>, a pair of brackets <code>()</code>, and a pair of curly braces <code>{}</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">functionName</span> (<span class="hljs-params"></span>) </span>{}
</code></pre>
<p>There are a few things/conventions you should have in mind when writing functions:</p>
<ul>
<li><p>Function names should follow the same naming rules as variables.</p>
</li>
<li><p>Function names should be verbs (to depict an action).</p>
</li>
<li><p>The code logic for the actual task should be written between the opening <code>{</code> and closing <code>}</code> curly braces.</p>
</li>
<li><p>If there are values required to carry out the task, they should be passed into the function as arguments. In this case, during the function declaration, parameters should be stated between the opening <code>(</code> and closing <code>)</code> brackets in a comma-separated fashion. That is: <code>function addNumbers(num1, num2)...</code>.</p>
</li>
<li><p>If no data is required to carry out the task, then the opening <code>(</code> and closing <code>)</code> brackets should be left empty: <code>function sayHi()...</code>.</p>
</li>
</ul>
<p>A parameter is a variable defined between the opening <code>(</code> and closing <code>)</code> of a function during its declaration: <code>function doSomething (param1, param2) {...}</code>.</p>
<p>An argument is the value passed into the function during its invocation/call: <code>doSomething(1, 2)</code></p>
<p>As seen above, to call/invoke a function, write the function name, followed by an opening and a closing bracket (without any whitespace). Required arguments should be provided between the opening and closing brackets (if any).</p>
<p>To drive this concept home, let's create a function to multiply two digits:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//        functionName   param1 param2</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiplyNumbers</span> (<span class="hljs-params">num1, num2</span>) </span>{
    <span class="hljs-keyword">return</span> num1 * num2; <span class="hljs-comment">// task to carry out.</span>
}
</code></pre>
<p>It's as simple as that.</p>
<p>Having done that, let's call/invoke the function.</p>
<pre><code class="lang-javascript">multiplyNumbers(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>) <span class="hljs-comment">// 6</span>
</code></pre>
<p>Notice that while creating the function, we declared two parameters: <code>num1</code> and <code>num2</code>. When calling the function, we assigned values to the two arguments: 1 and 2.</p>
<p><code>return</code> <strong>keyword</strong></p>
<p>Functions may return values or not.</p>
<p>If a function contains a <code>return</code> statement, like the <code>multiplyNumbers</code> function, then it will return a value if everything goes well. If there is no return statement for the function, it will return <code>undefined</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHi</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hi"</span>);
}
</code></pre>
<p>If we invoke <code>sayHi</code>, it would log the text <code>Hi</code> to the console and it will also return <code>undefined</code>.</p>
<p>Remember that functions are like helpers, when you send a helper to carry out an assignment, you may require them to give you feedback (the result of the task they carried out) or you may not need feedback.</p>
<p>If you need feedback, add a <code>return</code> statement about what feedback you need. Otherwise, do not add a <code>return</code> statement to the function.</p>
<p>There is still a lot to learn about every data type we have highlighted in this article so take your time to practice these basics and when you feel comfortable enough using them, you'll see the need to dive deeper.</p>
<h2 id="heading-summary">Summary</h2>
<p>Variables are "pointers" to values. When you mention (use) a variable anywhere in your code, the variable identifier (name) is replaced with the value it points to. It's just like calling someone's name. The name doesn't respond, the person (value) behind the name is what you hope to get as a response.</p>
<p>By way of retention, do not try to cram all these rules and conventions. Feel free to refer back to this article when programming and in a short amount of time, you'll be used to all of them and you won't need to refer to any article ever again to name your variables properly.</p>
<p>If you should have anything in mind, remember to start variables with a lowercase letter if the variable is made of multiple words, subsequent words should start with uppercase letters. That is: <code>age</code>, <code>dateOfBirth</code>.</p>
<p>To create a variable, use the keyword <code>let</code>, <code>const</code>, or <code>var</code>, followed by the variable name. If you wish to initialize the variable, then on the same line before the semi-colon, input the assignment operator and variable value after it.</p>
<p>For example: <code>let score;</code> or <code>let score = 3;</code> (if you wish to initialize during declaration).</p>
<p>If you wish to use a variable, just mention its name and the value will be used during the execution of your code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-number">2</span>;
<span class="hljs-keyword">let</span> b = <span class="hljs-number">3</span>;
<span class="hljs-built_in">console</span>.log(a + b) <span class="hljs-comment">// 4</span>
</code></pre>
<p>This article also showed you the different data types in JavaScript and how to use them.</p>
<p>Did this post help? Let’s keep the conversation going. Feel free to share your thoughts or questions on Twitter (x) or LinkedIn. You can find me on Twitter (x) <a target="_blank" href="https://x.com/asoluka_tee">@asoluka_tee</a> and <a target="_blank" href="https://www.linkedin.com/in/tochukwu-austin-asoluka-415326155/">Tochukwu Austin Asoluka</a> on LinkedIn.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is Prototypal Inheritance in JavaScript? Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Prototypal inheritance can feel like a complex concept shrouded in technical jargon. But fear not! This guide will break it down using clear, relatable examples that go beyond the typical textbook explanations.  We'll ditch the confusing terms and fo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-prototypal-inheritance/</link>
                <guid isPermaLink="false">66c375021e62f88108dcb768</guid>
                
                    <category>
                        <![CDATA[ inheritance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Austin Asoluka ]]>
                </dc:creator>
                <pubDate>Fri, 31 May 2024 08:10:16 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/Screenshot-2024-05-29-at-00.19.30.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Prototypal inheritance can feel like a complex concept shrouded in technical jargon. But fear not! This guide will break it down using clear, relatable examples that go beyond the typical textbook explanations. </p>
<p>We'll ditch the confusing terms and focus on real-world scenarios that you can easily understand.</p>
<p>By the end of this post, you'll be a prototypal inheritance pro, realizing that it wasn't that hard after all!</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-concept-introduction">Concept Introduction</a></li>
<li><a class="post-section-overview" href="#heading-what-are-javascript-objects">What are JavaScript Objects?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-an-object-prototype">What is an Object Prototype?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-prototype-of-a-constructor">How to Work with .prototype Object of a Constructor</a></li>
<li><a class="post-section-overview" href="#heading-how-to-alter-a-constructors-prototype">How to Alter a Constructor's Prototype</a></li>
<li><a class="post-section-overview" href="#heading-the-proto-property">The <strong>proto</strong> Property</a></li>
<li><a class="post-section-overview" href="#heading-summary">Summary</a></li>
</ul>
<h2 id="heading-concept-introduction">Concept Introduction</h2>
<p>Imagine that I'm a parent and I have a child and a grandchild. If you were to represent my family tree in a diagram, it should look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/Screenshot-2024-05-09-at-23.12.29.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Fig 1</strong>: Depicting the inheritance structure with family</em></p>
<p>You can see that <code>grandparent</code> is at the top of this family tree, while the <code>parent</code> is a direct descendant of the <code>grandparent</code>, and the <code>child</code> is a descendant of <code>parent</code>.  </p>
<p>If you attempt to walk your way back up, you'll see that <code>grandchild</code> is a child of <code>parent</code> and its own parent is a <code>child</code> of <code>grandparent</code>.</p>
<h2 id="heading-what-are-javascript-objects">What are JavaScript Objects?</h2>
<p>You may have come across this statement at some point: "In JavaScript, almost everything is an Object".</p>
<p>Notice how I spelt <code>Object</code>? When I use Object and object throughout this article, they will mean different things.</p>
<p>Object is a constructor used to create objects. That is: one is parent/ancestor and the other is child.</p>
<p>Using the illustration in <strong>Fig 1.0</strong> above, let's attempt to demonstrate how the family tree works in JavaScript.</p>
<p> <code>Object</code> ⁠ is the grandparent.</p>
<p>Constructors like ⁠ <code>Array</code>, <code>String</code>, <code>Number</code>, <code>Function</code>, ⁠ and <code>⁠ Boolean</code> ⁠ are all descendants of ⁠ <code>Object</code>.</p>
<p>They all produce offspring of different types: <code>array</code>, <code>string</code>, <code>number</code>, <code>function</code>, and <code>Boolean</code>. However, if you trace back to their origin, they are all <code>Objects</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/Screenshot-2024-05-10-at-00.08.57.png" alt="Image" width="600" height="400" loading="lazy">
<em><strong>Fig 2</strong>: Object is at the top of the inheritance tree in JavaScript</em></p>
<p>So if you're asked why everything (except <code>null</code> and <code>undefined</code>) are regarded as objects in JavaScript, it is because they are all descendants of the <code>Object</code> constructor.  </p>
<p>The constructors listed in the image above are responsible for the different data types you use in JavaScript. That is, they are used behind the scenes to create familiar data types (and you can also use them to create values of different types explicitly).</p>
<p>Let's try out some code snippets.</p>
<h3 id="heading-how-to-create-an-object">How to Create an object</h3>
<pre><code class="lang-js"><span class="hljs-comment">// Using the regular object syntax</span>
<span class="hljs-keyword">const</span> newObj = {}

<span class="hljs-comment">// Using the object constructor</span>
<span class="hljs-keyword">const</span> newObjWithConstructor = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Object</span>()
</code></pre>
<h3 id="heading-how-to-create-an-array">How to Create an array</h3>
<pre><code class="lang-js"><span class="hljs-comment">// Using the regular array syntax</span>
<span class="hljs-keyword">const</span> newArr = []

<span class="hljs-comment">// Using the array constructor</span>
<span class="hljs-keyword">const</span> newArrWithConstructor = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Array</span>()
</code></pre>
<h3 id="heading-how-to-create-a-number">How to Create a number</h3>
<pre><code class="lang-js"><span class="hljs-comment">// Using the regular syntax</span>
<span class="hljs-keyword">const</span> num = <span class="hljs-number">3</span>

<span class="hljs-comment">// Using the number constructor</span>
<span class="hljs-keyword">const</span> numWithConstructor = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Number</span>(<span class="hljs-number">3</span>)
</code></pre>
<h3 id="heading-how-to-create-a-function">How to Create a function</h3>
<pre><code class="lang-js"><span class="hljs-comment">// Using regular function syntax</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">logArg</span> (<span class="hljs-params">arg</span>) </span>{
    <span class="hljs-built_in">console</span>.log(arg)
}

<span class="hljs-comment">// Using the Function constructor</span>
<span class="hljs-keyword">const</span> logArgWithConstructor = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Function</span>(<span class="hljs-string">'arg1'</span>, <span class="hljs-string">'console.log(arg1)'</span>)
</code></pre>
<h3 id="heading-how-to-create-a-boolean">How to Create a boolean</h3>
<pre><code class="lang-js"><span class="hljs-comment">// Using the regular boolean syntax</span>
<span class="hljs-keyword">const</span> isValid = <span class="hljs-literal">true</span>

<span class="hljs-comment">// Using the Boolean constructor</span>
<span class="hljs-keyword">const</span> isValidWithConstructor = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Boolean</span>(<span class="hljs-literal">true</span>)
</code></pre>
<p>You can see that from the example snippets above, it is possible to explicitly create values using the appropriate constructor, or just by using the simple syntax and allow JavaScript to create the value with the appropriate type for us.</p>
<p><strong>Note</strong>: It is important to state that each method of creating values have their own use case and side effects but we won't be getting into that in this article.</p>
<p>The constructors of these various values have something called a prototype.</p>
<h2 id="heading-what-is-an-object-prototype">What is an Object Prototype?</h2>
<p>In JavaScript, there is something called <code>prototype</code>. The closest concept to this is the human DNA.</p>
<p>Just like DNA acts as blueprints that define characteristics that are passed on through generations of the human family tree, <code>prototypes</code> in JavaScript are used to define properties and methods that are inherited by objects down the JavaScript Object tree.</p>
<p>Let us combine <strong>Fig 1</strong> and <strong>Fig 2</strong> above, updating it now to accommodate the concept of DNA and prototype.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/Screenshot-2024-05-10-at-01.01.47.png" alt="Image" width="600" height="400" loading="lazy">
<em>Fig 3: Comparing JavaScript inheritance with the concept of inheritance in humans</em></p>
<p>In JavaScript, all constructors have a prototype<strong>.</strong> The prototype of a constructor is a dictionary of everything that values created with the constructor should inherit.</p>
<p>Read the line above ☝️ again and proceed when it is clear.</p>
<p>Think of the constructor like a parent and the prototype like the DNA. When the constructor (parent) creates (gives birth to) an offspring (value), the offspring inherits from the DNA (prototype) of it's parent the constructor.</p>
<p>Let's consider another diagram:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/Screenshot-2024-05-10-at-01.28.05.png" alt="Image" width="600" height="400" loading="lazy">
<em>Fig 4: Rough depiction of DNA Inheritance in human</em></p>
<p>From <strong>Fig 4</strong>, you can see that a child inherits directly from their parent and their parent inherits traits from the grandparent. In this chain of inheritance, the child actually inherits from both the grandparent and the parent. </p>
<p>In fact, the child's characteristics traits are strongly influenced by the combination of the DNA of every ancestor before itself.</p>
<p>This is how prototypal inheritance works in JavaScript.</p>
<p>The properties in the prototype of a constructor are inherited by the children created by that constructor. This continues down the chain. You can reason about it like this:</p>
<p>Every descendant in the inheritance chain, inherits everything available in the prototype of its ancestors.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/Screenshot-2024-05-10-at-02.07.22.png" alt="Image" width="600" height="400" loading="lazy">
<em>Fig 5: Prototypal inheritance chain</em></p>
<p>From the diagram above, you can see that all other prototypes inherit from the Object prototype. Therefore, any value created with the Array constructor (for instance), will inherit from the Array prototype, and also, the Object prototype.</p>
<p>This is so because Array prototype inherits from Object prototype.</p>
<p>The term Array prototype is written as <code>Array.prototype</code> in JavaScript, while Object prototype is <code>Object.prototype</code>.</p>
<p><strong>Note</strong>: It is important to note that the concept of DNA is complex so if stretched, we would quickly discover that there are some nuances and difference between how DNA and prototypes work but at the high level, they are very similar.</p>
<p>Therefore, an understanding of inheritance in human family tree would give us a strong understanding of prototypal inheritance in JavaScript.</p>
<p>If you learn better with videos, <a target="_blank" href="https://www.youtube.com/watch?v=TzqJPmEkZ0o">watch this</a>, before you continue.</p>
<h2 id="heading-how-to-work-with-prototype-of-a-constructor">How to Work With <code>.prototype</code> of a Constructor</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/Screenshot-2024-05-10-at-02.16.07.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To view the content of a constructor's prototype, we simply write <code>theConstructorName.prototype</code>. Foe example: <code>Array.prototype</code>, <code>Object.prototype</code>, <code>String.prototype</code> and so on.</p>
<p>Ever imagined how it is possible to write <code>[2, 8, 10].**map**(...)</code>? This is because, in the prototype of the Array constructor, there's a key called <code>map</code>. So even though you did not create the property <code>map</code> by yourself, it was inherited by the array value because that value was created by the <code>Array</code> constructor internally.</p>
<p>Read the above statement thus: Have you ever wondered why you have your specific blood type? It's because you get your blood type from the genes you inherited from your parents!</p>
<p>So the next time you make use of properties and methods like <code>.length</code>, <code>.map</code>, <code>.reduce</code>, <code>.valueOf</code>, <code>.find</code>, <code>.hasOwnProperty</code> on a value, just remember that they are all inherited from the constructor's prototype or some prototype up the prototype chain (the ancestry).</p>
<p>You can see the constructor prototype as the prototype of the entity used to construct/create/make a value.</p>
<p>You should be aware that the <code>.prototype</code> of every constructor is an object. The constructor itself is a function, but it's prototype is an object.</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">Array</span>) <span class="hljs-comment">// function</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">Array</span>.prototype) <span class="hljs-comment">// object</span>
</code></pre>
<p><strong>Note</strong>: An exception to this is the prototype of the Function constructor. It is a function object, but it still has properties attached to it and those properties can be accessed like we would do with regular objects (using the <code>.</code> notation).</p>
<p>If you recall, we can add new properties to and retrieve values of already existing properties of objects by using the dot <code>.</code> notation. For example: <code>objectName.propertyName</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">"asoluka_tee"</span>,
    <span class="hljs-attr">stack</span>: [<span class="hljs-string">"Python"</span>, <span class="hljs-string">"JavaScript"</span>, <span class="hljs-string">"Node.js"</span>, <span class="hljs-string">"React"</span>, <span class="hljs-string">"MongoDB"</span>],
    <span class="hljs-attr">twitter_url</span>: <span class="hljs-string">"https://twitter.com/asoluka_tee"</span>
}

<span class="hljs-comment">// Using the syntax objectName.propertyName, to access the name key we'll write; user.name </span>
<span class="hljs-keyword">const</span> userName = user.name;
<span class="hljs-built_in">console</span>.log(userName) <span class="hljs-comment">// asoluka_tee</span>

<span class="hljs-comment">// To add a new property to the object we'd write;</span>
user.eyeColor = <span class="hljs-string">"black"</span>

<span class="hljs-comment">// If we log the user object to the console now, we should see eyeColor as part of the object properties with the value of 'black'</span>
</code></pre>
<p>Ever heard of DNA mutation? It's the idea of altering ones DNA. In JavaScript, this is possible with prototypes.</p>
<p>Just like DNA mutation is an extremely dangerous thing to try and the outcome could be uncertain or cause undesired side-effects, altering the prototype of a constructor is not a good idea unless you know what you are doing.</p>
<h2 id="heading-how-to-alter-a-constructors-prototype">How to Alter a Constructor's Prototype</h2>
<p>In JavaScript, it is possible to alter the prototype object of a constructor just the same way you can with a regular JavaScript object (as shown above).  </p>
<p>This time, we just need to follow this syntax <code>constructorName.prototype.newPropertyName = value</code>. For example, if you want to add a new property named <code>currentDate</code> to the prototype object of the Array constructor, you'd write:</p>
<pre><code class="lang-js"><span class="hljs-comment">//constructorName.prototype.newPropertyName</span>
<span class="hljs-built_in">Array</span>.prototype.currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toDateString();
</code></pre>
<p>From now on, in your code, because <code>currentDate</code> now exists in the prototype of the <code>Array</code> constructor <code>(Array.prototype)</code>, every array created in our program can access it like this: <code>[1, 2, 3].currentDate</code> and the result will be today's date.   </p>
<p>If you want every object in your JavaScript program to have access to <code>currentDate</code>, you have to add it to the prototype object of the <code>Object</code> constructor <code>(Object.prototype)</code> instead:</p>
<pre><code class="lang-js"><span class="hljs-comment">//constructorName.prototype.newPropertyName</span>
<span class="hljs-built_in">Object</span>.prototype.currentDate = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().toDateString();

<span class="hljs-keyword">const</span> newArr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
<span class="hljs-keyword">const</span> newObj = {}
<span class="hljs-keyword">const</span> newBool = <span class="hljs-literal">true</span>

<span class="hljs-comment">// NB: The date shown is the date of writing this article</span>
<span class="hljs-built_in">console</span>.log(newArr.currentDate) <span class="hljs-comment">// 'Fri May 10 2024'</span>
<span class="hljs-built_in">console</span>.log(newObj.currentDate) <span class="hljs-comment">// 'Fri May 10 2024'</span>
<span class="hljs-built_in">console</span>.log(newBool.currentDate) <span class="hljs-comment">// 'Fri May 10 2024'</span>
</code></pre>
<p>This is possible because the prototype object of all constructors inherit from the prototype object of the <code>Object</code> constructor.  </p>
<p>Let's write our version of two popular array methods and use them just like we'd used the original.</p>
<ol>
<li><strong>Array.prototype.reduce</strong>: We'll call ours <code>.reduceV2</code></li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// Add our new function to the prototype object of the Array constructor</span>
<span class="hljs-built_in">Array</span>.prototype.reduceV2 = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">reducer, initialValue</span>) </span>{
  <span class="hljs-keyword">let</span> accum = initialValue;
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">this</span>.length; i++) {
    accum = reducer(accum, <span class="hljs-built_in">this</span>[i]);
  }
  <span class="hljs-keyword">return</span> accum;
};

<span class="hljs-comment">// Create an array of scores</span>
<span class="hljs-keyword">let</span> scores = [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>, <span class="hljs-number">50</span>];

<span class="hljs-comment">// Use our own version of Array.prototype.reduce to sum the values of the array</span>
<span class="hljs-keyword">const</span> result = scores.reduceV2(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">accum, curr</span>) </span>{
  <span class="hljs-keyword">return</span> accum + curr;
}, <span class="hljs-number">0</span>);

<span class="hljs-comment">// Log the result to the console</span>
<span class="hljs-built_in">console</span>.log(result);
</code></pre>
<p>The focus here is not to explain the whole syntax, it is to show you that by leveraging the prototype chain, you can create your own methods and use them just like the ones JavaScript provides.</p>
<p>Notice that you can just replace our <code>.reduceV2</code> with the original <code>.reduce</code> and it will still work (edge cases are not handled here).  </p>
<ol start="2">
<li><strong>Array.prototype.map</strong>: We'll call ours <code>.mapV2</code> </li>
</ol>
<pre><code class="lang-js"><span class="hljs-comment">// Add mapV2 method to the prototype object of the Array constructor</span>
<span class="hljs-built_in">Array</span>.prototype.mapV2 = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">func</span>) </span>{
  <span class="hljs-keyword">let</span> newArray = [];
  <span class="hljs-built_in">this</span>.forEach(<span class="hljs-function">(<span class="hljs-params">item, index</span>) =&gt;</span> newArray.push(func(item, index)));
  <span class="hljs-keyword">return</span> newArray;
};

<span class="hljs-comment">// Create an array of scores </span>
<span class="hljs-keyword">const</span> scores = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

<span class="hljs-comment">// Use our mapV2 method to increment every item of the scores array by 2</span>
<span class="hljs-keyword">const</span> scoresTimesTwo = scores.mapV2(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">curr, index</span>) </span>{
    <span class="hljs-keyword">return</span> curr * <span class="hljs-number">2</span>;
})

<span class="hljs-comment">// Log the value of scoresTimesTwo to the console.</span>
<span class="hljs-built_in">console</span>.log(scoresTimesTwo)
</code></pre>
<p><strong>Note</strong>: It is important to state that this is by no means a perfect implementation of the original versions of the <code>map</code> method of JavaScript. It is just an attempt to show you what's possible with a constructor's prototype object.</p>
<p>Before we round up this lesson, there's one more thing I need to mention; It is the <code>__proto__</code> property of every object.</p>
<h2 id="heading-the-proto-property">The <strong>proto</strong> Property</h2>
<p><code>__proto__</code> is a setter and getter for [[prototype]] property of an object. This means that it is used to set or get the prototype of an object (for example, the object from which another object inherits from).</p>
<p>Consider this code snippet;</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {}
<span class="hljs-keyword">const</span> scores = []

user.prototype <span class="hljs-comment">// undefined</span>
scores.prototype <span class="hljs-comment">// undefined</span>
</code></pre>
<p>In the above snippet, we tried to access the prototype object directly from values. This is not possible in JavaScript. </p>
<p>This makes sense because only constructors have the <code>prototype</code> property attached to them.</p>
<p>Just like DNA mutation is risky, it could be chaotic to mess with the prototype object if you do not absolutely know what you're doing.  </p>
<p>Under normal circumstances, a child should not try to alter the DNA of its ancestor or even determine who to inherit traits from 😉</p>
<p>The JavaScript language however provides a way for us to access the prototype object from values that are not constructors using the <code>__proto__</code> property.</p>
<p>This is a deprecated method and should not be used for new projects. I am mentioning <code>__proto__</code> because you could be employed to work in a codebase that still uses it.</p>
<p><code>__proto__</code> allows a value to access the prototype object of it's constructor directly. So if for any reason you wish to see what is available in the prototype chain of a value's immediate ancestor, the <code>__proto__</code> property could be used for that.  </p>
<p>You can also use <code>__proto__</code> to determine which object a value should inherit from.</p>
<p>For instance, we have an object called <code>human</code>, and we want another object called <code>parent</code> to inherit from human, this can be done with the <code>__proto__</code> property of parent like this;</p>
<pre><code class="lang-js"><span class="hljs-comment">// Create a human object</span>
<span class="hljs-keyword">const</span> human = {
    <span class="hljs-attr">walk</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">'sleeping'</span>) },
    <span class="hljs-attr">talk</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">'talking'</span>) },
    <span class="hljs-attr">sleep</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">'sleeping'</span>) }
}

<span class="hljs-comment">// Create a parent object and configure it to inherit from human.</span>
<span class="hljs-keyword">const</span> parent = {
    <span class="hljs-attr">__proto__</span>: human
}

<span class="hljs-comment">// Use a method from the ancestor of parent</span>
parent.sleep() <span class="hljs-comment">// sleeping</span>
</code></pre>
<p>Notice how we can call the <code>sleep</code> method on <code>parent</code> because <code>parent</code> now inherits from <code>human</code>.</p>
<p>There are more modern recommended methods to use when interacting with the prototype object like <code>Object.getPrototypeOf</code> and <code>Object.setPrototypeOf</code></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {}
<span class="hljs-keyword">const</span> scores = []

<span class="hljs-comment">// Get the prototype of the user object</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getPrototypeOf(user))

<span class="hljs-comment">// Change the prototype of the scores array. This is like switching ancestry and should be done with great care.</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.setPrototypeOf(scores, {}))

<span class="hljs-comment">// Check the prototype of scores now</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.getPrototypeOf(scores)) <span class="hljs-comment">// {}</span>
</code></pre>
<p>These methods should be used with great care. In fact, you should read more about them in the MDN JS docs to get more information on their pros and cons.</p>
<p>If you've read up to this point, you now know the fundamentals of <code>Array.prototype</code> and from now on, learning about any other concept built on top of this in JavaScript will be easier to understand.  </p>
<p>Let's summarize what you have learned so far.</p>
<h2 id="heading-summary">Summary</h2>
<p>We have different constructors in JavaScript: <code>Array</code>, <code>Boolean</code>, <code>Function</code>, <code>Number</code>, <code>String</code>, and <code>Object</code>.   </p>
<p>Object is the parent of all the other constructors.</p>
<p>Each constructor has a <code>.prototype</code> object and this object contains properties and methods that could be accessed by values created using the constructor. For example, a value created using the <code>Array</code> constructor will have access to all the properties and methods available in the <code>Array.prototype</code> object and this inheritance goes all the way up.  </p>
<p>That is to say, a value created using the <code>Array</code> constructor (whether implicitly or explicitly), will not only have access to properties and methods in the <code>Array.prototype</code> object, but also properties and methods in the <code>Object.prototype</code> object.  </p>
<p>This is because of the concept of prototypal inheritance. <code>Object</code> is parent of <code>Array</code> and every child produced by <code>Array</code> will have access to traits from both <code>Array</code> and <code>Object</code>.</p>
<p>This is what happens when you try to get a property from a value which is not explicitly declared on the value. See code snippet below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> user = {}

<span class="hljs-comment">// trying to retireve .valueOf property from the user object</span>
<span class="hljs-built_in">console</span>.log(user.valueOf)
</code></pre>
<p>Obviously the <code>user</code> object has no <code>.valueOf</code> property, so it looks up its prototype chain for any prototype which has that property and if it is found, the value is returned. Otherwise, we get <code>undefined</code>.</p>
<p>We also learned that we can alter the prototype of any constructor to add functionality and this should be done with caution.</p>
<p>Finally, we learned about how <code>__proto__</code>, <code>getPrototypeOf</code>, and <code>setPrototypeOf</code> could be used to retrieve and set the prototype of a value.</p>
<h3 id="heading-how-is-this-useful">How is This Useful?</h3>
<p>Imagine that you want to create a method which creates a new object based on an array and returns it when called on the array.  </p>
<p>This one's for you to try out yourself.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Array.prototype.toObject</span>
<span class="hljs-keyword">const</span> names = [<span class="hljs-string">'Austin'</span>, <span class="hljs-string">'Tola'</span>, <span class="hljs-string">'Joe'</span>, <span class="hljs-string">'Victor'</span>];

<span class="hljs-comment">// Write your implementation of toObject here.</span>

<span class="hljs-built_in">console</span>.log(names.toObject()) <span class="hljs-comment">// {0: 'Austin', 1: 'Tola', 2: 'Joe', 3: 'Victor'}</span>
</code></pre>
<p>Hurray!!! I know you feel like a JavaScript ninja already.</p>
<p>If you learn better with videos, do subscribe to my <a target="_blank" href="https://www.youtube.com/@asoluka_tee">YouTube</a> channel and I'd be releasing lecture videos soon.</p>
<p>Thanks for reading! Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Do Closures Work in JavaScript? Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Sally and Joe are two love birds. They shared everything with each other and soon enough it was almost impossible to think that anything could come between them. One day, they had a quarrel which built up to a break up.    It was hard for Joe and ]]>
                </description>
                <link>https://www.freecodecamp.org/news/understand-javascript-closures/</link>
                <guid isPermaLink="false">66c37506d0cda7b58da26c34</guid>
                
                    <category>
                        <![CDATA[ closure ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Austin Asoluka ]]>
                </dc:creator>
                <pubDate>Tue, 07 May 2024 07:13:36 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/hand-1222229_1280-2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Sally and Joe are two love birds. They shared everything with each other and soon enough it was almost impossible to think that anything could come between them. One day, they had a quarrel which built up to a break up.   </p>
<p>It was hard for Joe and he wanted "closure". Although Sally already moved on, Joe found closure by taking time to think through the whole experience, recalling "shared memories" and properly introspecting. Even though the relationship had ended, Joe still had something that reminded him of Sally and he was cool with that.</p>
<p>The story ends.</p>
<p>If this is your first time hearing of the term "closure", I'll do you the honor of telling you what it means.  </p>
<p>Closure is simply the act of bringing something to an end. Closure in a relationship refers to the sense of peace and understanding you get after the relationship comes to an end. It's that feeling of "letting go" and being able to move on.  </p>
<p>For some people, getting closure involves holding on to a "shared memory" with the other party, or something (perhaps an item) that reminds them of the other.</p>
<p>Now that you are familiar with the term closure as it relates to humans, let's try to understand it in terms of the relationship between functions in JavaScript.</p>
<p>In JavaScript, a closure is said to be created when a function retains access to resource(s) declared in it's parent scope even after the parent function has been removed from the call stack.</p>
<p><strong>Note</strong>: In JavaScript, when a function is said have been popped-off/removed from the stack, it means that the function has completed its life-span (is done executing), and all of its resources have been removed from memory and are no longer accessible.</p>
<p>Think of the call stack like the world, while parent and child are two entities in the world.</p>
<p>In this case, <code>parent</code> is the function that has completed execution and logically, everything about it should be out of reach. But because of the concept of closure, even when the relationship between the <code>parent</code> and <code>child</code> functions has ended – that is, when the parent gets popped-off the stack (removed from the world) – the child function still remembers everything they shared together.</p>
<p><strong>Note</strong>: Everything they shared together as used above simply means the variables declared in the <code>parent</code> function which are used by the <code>child</code> function.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">parent</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> a = <span class="hljs-string">"Az"</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">child</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(a);
    }
}
</code></pre>
<p>In the code snippet above, the variable <code>a</code> is what the <code>parent</code> and <code>child</code> functions shares together.  </p>
<p>So even when <code>parent</code> gets removed from the call stack, <code>child</code> still remembers the value of <code>a</code> for as long as it lives.</p>
<p>If you stop reading at this point, you already know what closure is conceptually. But if you want to fully understand it and never forget, we'll have to take a deep dive into the workings of JavaScript.</p>
<h2 id="heading-deep-dive-into-the-concept-of-closure">Deep Dive into the Concept of Closure.</h2>
<p>To really understand closures in JavaScript, you have to be familiar with the following concepts:</p>
<ol>
<li><p>The concept of functions being first-class citizens in JavaScript. This means that:</p>
</li>
<li><p>Functions can be assigned to variables as values</p>
</li>
</ol>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> getName = <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">'Allice'</span>   
};
</code></pre>
<p>Now you can simply call the function <code>getName</code> just like you would call any other function using the parenthesis like this <code>getName()</code>  </p>
<p>Think of functions as callable objects. This means, just like we can assign objects to variables and pass them around, you can do same with functions. The difference between them is that you can call a function when you need the code in it to execute.</p>
<ul>
<li>Functions can be passed into other functions as arguments</li>
</ul>
<pre><code class="lang-js"><span class="hljs-built_in">setTimeout</span>(getName, <span class="hljs-number">5000</span>)
</code></pre>
<p>As you can see in the code snippet above, during the invocation of the <code>setTimeout</code> function, we passed the <code>getName</code> function into it as an argument. Again, this is because functions are simply objects that are callable.   </p>
<p>Take note that when we pass the <code>getName</code> function into the <code>setTimeout</code> function, we are not calling/invoking it. We are simply passing the function as a value.   </p>
<p>If we called the function, we'd be passing its return value instead and that's a significant difference there.  </p>
<p>I'd also like to bring to your notice that mentioning the name of a function is simply referencing that function. Behind the scene, the function name gets replaced by the function itself.  </p>
<p>That is, this code <code>setTimeout(getName, 5000)</code> is equivalent to the code below;</p>
<pre><code class="lang-js"><span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Allice'</span>   
}, <span class="hljs-number">5000</span>)
</code></pre>
<p>The function name gets replaced with the function itself during execution just like a regular variable name gets replaced by its value during execution.</p>
<ul>
<li>Functions can be returned from other functions.</li>
</ul>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiplyBy</span> (<span class="hljs-params">numberToMultiplyBy</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">numberToMultiply</span>) </span>{
        <span class="hljs-keyword">return</span> numberToMultiply * numberToMultiplyBy
    }
}
</code></pre>
<p>Taking a close look at the code snippet above, you'll notice that we have a function called <code>multiplyBy</code> which expects an argument during invocation and returns a new function.   </p>
<p>The interesting thing to notice here is that when we call the returned function, it expects an argument too, but this time, it remembers the argument passed into the original <code>multiplyBy</code> function ( <code>numberToMultiplyBy</code> ), then multiplies the value passed into itself ( <code>numberToMultiply</code> ) with the value passed into its parent function, and returns the result.  </p>
<p>Carefully observe the code below which makes use of the higher-order function <code>multiplyBy</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> multiplyByTwo = multiplyBy(<span class="hljs-number">2</span>)
<span class="hljs-keyword">const</span> result = multiplyByTwo(<span class="hljs-number">8</span>)

<span class="hljs-built_in">console</span>.log(result) <span class="hljs-comment">// 16</span>
</code></pre>
<ol start="2">
<li>The concept of Higher-order functions: This is the second concept you need to be aware of to understand closure.</li>
</ol>
<p>A higher order function is a function which:</p>
<ul>
<li>Accepts a function as an argument. For example: <code>setTimeout</code>, <code>Promise</code>, and so on.</li>
<li>Returns a function. For example: <code>multiplyBy</code> function declared above.</li>
<li>Or fulfils the first and second items above.</li>
</ul>
<p>Now that you understand that functions are first-class citizens and you've seen implementations of a higher-order function, we can proceed to talk about closures.</p>
<p>Recall that a closure occurs when a child function holds reference to/remembers a value or resource which belonged to its parent function even after the parent function has been removed from the call stack.</p>
<p>Consider this code:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sally</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> age = <span class="hljs-number">64</span>;

    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">joe</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">const</span> data = {
            <span class="hljs-attr">name</span>: <span class="hljs-string">"Joe"</span>,
            <span class="hljs-attr">parentName</span>: <span class="hljs-string">"Sally"</span>,
            <span class="hljs-attr">parentAge</span>: age
        }
        <span class="hljs-keyword">return</span> data
    }
}
</code></pre>
<p>In the code snippet above, we can observe that:</p>
<ul>
<li><code>sally</code> is the parent function and it declares a scope</li>
<li><code>age</code> is a variable declared within the <code>sally</code> scope</li>
<li><code>joe</code> is a function which lives in the <code>sally</code> scope and is returned by the <code>sally</code> function. You should also note that:  </li>
<li><code>joe</code> defines its own scope which is a child scope of the <code>sally</code> scope  </li>
<li>within the <code>joe</code> scope, we make reference to the variable <code>age</code> which belongs to <code>sally</code> scope (this is where closure happens because <code>joe</code> is referring or holding on to a resource/variable which belongs to <code>sally</code>).</li>
</ul>
<p>Because <code>joe</code> holds a reference to the variable <code>age</code> which belongs to <code>sally</code>, even when <code>sally</code> has been popped-off the call stack and its scope discarded, <code>joe</code> will retain access to the <code>age</code> variable because of the concept of closure.</p>
<p>So in the code below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> joe = sally() <span class="hljs-comment">// sally is invoked and returns the joe function</span>
<span class="hljs-keyword">const</span> joeyData = joe() <span class="hljs-comment">// joe function is invoked and returns an object</span>

<span class="hljs-built_in">console</span>.log(joeyData) <span class="hljs-comment">// we log the object returned.</span>
</code></pre>
<p>You can observe that even though <code>sally</code> is called and popped-off the stack, when you invoke <code>joe</code> and log the return value of <code>joe</code> to the console, it still remembers the <code>age</code> of sally during the execution (which we can access in the returned object like so <code>joeyData.parentAge</code>).</p>
<h2 id="heading-summary">Summary</h2>
<p>When a child function refers to variables used in its parent scope, closure occurs.<br>Closure is like a memory box which stores all the items of the parent scope that are referred to from the child scope.</p>
<p>A look at the slides below should cement the knowledge you've gained so far and hopefully everything will fall in place.</p>
<div class="embed-wrapper"><iframe class="speakerdeck-iframe" src="https://speakerdeck.com/player/361482321f264b4aa170e04776365956" style="border:0px;background:padding-box padding-box rgba(0, 0, 0, 0.1);margin:0px;padding:0px;border-radius:6px;box-shadow:rgba(0, 0, 0, 0.2) 0px 5px 40px;width:100%;height:auto;aspect-ratio:560 / 432" title="Embedded content" loading="lazy"></iframe></div>

<p>Closures unlocked? Level up your JavaScript skills with more full-stack development tutorials on my <a target="_blank" href="https://www.youtube.com/@asoluka_tee">YouTube</a> channel. Subscribe now for my next playlist on fundamental JavaScript concepts!</p>
<p>Thanks for reading! Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
