<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ajo John on Medium]]></title>
        <description><![CDATA[Stories by Ajo John on Medium]]></description>
        <link>https://medium.com/@ajomadlabs?source=rss-4ab206bad4df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MIkzU98KPxd_oGQQHnoUJg.png</url>
            <title>Stories by Ajo John on Medium</title>
            <link>https://medium.com/@ajomadlabs?source=rss-4ab206bad4df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:41:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ajomadlabs/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Demystifying JavaScript Arrow Functions]]></title>
            <link>https://javascript.plainenglish.io/demystifying-javascript-arrow-functions-7b2a0908a2b3?source=rss-4ab206bad4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b2a0908a2b3</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Ajo John]]></dc:creator>
            <pubDate>Mon, 27 Sep 2021 13:52:23 GMT</pubDate>
            <atom:updated>2021-09-27T13:52:23.421Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wOZ5FwJVP9bNa9G9Ym1V4A.png" /></figure><p>The arrow function is an alternative to function expressions with a difference in syntax and cannot be used in all cases. If you haven’t read about function expressions in JavaScript yet, I would recommend you to read <a href="https://themallu.dev/demystifying-function-expressions"><strong>this</strong></a> before continuing any further.</p><p>Now, let’s try to understand an arrow function with respect to its <strong>syntax, execution, scope, and hoisting</strong> along with code examples.</p><h3>1. Syntax</h3><pre>const arrowFunctionSyntax = () =&gt; {<br> console.log(“Hi, I am an arrow function”);<br>}<br>arrowFunctionSyntax();</pre><p>In the above code example, we can see that the arrow function is similar to function expressions as they are being assigned as a value to a variable. The major difference is the way in which the function is written. Following are the observations from the above code that we can make based on its syntax:</p><p>1. It does not contain the <strong>function</strong> keyword.<br>2. It does not have a <strong>function name</strong> which means that these are anonymous functions.<br>3. An arrow <strong>=&gt;</strong> symbol is being introduced</p><pre>const arrowFunctionWithOneParam = number =&gt; number + 1;<br>const arrowFunctionWithMultipleParams = (numberOne, numberTwo) =&gt; {<br> let sum = numberOne + numberTwo;<br> return sum;<br>}<br>console.log(arrowFunctionWithOneParam(5));<br>console.log(arrowFunctionWithMultipleParams(5,6))</pre><p>If we observe both `<strong>arrowFunctionWithOneParam</strong>` and `<strong>arrowFunctionWithMultipleParams</strong>`, we can find difference in three things — parenthesis `<strong>()</strong>`, block `<strong>{}</strong>` and the usage of `<strong>return</strong>` keyword. According to the syntax of arrow function, parenthesis`<strong>()</strong>` can be ignored if the function just accepts one parameter, block`<strong>{}</strong>` can be ignored if the function contains only a single statement and finally the `return` can also be ignored if the function contains only a single statement.</p><h3>2. Execution</h3><pre>const arrowFunctionExecution = () =&gt; {<br> console.log(“Hi, my execution is similar to normal function”);<br>}<br>arrowFunctionExecution();</pre><p>When it comes to the execution of an arrow function, they execute in a similar manner as that of any normal function. When the JS engine executes `<strong>arrowFunctionExecution()</strong>`, it creates a function execution context and gets pushed to the call stack. As soon as the execution context is created, it initiates the creation phase. In this phase, it will create the arguments object and declare all the variables in its local memory heap. The major difference, when compared to the normal function, is the declaration of `<strong>this</strong>`. An arrow function does not have a `<strong>this</strong>` variable of its own; `this` when used inside an arrow function gets lexically resolved. Soon after the creation phase, the execution phase get’s initiated. This is the phase where it executes the statement `<strong>console.log()</strong>` and prints `<strong>“Hi, my execution is similar to normal function”</strong>` to the console.</p><h3>3. Scope</h3><pre>const arrowFunctionScope = () =&gt; {<br> console.log(“Hi, my scoping rules works similar to function expression”)<br>}</pre><p>These functions follow the same scoping rules as that of any function expression. These functions have their own scope and any variables declared inside the function cannot be accessed outside the function. These functions are also not suitable for `<strong>call</strong>`, `<strong>apply</strong>` and `<strong>bind</strong>` methods, which generally rely on establishing scope. If in case you haven’t read about scopes in javascript yet, I would recommend you to read <a href="https://themallu.dev/demystifying-scopes"><strong>this</strong></a><strong>.</strong></p><h3>4. Hoisting</h3><pre>amIGoingToBeHoisted();<br>var amIGoingToBeHoisted = () =&gt; {<br> console.log(“The answer is NO”);<br>}</pre><p>Arrow functions are not hoisted as they are also function expressions where the function is assigned as a value to the variable. When the JavaScript engine executes the above code, in the creation phase the declaration statement `<strong>var amIGoingToBeHoisted</strong> ` will be moved to the top and initialised with a value `<strong>undefined</strong>`, leaving the initial value behind. During the execution phase, it will throw a type error when it encounters the statement `<strong>amIGoingToBeHoisted</strong>` as its value is undefined, which is not a function type after hoisting. To know more about hoisting in JavaScript, I would recommend you to read <a href="https://themallu.dev/demystifying-hoisting"><strong>this</strong></a>.</p><p>I hope this clears up how arrow functions work in JavaScript. If you feel this article was useful, please do show your love and share this with your fellow beings. Always feel free to connect with me on <a href="https://twitter.com/ajojm"><strong>Twitter</strong></a>, <a href="https://www.linkedin.com/in/ajojohn/"><strong>LinkedIn</strong></a>, or via email.</p><p>Until we meet again, <strong>The Mallu Dev</strong> signing off 👋 Cheers! 🥂</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b2a0908a2b3" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/demystifying-javascript-arrow-functions-7b2a0908a2b3">Demystifying JavaScript Arrow Functions</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying JavaScript Function Expressions]]></title>
            <link>https://javascript.plainenglish.io/demystifying-javascript-function-expressions-4135a64b4c65?source=rss-4ab206bad4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/4135a64b4c65</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ajo John]]></dc:creator>
            <pubDate>Wed, 22 Sep 2021 11:48:01 GMT</pubDate>
            <atom:updated>2021-09-22T11:48:01.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kNb2c_miYzjEJbroYQTpWQ.png" /></figure><p>Functions that are assigned as values to variables are called <strong>function expressions</strong>. If you haven’t read about functions in JavaScript yet, I would recommend you to read <a href="https://themallu.dev/demystifying-functions-in-js"><strong>this</strong></a> before continuing further. Let’s try to understand function expression with the help of an example.</p><pre>var counter = 0<br>var incrementCounterAndPrint = function () {<br>  counter++;<br>  console.log(&quot;Incremented Counter&quot;, counter);<br>}<br>incrementCounterAndPrint()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9mcqx2esgNQ0ngMDUjFkg.png" /></figure><p>When the JS engine encounters this code, at first it creates a global execution context and initiates the creation phase. During the creation phase, it will go through all the declaration statements and place them in the memory. In this case, variables, `<strong>counter</strong>` and `<strong>incrementCounterAndPrint</strong>` will be stored in the memory with a default value, `undefined` assigned to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2sq_bfO0b1Ja9SkVU3K4w.png" /></figure><p>As there are no more declaration statements, it will move to the second phase, which is the execution phase. The execution phase is the phase in which the code is executed line by line. In this case, at first, `<strong>counter</strong>` will be assigned to a value `<strong>0</strong>` and `incrementCounterAndPrint` will be assigned with the entire function as the value. When the JS engine encounters the statement `<strong>incrementCounterAndPrint()</strong>`, it will first check the memory whether this particular variable is present or not. As it is present, it will fetch the value from the memory and execute it. On executing the function, the function `<strong>incrementCounterAndPrint</strong>` will be pushed to the call stack and a new function execution context is created. As soon as the execution context is created, it will initiate the creation phase. As there are no declaration statements as such, it will move to the second phase called the execution phase. In this phase, at first, the JS engine will execute the statement `<strong>counter++</strong>`. While executing, it will check whether the variable is present in the local memory, as its not present, it will move to the global execution context and check it’s memory. As soon as it finds the variable, it will execute the operation and move to the next line. On executing the statement `<strong>console.log(‘Incremented Counter’, counter)</strong>`, it will print the value `<strong>1</strong>` to the console.</p><p>Now, the obvious question is whether function expressions are hoisted? Well, let’s check this by tweaking the above code.</p><pre><br>var counter = 0<br>incrementCounterAndPrint() // TypeError: incrementCounterAndPrint is not a function<br>var incrementCounterAndPrint = function () {<br> counter++;<br> console.log(“Incremented Counter”, counter);<br>}</pre><p>When the JS engine runs the above code it will throw a type error. Can you tell me why this happens? Well, if we try to observe the code, we can see that function is being assigned as a value to the variable `<strong>incrementCounterAndPrint</strong>`. In the creation phase as per the hoisting feature, all the variable declarations will be moved to the top leaving the values assigned to it behind. In this case, `<strong>incrementCounterAndPrint</strong>` will be moved to the top leaving the function code-behind, and will be set with a value `<strong>undefined</strong>` by default as it was declared using `<strong>var</strong>`. When the JS engine encountering the statement `<strong>incrementCounterAndPrint()</strong>` will first check the memory for the variable. As it’s present, it will fetch the value that is stored which is `<strong>undefined</strong>`. Since undefined is not a `<strong>function</strong>` type, it will throw a type error. This brings us to the conclusion that function expressions are not hoisted. Function expressions have their scope. Function expressions generally are anonymous but we could also have it named, which helps a lot in debugging.</p><p>So what about arrow functions ???. Well, I will be soon covering that in detail in my next blog, hold tight. Till then, if you feel this article was useful, please do show your love and share this with your fellow beings via your social media who could make maximum use of this. Always feel free to connect with me on <a href="https://twitter.com/ajojm"><strong>Twitter</strong></a>, <a href="https://www.linkedin.com/in/ajojohn/"><strong>LinkedIn</strong></a>, or email.</p><p>Until we meet again, <strong>The Mallu Dev</strong> signing off 👋 Cheers! 🥂</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4135a64b4c65" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/demystifying-javascript-function-expressions-4135a64b4c65">Demystifying JavaScript Function Expressions</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Functions in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/demystifying-functions-in-javascript-791d7d66e72f?source=rss-4ab206bad4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/791d7d66e72f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ajo John]]></dc:creator>
            <pubDate>Mon, 20 Sep 2021 14:33:05 GMT</pubDate>
            <atom:updated>2021-09-20T14:33:05.107Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Pl10Gz3MGuxjC__ofIu4g.png" /></figure><p>Functions are small programs in themselves that help to increase the readability and reusability of our code. Functions have their own execution context where the entire code present in the function gets executed. Similar to the global execution context, the function execution context also consists of two phases — The creation Phase and the Execution Phase. Creation Phase is the phase in which arguments object will be created, this variable is declared and referenced to the Global Object and finally creating and storing all the other variables in the function to the memory heap. The execution phase is the phase in which all the variables will be assigned to their actual values and functions will be executed. Now let’s try to dig deep with the help of an example.</p><pre><br>function printIcecreamFlavour(flavour) {<br> console.log(`Icecream ${flavour}:`);<br>}<br>function calculateCost(price, numberOfIcecreams) {<br> return price * numberOfIcecreams;<br>}<br>printIcecreamFlavour(“Vanilla”);<br>var price = calculateCost(10, 5);<br>console.log(price);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ncyun1v8_mMqhS4PnaK6RQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQ607rbzeEPhR6PzY7FgGg.jpeg" /></figure><p>When the Javascript engine runs the above code, at first it will create a global execution context. Global execution context would contain two parts — one part would contain the entire code and the other part would be the place where the variables and functions are stored. After the execution context is created, the creation phase get’s initiated. During this phase, functions <strong>printIcecreamFlavour</strong> and <strong>calculateCost</strong> gets stored in the memory with their respective function codes as their values while the variable <strong>price</strong> will be stored in the memory with <strong>undefined</strong> as it’s default value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LakkOcxFdPfYbpU08kY9ng.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eolHDbw8Ho04niW0oEdvOA.jpeg" /></figure><p>Soon after the creation phase, the execution phase get’s initiated. During this phase, the JS engine executes the code line by line. As soon as it encounters line 8, it checks whether this identifier is present in the local memory, if it’s present, it will get the value which in this case would be the entire function code and executes it. As soon as the JS engine executes the function, it will push the function to the call stack and creates a new execution context for the function <strong>printIcecreamFlavour</strong>. This execution context will be containing two parts — one part where the function code will reside and the other part where all the variables and functions will be stored. Soon after the execution context is created, the creation phase gets initiated. In this phase, the arguments object will be created, containing the values passed to the function. Since there are no more declaration statements, it moves to the execution phase. In this phase, as it encounters the <strong>console.log(`Icecream ${flavour}`)</strong>, it will first check whether there is an identifier called console present in the local memory or not. As it is not present in the local memory, it will move to the global execution context and check its memory. This works based on the scope rules defined in Javascript. If you are struggling to understand how scope works in JS, you can check <a href="https://themallu.dev/demystifying-scopes"><strong>this</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dz-PvVkQL0_8KeOWnsoXBA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*34Q3p_hILKYZLkI6-yKYKQ.jpeg" /></figure><p>As it finds the object <strong>console</strong>, it will search for the method <strong>log</strong> defined in the object and execute the <strong>log</strong> function in a similar fashion where the log function is pushed to the call stack and a new execution context for the <strong>log</strong> function is created. On executing the function, <strong>Icecream Vanilla</strong> will be printed on the console. Soon after the execution, the execution context of the <strong>log</strong> will be deleted and popped from the call stack. Since there are no more statements left to be executed in <strong>printIcecreamFlavour</strong> function, the execution context of <strong>printIcecreamFlavour</strong> will be deleted and popped from the call stack. Now the current execution context will be the global execution context and the JS engine will continue executing the next statement. When it encounters the statement <strong>var price = calculateCost(10, 5)</strong>, it will first check for the identifier <strong>price</strong>. As it’s present, it will assign the value of <strong>calculateCost</strong>. As <strong>calculateCost</strong> is a function, the price will be assigned only a value after the completion of <strong>calculateCost</strong> function. When <strong>calculateCost</strong> is executed, the function will be pushed to the call stack and a new execution context will be created for <strong>calculateCost</strong>. Similar to the previous function at first the creation phase gets initiated. During this phase, the arguments object will be created which would contain the values of price and <strong>numberOfIcecreams</strong> that are passed as arguments into the function. Since there are no more declaration statements, it starts the execution phase. During this phase, the JS engine starts executing the code line by line. As soon as it encounters the statement <strong>return price * numberOfIcecreams</strong>, it will get the value of <strong>price</strong> and <strong>numbeOfIcecreams</strong> from the memory, evaluate the expression <strong>price * numberOfIcecreams</strong> and return that value which is then assigned to the variable <strong>price</strong>.</p><p>As there are no more statements to be executed in the function, the function execution context will be destroyed and <strong>calculateCost</strong> function will be popped from the call stack where the global execution context would be the current execution context. Now JS engine proceeds to the next statement which would be the <strong>console.log(price)</strong>. On executing this, it will fetch the value of <strong>price</strong> from the memory and print it to the console. As there are no more statements to be executed, the JS engine will destroy the global execution context and pop it from the call stack.</p><p>So what about function expression ???. Well, I will be soon covering this in detail in my next blog, hold tight. Till then, if you feel this article was useful, please do show your love and share this with your fellow beings via your social media who could make maximum use of this. Always feel free to connect with me on <a href="https://twitter.com/ajojm"><strong>Twitter</strong></a>, <a href="https://www.linkedin.com/in/ajojohn/"><strong>LinkedIn</strong></a> or email.</p><p>Until we meet again, <strong>The Mallu Dev</strong> signing off 👋 Cheers! 🥂</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=791d7d66e72f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/demystifying-functions-in-javascript-791d7d66e72f">Demystifying Functions in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Demystify Hoisting in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/lets-demystify-hoisting-in-javascript-84e18b9f6569?source=rss-4ab206bad4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/84e18b9f6569</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ajo John]]></dc:creator>
            <pubDate>Thu, 16 Sep 2021 10:56:05 GMT</pubDate>
            <atom:updated>2021-09-16T10:56:05.975Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is hoisting in JavaScript and how does it work?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o6nKc31zj_yGBhuzMUYAgA.png" /></figure><p>Hoisting is a feature in JavaScript which moves all the variable and function declarations to the top of the code (this statement doesn’t mean that the code is physically moved to the top.). As we all know, the JavaScript engine creates an <em>execution context</em> where it runs the JavaScript code.</p><p>There are two phases in the execution contexts — the creation phase and the execution phase. The creation phase is the phase where hoisting takes place. Now, let’s try to understand how hoisting works with the help of examples.</p><h3>Variable Hoisting</h3><p>JavaScript has three ways with which we could declare variables. They are <strong>var</strong>, <strong>let,</strong> and <strong>const</strong>. Each of them is different from the other in terms of usage, scope, and hoisting. You could read more about variable declaration over <a href="https://themallu.dev/demystifying-var-let-and-const">here</a>. The important point to note here is that, during variable hoisting, only the variable declaration part will be moved to the top of the code leaving the assigned value behind.</p><h3>Case 1</h3><pre><br>console.log(icecream); // Prints undefined<br>var icecream = “Vanilla”;<br></pre><p>In the above code snippet, we are trying to use the variable even before declaring it. This looks like it will throw an error. But does it? This is where hoisting comes into the picture.</p><p>The JavaScript engine on running this code at first creates an execution context. As soon as the execution context is created, it begins with the creation phase. During the creation phase, the engine parses the code, splits the declarations and initialisations into two statements and moves all the declarations to the top of the code. All the variables declared using the <strong>var</strong> keyword will be initialised with a default value <strong>undefined</strong> when they are hoisted. This is the reason why it prints <strong>undefined</strong> rather than an error when JavaScript executes the above code.</p><h3>Case 2</h3><pre><br>console.log(icecream); // Prints ReferenceError: icecream is not defined<br>let icecream = “Vanilla”;</pre><p>When the JavaScript engine executes the above code, it throws a reference error. Why does this happen? Shouldn’t it print <strong>undefined</strong>? Are <strong>let</strong> declared variables really hoisted? Well, <strong>let</strong> variables are also hoisted but they are a little different when compared with <strong>var</strong>.</p><p>The JavaScript engine on running this code creates an execution context. As soon as the execution context is created, it begins with the creation phase. During the creation phase, the engine parses the code, splits the declarations and initialisations into two statements and moves all the declarations to the top of the code.</p><p>Now comes the difference: all the variables that are declared using the <strong>let</strong> keyword will not be having a default value like that of <strong>var</strong>; instead, they will be marked as being in the <strong>TDZ (Temporal Dead Zone)</strong> mode when they are hoisted. This just means that the variables do exist, but they are not accessible until they are initialised with a value. This is the reason why JavaScript throws a reference error when <strong>let</strong> declared variables are hoisted.</p><h3>Case 3</h3><pre><br>console.log(icecream); // Prints ReferenceError: icecream is not defined<br>const icecream = “Vanilla”;<br></pre><p>What about <strong>const</strong> declared variables? Well, const variables are also hoisted and they work exactly the same way as that of <strong>let</strong> in terms of hoisting. This is the reason why we get the same error when <strong>const</strong> declared variables are also hoisted.</p><h3>Function Hoisting</h3><p>Hoisting in which the function declaration will be moved to the top of the code is known as function hoisting.</p><h3>Case 1</h3><pre><br>getIcecream(); // Prints Vanilla Icecream<br>function getIcecream() {<br> console.log(“Vanilla Icecream”),<br>}<br></pre><p>The JavaScript engine on running the above code creates an execution context and starts the creation phase. During the creation phase, it moves all the variable and function declarations to the top of the code. In this case, function declaration <strong>getIcecream</strong> would be moved to the top of the code. Soon after the creation phase, the execution phase get’s started where the code will be executed. Since the function <strong>getIcecream</strong> was already declared during the creation phase, calling <strong>getIcecream</strong> would print the expected output rather than an error.</p><h3>Case 2</h3><pre><br>icecream(); // Prints TypeError: icecream is not a function<br>var icecream = function () {<br> console.log(“Vanilla Icecream”)<br>}<br></pre><p>The JavaScript engine on running the above code creates an execution context and starts the creation phase. During the creation phase, it moves all the variable and function declarations to the top of the code. In this case, <strong>var icecream</strong> is assigned to a function, this statement is called a function expression. As the engine identifies the <strong>var variable</strong> icecream, it moves the declaration to the top of the code and assigns a default value <strong>undefined</strong>, leaving the function code behind. During the execution phase, when it encounters the statement <strong>icecream()</strong>, it will throw a type error as the engine expected a function but instead got an undefined. This is the reason why function expressions are not hoisted. What about arrow functions? Well, the same thing applies in the case of arrow functions too. This means that arrow functions are also not hoisted.</p><p>I hope this clears how hoisting works in JavaScript. If you feel this article was useful, please do show your love and share this with your fellow beings via your social media who could make maximum use of this. Always feel free to connect with me on <a href="https://twitter.com/ajojm">Twitter</a>, <a href="https://www.linkedin.com/in/ajojohn/">LinkedIn</a>, or througbh email.</p><p>Until we meet again, <strong>The Mallu Dev</strong> signing off 👋 Cheers! 🥂</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84e18b9f6569" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/lets-demystify-hoisting-in-javascript-84e18b9f6569">Let’s Demystify Hoisting in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying ‘var,’ ‘let’ and ‘const’ in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/demystifying-var-let-and-const-in-javascript-9a241615d3a1?source=rss-4ab206bad4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a241615d3a1</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ajo John]]></dc:creator>
            <pubDate>Tue, 14 Sep 2021 11:12:48 GMT</pubDate>
            <atom:updated>2021-09-14T11:12:48.259Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ATtUW0s_CNSCbKicychxag.png" /></figure><p>JavaScript is a dynamically typed language. Dynamically typed languages are those languages, where the type of the variable purely depends on the type of the value that is being stored inside the variable. For example, if the type of the value is a String, then the type of the variable would also be a String.</p><p>There are currently three ways in which we can declare variables in JavaScript. They are — var, let and const. All three are different from each other either with respect of usage, scope or hoisting. Let’s try to understand each of these with the help of an example.</p><h3>Case One — var</h3><h4>Usage</h4><pre><br>“use strict”<br>var variableWithVar = 5;<br>var variableWithVar;<br>console.log(variableWithVar); // Prints 5<br></pre><p><strong>var</strong> is a special keyword which is used to declare variables as shown above. Duplicate variable declarations would not cause any error even in strict mode(<strong>use strict</strong>) and the value would not be lost unless a new value is assigned to that variable.</p><h4>Scope</h4><p>In terms of scope, <strong>var</strong> declarations are function scoped if declared inside a function, otherwise, it would be treated as global variables, which are stored inside the global object. These are also added to a list on the internal names <strong>[[VarNames]]</strong> slot on the global environment record. Function scoped variables are those variables, which would be accessible only inside the functions where they are declared.</p><pre><br>// Example One<br>function varScope() {<br> var variableWithVar = 1;<br> console.log(“Inside Function”, variableWithVar);<br>}<br>varScope() // Prints ‘Inside Function’ 1<br>console.log(“Outside Function”, variableWithVar) // ReferenceError: variableWithVar is not defined<br></pre><pre><br>// Example Two<br>var variableGlobal = 5;<br>function varScopeTwo() {<br> console.log(“Inside Function”, variableGlobal);<br>}<br>varScopeTwo() // Prints ‘Inside Function 5’<br></pre><p>In the above code snippets, Example One is a clear example of <strong>var</strong> being function scoped while Example Two is a clear example of <strong>var</strong> being a global variable.<br> <br><strong>Hoisting</strong></p><p>In terms of hoisting, all the variables declared using the <strong>var</strong> keyword will be hoisted. The concept of hoisting is that all the declaration statements will be moved to the top, even before any code is executed. The important thing to remember is that, only the variable declarations will be hoisted and not their values. All the variable declarations after hoisting, will be assigned a value <strong>undefined, </strong>because of which, it is always recommended to declare the variables before even using it.</p><pre><br>console.log(variableWithVar); // Prints ‘undefined’<br>var variableWithVar = 5;<br></pre><p>In the above code snippet, at first, Javascript parses the code during which, all the declaration statements will be hoisted. In this case, <strong>var variableWithVar</strong> will be moved to the top and will be assigned with the value <strong>undefined</strong>. As there are no more declaration statements, it moves to the code execution phase where it executes the <strong>console.log()</strong> statement. On execution, it searches for the variable, <strong>variableWithVar</strong> in the global memory. As soon as it finds it, it passes the value as an argument to the <strong>console.log()</strong> method. Since the value of <strong>variableWithVar</strong> was undefined, it prints <strong>undefined</strong></p><h3>Case Two — let</h3><h4>Usage</h4><pre><br>let variableWithLet = 5;<br>console.log(variableWithLet); <br>let variableWithLet;</pre><pre>// Output<br>/*<br>SyntaxError: Identifier ‘variableWithLet’ has already been declared. (3:4)<br>*/<br></pre><p><strong>let</strong> is a special keyword which is used to declare variables as shown above. Duplicate variable declarations would throw error as shown in the above code snippet. Variables declared using <strong>let</strong> can be re-assigned similar to <strong>var</strong>.</p><h4>Scope</h4><p>In terms of scope, <strong>let</strong> declarations are block scoped. Blocks are represented with the help of <strong>{}</strong>. Block scoped variables are those, which would be accessible only inside the blocks where they are declared. In simple terms, any blocks (<strong>{}</strong>) are turned into a block scope, if any of the variables inside the block are declared using <strong>let</strong>. Unlike <strong>var</strong>, <strong>let</strong> does not create a property in the global object.</p><pre><br>// Example One<br>function exampleOne() {<br> let one = 1;<br> console.log(one);<br>}<br>exampleOne() // Prints 1<br>console.log(one) // ReferenceError: one is not defined<br></pre><p>In the above code snippet, <strong>exampleOne</strong> is a function, where the body of the function is present inside the <strong>{}</strong>. Declaring any variables using <strong>let</strong> inside this function will make it block scoped. <strong>console.log(one)</strong> throws an error as we are trying to access the variable <strong>one</strong> outside the block of <strong>exampleOne</strong>.</p><pre><br>// Example Two<br>{<br> let one = 1;<br> console.log(one) // Prints 1<br>}<br>console.log(one) // Prints ReferenceError: one is not defined<br></pre><p>The above code snippet is a clear example which show that <strong>let</strong> converts any blocks(<strong>{}</strong>) into scoped block where any variables declared using <strong>let</strong>, can only be accessed inside that block and not anywhere else.</p><pre><br>// Example Three<br>function letScope() {<br> let outsideOne = 1;<br> if(true) {<br> let insideOne = 2;<br> console.log(insideOne) // Prints 2<br> console.log(outsideOne) // Prints 1<br> }<br> console.log(insideOne) // Prints ReferenceError: insideOne is not defined<br>}<br>letScope()<br></pre><p>In the above code snippet, on executing the <strong>letScope()</strong> function, <strong>if(){}</strong> statement present inside the function turns to be block scoped as the variables inside the block are declared using <strong>let.</strong> <strong>console.log(insideOne)</strong> prints <strong>2</strong>, as <strong>insideOne</strong> is in the same scope. <strong>console.log(outsideOne)</strong> prints <strong>1</strong> by following the rules of lexical scoping, where the child function can access the variables of it’s parent functions. On executing the <strong>console.log(insideOne)</strong> statement present outside the <strong>if</strong> block, Javascript throws a reference error as we are trying to access <strong>insideOne</strong> variable outside the <strong>if</strong> block.</p><pre><br>// Example Four<br>var one = 1;<br>let two = 2;<br>console.log(this.one) // Prints 1;<br>console.log(this.two) // Prints undefined;<br></pre><p>The above code snippet is a clear example which shows that <strong>let </strong>does not create a property in the global Object.</p><h4>Hoisting</h4><p>In terms of hoisting, all the variables declared using the <strong>let</strong> keyword will be hoisted. During hoisting, all the <strong>let</strong> declarations moves to the top of the code. Unlike <strong>var</strong>, <strong>let</strong> variables cannot be used (read/write) till they are fully initialised. They become fully initialised only when they are initialised with a value. Accessing <strong>let</strong> variables before initialisation throws a Reference Error.</p><pre><br>console.log(one); // ReferenceError: one is not defined<br>let one = 1;<br></pre><p><strong>let</strong> variables are said to be inside the <strong>Temporal Dead Zone(TDZ)</strong> till they are completely initialised. <strong>Temporal Dead Zone</strong> is the time period in which the variables are declared but are not accessible since they are not set with a value. This happens when <strong>let</strong> variables are hoisted. <strong>var</strong> variables on the other hand, are by default set to a value <strong>undefined</strong> during hoisting.</p><pre><br>{ <br> // TDZ of one starts<br> console.log(two); // Prints undefined<br> console.log(one); // Prints ReferenceError: Cannot access ‘one’ before initialisation<br> var two = 1;<br> let one = 2; // TDZ of one ends<br>}<br></pre><p>In the above code snippet, the Javascript engine parses the code and moves all the variable declarations to the top — <strong>var two = undefined</strong> and <strong>let one</strong>. This marks the start of TDZ as the variable <strong>one</strong> is not completely initialised with a value. Now, as the javascript enters the execution phase, it prints <strong>undefined</strong> for the <strong>console.log(two)</strong> statement and throws an error for <strong>console.log(one)</strong> as the <strong>let</strong> variables cannot be accessed till they are completely initialised.</p><h3>Case Three — const</h3><p><strong>Usage</strong></p><pre><br>const variableWithConst = 5;<br>console.log(variableWithConst); // Prints 5<br>variableWithConst = 6;<br>console.log(variableWithConst); // Prints TypeError: Assignment to constant variable.<br></pre><p><strong>const</strong> is a special keyword which is used to declare variables as shown above. Duplicate variable declarations and re-assigning values to a <strong>const</strong> variable would throw a reference and type error respectively as shown above.</p><h4>Scope</h4><p>In terms of scope, <strong>const</strong> declarations are also block scoped which is same as that of <strong>let</strong>.</p><pre><br>// Example One<br>function exampleOne() {<br> const one = 1;<br> console.log(one);<br>}<br>exampleOne() // Prints 1<br>console.log(one) // ReferenceError: one is not defined<br></pre><p>In the above code snippet, <strong>exampleOne</strong> is a function, where the body of the function is present inside the <strong>{}</strong>. Declaring any variables using <strong>const</strong> inside this function will make it block scoped. <strong>console.log(one)</strong> throws an error, as we are trying to access the variable <strong>one</strong> outside the block of <strong>exampleOne</strong>.</p><h4>Hoisting</h4><p>In terms of hoisting, all the variables declared using the <strong>const</strong> keyword will be hoisted, which is same as that of <strong>let</strong>.</p><pre><br>console.log(one); // ReferenceError: one is not defined<br>const one = 1;<br></pre><p>The <strong>const</strong> variables are also said to be inside <strong>Temporal Dead Zone (TDZ)</strong> till they are completely initialised which is exactly the same as that of <strong>let</strong>. This happens when <strong>const</strong> variables are hoisted.</p><p>I hope this clears how var, let and const declarations work with respect to usage, scope and hoisting. If you feel this article was useful, please do show your love and share this with your fellow beings via your social media who could make maximum use of this. Always feel free to connect with me on <a href="https://twitter.com/ajojm">Twitter</a>, <a href="https://www.linkedin.com/in/ajojohn/">LinkedIn</a>, or email.</p><p>Until we meet again, <strong>The Mallu Dev </strong>signing off 👋 Cheers! 🥂</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a241615d3a1" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/demystifying-var-let-and-const-in-javascript-9a241615d3a1">Demystifying ‘var,’ ‘let’ and ‘const’ in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying JavaScript Scope]]></title>
            <link>https://javascript.plainenglish.io/demystifying-javascript-scope-abdbe68914fd?source=rss-4ab206bad4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/abdbe68914fd</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Ajo John]]></dc:creator>
            <pubDate>Sun, 12 Sep 2021 07:57:23 GMT</pubDate>
            <atom:updated>2021-09-12T07:57:23.998Z</atom:updated>
            <content:encoded><![CDATA[<p>Scopes are properties of name bindings which tells us what and which are the name bindings that are accessible at a particular part of the program or at a given point of time. Name bindings refers to the name associated with an entity. Entity could be a variable, a function etc. The rules that define these scopes are called scope rules.</p><p>Generally, there are two types of Scopes — Lexical Scope and Dynamic Scope. Lexical Scope resolves the name bindings based on where they are defined (lexical context) and their location in the source code. Dynamic Scope resolves the name bindings based on the program state, which is determined by the execution context (runtime context).</p><p>JavaScript is a lexically scoped language. All the names which are associated with variables, functions etc are resolved based on where they are defined and what is their location in source code.</p><p>Normally in lexical scope, the child functions searches the names in the local lexical context, if it fails, it moves to the outer function and searches its local lexical context.</p><p>This continues until it reaches the outermost function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*utpTdIvo4yxGWmmVeyL-cA.jpeg" /></figure><p>The above image is a clear representation of lexical scoping, where <strong>Function C</strong> can access all the variables present in <strong>Function C, Function B, Function A and Global Function</strong>; <strong>Function B</strong> can access all the variables present in <strong>Function B, Function A and Global Function</strong>;<strong> Function A</strong> can access all the variables present in <strong>Function A and Global Function</strong> while <strong>Global Function</strong> can access only the variables present in the <strong>Global Function</strong>.</p><p>I hope now you have a clear picture on how lexical scoping works in JavaScript. Let’s apply this knowledge in a real code snippet and try to understand it more deeply.</p><h3>Case 1</h3><pre><br>var myCar = {<br> model: “Nissan”,<br> type: “XUV”,<br> color: “black”,<br> price: 1500000<br>}<br>function calLoanPercentage(number) {<br> return myCar.price * number/100;<br>}<br>console.log(calLoadPercentage(25));<br></pre><p>As the JavaScript engine parses the above code snippet, it prepares a scope plan for all the name bindings that’s present in the code. In this case, it starts with <strong>myCar</strong>. It checks whether this is present or not. If it’s not present, it creates a scope (<strong>Global Scope as it’s the outermost function</strong>) for this name binding (<strong>myCar</strong>) and moves forward.</p><p>Now, it encounters a new name binding, which is the function, <strong>calLoanPercentage(number)</strong>. This name binding will also be having the same scope as that of <strong>myCar</strong> as both of them are at the same level. In case of functions, an additional scope called local scope, will also be created, where all the parameters and other variables present inside the function, will be of that scope.</p><p>These name bindings cannot be called from the outer functions.<br>During the execution phase, JavaScript engine starts executing the code line by line. At first, it will check if there is a name binding called <strong>myCar</strong>, if it is present, it will assign its value. Then it moves directly to the console statement.</p><p>In the console statement, we are calling the function <strong>calLoanPercentage(25)</strong> with an argument value 25. As soon as the JavaScript executes this, it checks for the name binding <strong>calLoanPercentage()</strong> in the memory, as it is present, it takes the function definition and starts executing.</p><p>At first, it will define it’s parameters and assign it with the argument value 25. After which, it will return <strong>myCar.price * number/100</strong>. While executing this statement, it will first try to find <strong>myCar</strong> in the local memory. As it does not find, it will move to the outer function and searches in its memory.</p><p>As it finds, it will grab the value and checks for the property <strong>price</strong>, which is present, and hence returns the value 1500000. Similarly, it searches for the variable, <strong>number</strong>, in its local memory.</p><p>As it finds, it will grab the value and evaluate the expression. The evaluated value is then passed as an argument to the <strong>console.log()</strong> method, which prints the value to the console.</p><h3>Case 2</h3><pre><br>var functionExpression = function printOne() {<br> var text = “hello”;<br> console.log(text);<br>}<br>functionExpression() // prints “hello”<br>printOne() // ReferenceError: printOne is not defined<br></pre><p>In the above code, we have made use of named function expressions. In this case, the name <strong>printOne</strong> will be in the local scope of the function and not in the global scope.</p><p>This is the reason why we get a Reference Error when we try to call the function by its name <strong>printOne</strong>.</p><p>So how does scoping works in the cases of <strong>const</strong> and <strong>let</strong> declarations? Well, I will be soon covering this in detail in my next blog, hold tight. Until then, if you found this article useful, please show your love and share this on social media. Always feel free to connect with me on Twitter, LinkedIn or email.</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abdbe68914fd" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/demystifying-javascript-scope-abdbe68914fd">Demystifying JavaScript Scope</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying JavaScript Code Execution]]></title>
            <link>https://javascript.plainenglish.io/demystifying-javascript-code-execution-b9f99b98485b?source=rss-4ab206bad4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9f99b98485b</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ajo John]]></dc:creator>
            <pubDate>Thu, 09 Sep 2021 13:47:55 GMT</pubDate>
            <atom:updated>2021-09-09T13:47:55.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_xPtCvl6Qd7Jfc4S" /><figcaption>Photo by <a href="https://unsplash.com/@cebbbinghaus?utm_source=medium&amp;utm_medium=referral">Christopher Robin Ebbinghaus</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>JavaScript is a <strong>single-threaded</strong>, <strong>dynamically typed,</strong> and <strong>lexically scoped</strong> language. I know this might sound like jargon to you right now, but let’s try to understand this by breaking it down.</p><p><strong>Single-threaded</strong> means that JavaScript can only execute a single statement in a given time. In other words, JavaScript is a <strong>synchronous language</strong>.</p><p><strong>Dynamically typed</strong> means that the type of the variable purely depends on the type of the value that is stored inside the variable.</p><pre><br>var variableOne = 1;<br>console.log(typeof variableOne) // Prints “number”<br>variableOne = “Hello”;<br>console.log(typeof variableOne) // Prints “string”<br></pre><p>The above code snippet is a clear example of how the type of variable changes based on the value that is being assigned.</p><p><strong>Lexically scoped</strong> is the ability of the child functions to access the variables up to its parent scope and not vice-versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*PRC-ZqLBLMNGylAgNsEzkg.png" /><figcaption>Scope chain</figcaption></figure><p>The above image is a clear representation of lexical scoping, where <strong>Function C</strong> can access all the variables present in <strong>Function C, Function B, Function A and Global Function;</strong> <strong>Function B</strong> can access all the variables present in <strong>Function B, Function A and Global Function</strong>; <strong>Function A</strong> can access all the variables present in <strong>Function A and Global Function</strong> while <strong>Global Function</strong> can access only the variables present in the <strong>Global Function</strong>. This clearly proves that the child functions can access the scope of the parent functions while the parent functions cannot access the scope of the child functions.</p><p>Before proceeding any further, let me first introduce two important components that are required for understanding the JavaScript code execution.</p><p><strong>Execution Contexts</strong> — These are sections which are created whenever a Javascript engine executes a code. There are two execution contexts — <strong>Global Execution Context </strong>and <strong>Function Execution Context</strong>.</p><p><strong>Global Execution Context</strong> is the first context which gets created when the engine starts executing the code. This is either called the <strong>global()</strong> or the <strong>main()</strong> function. <strong>Function Execution Context</strong> is the context which gets created whenever it encounters a function invocation statement in the code. Both these contexts have two phases — The Creation Phase and the Execution Phase. Creation Phase is the phase where JavaScript creates a <strong>global object — window in the case of browser or global in the case of Node.js</strong>, a variable of type, <strong>object</strong>, called <strong>this</strong>, which refers to the <strong>global object</strong>, and allocate a <strong>memory heap</strong> which stores all the variables and function declarations, where values of the variables are set to <strong>undefined</strong>. Creation phase of the Function Execution Context is slightly different. Instead of the <strong>global object,</strong> it creates the <strong>arguments object</strong> which refers to all the parameters that are passed into the function. Execution phase is the phase where Javascript executes the code line by line. This is also the phase where variables will be assigned with their actual values and executes all the function calls that are present in the code.</p><p><strong>Call Stack </strong>— This is the section where Javascript manages both Global and Function Execution Context. From the name itself, it is very clear that this section works with the principle of <strong>Stack</strong>. When Javascript starts executing the code, the first context, which is the Global Execution Context gets pushed into the Stack. After which, whenever it encounters a function invocation, it pushes the Function Execution Context of that function into the stack. Similarly, whenever a function gets completed, the function execution context of that function will be popped from the Stack. Code execution is stopped when the Call Stack is completely empty.</p><p>Now let’s try to understand the end-to-end flow of the Javascript code execution.</p><pre>var counter = 0;<br>function increment() {<br> counter++<br>}</pre><pre>function addNumberToCounter(number) {<br> var result = counter + number;<br> console.log(result);<br>}</pre><pre>increment();<br>addNumberToCounter(5);</pre><p>First, Javascript engine creates a Global Execution Context and kicks off the Creation Phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iikzTn7_mNUkYF_n2UhOvg.png" /><figcaption>Creation Phase</figcaption></figure><p>In this phase, the JavaScript engine parses the code where it identifies all the variables and function declarations and stores them in the memory heap where the values of all the variables are set to <strong>undefined</strong>.</p><p>After the creation phase is over, it begins the Execution Phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FjqXslaaTCnIHjUytBQ2vA.png" /><figcaption>Execution Phase</figcaption></figure><p>Now, the JavaScript engine starts executing the code line-by-line. In our case, it would start from <strong>var counter = 0</strong>. When it encounters this statement, it checks whether the variable is present in the memory and set the value to 0 as per the statement. After executing this statement, it moves to the next line which in our case would be the <strong>function increment(){…}</strong>. Since this is a declaration statement, it skips the entire function block (line numbers 3–6). One of the important thing to note here is that, functions does not get executed until and unless the functions are invoked. Since the next line is also a function declaration, it skips the entire function block (line numbers 7 to 10).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xL2QJ9ycCtXLs63Y6uqnpA.png" /></figure><p>When it encounters the identifier <strong>increment</strong>, it checks if the identifier is present in the memory and executes the function code stored in the memory. The engine identifies function execution when it encounters <strong>()</strong> after the identifier. When the function is invoked, it creates a Function Execution Context and pushes it to the Call Stack. During the creation phase, the arguments object is created, <strong>this</strong> variable will reference the global Object (window) and checks whether there are any other declaration statements present in the function code. After this phase, the execution phase gets started. When it encounters the statement <strong>counter++</strong>, it checks whether the variable is present in the local memory of the Function Execution Context. When it does not finds the variable, it moves one level above, which is the Global Execution Context and searches for the variable <strong>counter</strong>. When it finds the variable, it grabs the value and does the <strong>++</strong> operation, which increases the current value of the variable by 1. Now, the counter variable will be updated with the new value which is 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NiuyXiU6tdwU70HaRCju7w.png" /></figure><p>As all the statements in the function are executed, the Function Execution Context of the increment function is popped from the Call Stack and destroyed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suxmKk-SeTOGJdzDqNWCEg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ytti0JGVqTj6GqWynycHEA.png" /></figure><p>Now, the engine goes back to the Global Execution Context which is currently at the top of the Call Stack. It moves to the next line and executes the next function invocation (addNumberToCounter(number)) , similar to the increment function. The only difference here is that addNumberToCounter(number) function consists of an argument value 5 which passed to the function. During the creation phase, the arguments object is created which will contain all the parameters passed into the function. In this case, number would be a value inside the arguments object. During the execution phase, it checks for the variable `result` in the local memory of the function execution context. As it’s present, it will evaluate the expression <strong>counter + number</strong>, where it grabs the value of counter and number from the global and local memory respectively. The evaluated result 6, would be assigned to the result variable present in the local memory. It then moves onto the next line and executes the <strong>console.log(result)</strong> statement. This prints the value of the <strong>result</strong> present in the local memory of the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suxmKk-SeTOGJdzDqNWCEg.png" /></figure><p>As soon as the execution phase is over, function execution context (<strong>addNumberToCounter(number)</strong>) is popped from the stack, destroyed and moves back to the global execution context. As the engine identifies that there are no more lines to be executed, it pops the global execution context from the Call Stack and destroys the execution context.</p><p>#Thank you!</p><p>If you feel this article was useful, please do show your love and share this with your fellow beings via your social media so others could make maximum use of this. Always feel free to connect with me on Twitter, LinkedIn or by email.</p><p>Until we meet again, <strong>The Mallu Dev</strong> signing off 👋 Cheers! 🥂</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9f99b98485b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/demystifying-javascript-code-execution-b9f99b98485b">Demystifying JavaScript Code Execution</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying “==” and “===” in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/demystifying-and-57e2d5194a66?source=rss-4ab206bad4df------2</link>
            <guid isPermaLink="false">https://medium.com/p/57e2d5194a66</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ajo John]]></dc:creator>
            <pubDate>Mon, 06 Sep 2021 05:37:56 GMT</pubDate>
            <atom:updated>2021-09-10T05:00:38.989Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyKcANDXKQ3G6UJ4OjvhzA.png" /></figure><p>One of the most common interview questions that every JavaScript developer has encountered in their career is:<em> “What is the difference between </em><em>== and </em><em>===?”</em> Well, I guess most of them reading this would already have come up with the most common answer which is</p><blockquote>‘’==’’ compares value and “===” compares both value and type.</blockquote><p>What if I say that this isn’t the right answer 🙈. Let’s dive deep and understand what’s happening behind the scenes. According to the ECMA Script specifications, both == and === checks the type of the variables. If the types are same, both == and === work exactly the same post which they return true or false based on the values. It&#39;s when the types of the variables are not matching, both differ. 😳</p><p>When the types are not same, == does an implicit coercion while === directly returns false. Implicit Coercion is nothing but the conversion of variable from one type to another.</p><p>Based on the ECMAScript specification, whenever JavaScript encounters a == operator, an abstract operation called IsLooselyEqual ( x, y ) gets invoked. Similarly, when it encounters a === operator an abstract operation called IsStrictlyEqual ( x, y ) gets executed. I understand this might be too much to digest at the moment but lets try to understand both these operations with the help of some code snippets. We won&#39;t be covering all the cases of the operation, rather we would try to address some of the common scenarios that we encounter normally.</p><h3>Case 1:</h3><pre>var stringOne = &#39;1&#39;;<br>var numberOne = 1;</pre><pre>if (stringOne == numberOne) {<br>  console.log(&quot;IsLooselyEqual(x,y) is invoked&quot;);<br>}</pre><p>In the above code snippet, we have two variables -stringOne and numberOne of types string and number respectively. After which we have a conditional statement where we check if stringOne and numberOne are equal using the == operator. As soon as the JavaScript encounters == operator it applies the IsLooselyEqual(x,y) abstract operation. According to this operation, following steps are done.</p><ol><li>It checks if the types of stringOne and numberOne are same or not. If they are same, it returns a value by applying IsStrictlyEqual(x, y) <a href="https://tc39.es/ecma262/#sec-islooselyequal">(Step 2 of the actual algorithm)</a> abstract operation where x would be stringOne and y would be numberOne respectively.</li><li>If the types are not same, it checks if the type of stringOne is a String type and type of numberOne is a Number type <a href="https://tc39.es/ecma262/#sec-islooselyequal">(Step 6 of the actual algorithm)</a> . Since it&#39;s true, it converts stringOne variable into a Number type by applying the ToNumber(x) abstract operation. ToNumber(x) is another abstract operation which converts the variable to a Number Type variable. In this scenario, stringOne would be x, applying ToNumber(x) operation would be ToNumber(stringOne) where stringOne would be converted from String type to Number type based on <a href="https://tc39.es/ecma262/#sec-tonumber">this</a> . After which it returns the value by applying IsLooselyEqual(x, y) abstract operation again where now both x and y are of the same type.</li><li>Since both are of the same type, it returns the value by applying IsStrictlyEqual(x,y) abstract operation.</li><li><a href="https://tc39.es/ecma262/#sec-isstrictlyequal">IsStrictlyEqual(x,y)</a> checks if the types of both x and y are the same. If the types are same, it checks the value of both x and y. If the values are also the same, then the operation would return a true else it would return a false.</li></ol><h3>Case 2:</h3><pre>var arrayOne = [&#39;1&#39;];<br>var numberOne = 1;</pre><pre>if (arrayOne == numberOne) {<br>  console.log(&quot;IsLooselyEqual(x,y) is invoked&quot;);<br>}</pre><p>In the above code snippet, we have two variables arrayOne and numberOne of types object and number respectively. After which we have a conditional statement where we check if arrayOne and numberOne are equal using the == operator. As soon as the JavaScript encounters == operator, it applies the IsLooselyEqual(x,y) abstract operation. According to this operation, following steps are done.</p><ol><li>It checks if the types of arrayOne and numberOne are the same or not. If they are the same, it returns the value by applying IsStrictlyEqual(x, y) abstract operation where x would be arrayOne and y would be numberOne respectively.</li><li>If the types are not the same, it checks if the type of arrayOne is an Object type and type of numberOne is a String, Number etc type <a href="https://tc39.es/ecma262/#sec-islooselyequal">(Step 12 of the actual algorithm)</a> . Since it&#39;s true, it converts the Object type variable into a Primitive type by applying the ToPrimitive() abstract operation. This operation, in brief, tries to convert the Object type to a Primitive type which would be either a String or a Number type <a href="https://tc39.es/ecma262/#sec-toprimitive">(ToPrimitive)</a>.</li><li>It then returns the value by applying IsLooselyEqual(x, y) operation by passing x and y and repeats the same steps till the types of both x and y are equal or when IsLooselyEqual(x, y) operation returns false.</li></ol><h3>Case 3:</h3><pre>var objectOne = [];<br>var booleanOne = true;</pre><pre>if(objectOne) {<br>  console.log(&quot;This check whether array is empty or not won&#39;t work !!&quot;)<br>}</pre><p>In the above code snippet, we have two variables objectOne and booleanOne of types object and boolean respectively. After which, we have a conditional statement where we check if objectOne is true. As soon as JavaScript encounters this, it applies a new abstract operation called ToBoolean(x). This operation converts the variable to a Boolean type depending on the reference table in this <a href="https://tc39.es/ecma262/#sec-toboolean">(ToBoolean)</a> .</p><p>Based on this table, since our variable is of type Object it would return us true irrespective of whether the array is empty or not. This is the main reason why we need other parameters while comparing Object types. In our case, since we clearly know it&#39;s an array object, we could use the length property. Now we can refactor the above code in the following way for checking emptiness.</p><p>By now I hope you understood how JavaScript treats the == and === operator and cases when they are actually different. The above-mentioned were just a few scenarios out of many. If you are really interested to dig deeper, I would recommend you to go through <a href="https://tc39.es/ecma262/#sec-islooselyequal">ECMA Specifications</a> where you will find the complete implementation of both IsLooselyEqual(x,y) and IsStrictlyEqual(x,y) abstract operations. I would also encourage you to read this book if you haven&#39;t - <a href="https://github.com/getify/You-Dont-Know-JS/tree/1st-ed">You Don&#39;t Know JS</a> by <a href="https://www.linkedin.com/in/getify/">Kyle Simpson</a>.</p><h3>Thank you</h3><p>Hope you enjoyed this read on == and === operators and how comparisons work in JavaScript. Now you can make use of this knowledge to really ace the above question in your upcoming interviews 😜. Let me know your thoughts in the comment section down below. If you feel this article is useful, please do show your love and share this with your fellow beings who could make maximum use of this.</p><p>Always feel free to connect with me via Twitter, LinkedIn, or email. Happy to help in all ways possible. 😊</p><p>Until we meet again, The Mallu Dev signing off 👋 Cheers! 🥂</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57e2d5194a66" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/demystifying-and-57e2d5194a66">Demystifying “==” and “===” in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>