<?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 Swati Redhu on Medium]]></title>
        <description><![CDATA[Stories by Swati Redhu on Medium]]></description>
        <link>https://medium.com/@swati.developer17?source=rss-a0b4a561a04a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rFwtWLlliAimnLru</url>
            <title>Stories by Swati Redhu on Medium</title>
            <link>https://medium.com/@swati.developer17?source=rss-a0b4a561a04a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 04:04:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swati.developer17/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[How to open up Chrome developer tools?]]></title>
            <link>https://medium.com/@swati.developer17/how-to-open-up-chrome-developer-tools-93445154c1df?source=rss-a0b4a561a04a------2</link>
            <guid isPermaLink="false">https://medium.com/p/93445154c1df</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[developer-tools]]></category>
            <dc:creator><![CDATA[Swati Redhu]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 12:47:12 GMT</pubDate>
            <atom:updated>2024-11-12T12:47:12.152Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fua7vVw9awZKWwLSYpW%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fpudgypenguins-computer-developer-binary-ua7vVw9awZKWwLSYpW&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExd2c2Yjd3aXd1bDlxYWQwZnF2OW54cWw4NzZmcnpmZHRyYjBpZ283aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Fua7vVw9awZKWwLSYpW%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae2596c5238c3852255c549d2fa71d69/href">https://medium.com/media/ae2596c5238c3852255c549d2fa71d69/href</a></iframe><ol><li><strong>Press cmd+option+J</strong> : This will then open up this console that we see below.<br>You can see all the tabs : Elements, Console,Sources, Network, Performance, Memory, Application, Security, Lighthouse.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2Ui90kJKs5GdRKNOUhhoA.png" /></figure><p>2. <strong>Right Click and then Inspect.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeHq7JZkQXCnt_qL1ov0IA.png" /></figure><p>3. <strong>Chrome Menu &gt;&gt; Go to View &gt;&gt; Developer &gt;&gt; JavaScript Console</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QT3-3-ZBpi6d72aAM-Anog.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93445154c1df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 15: What is an Anonymous Functions??]]></title>
            <link>https://medium.com/@swati.developer17/what-is-an-anonymous-functions-6d4b3ab99485?source=rss-a0b4a561a04a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d4b3ab99485</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[function-statement]]></category>
            <category><![CDATA[anonymous-function]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Swati Redhu]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 07:08:51 GMT</pubDate>
            <atom:updated>2024-03-12T07:11:36.238Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FMeIn1KDfJAyV357VgH%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FMeIn1KDfJAyV357VgH%2Fgiphy.gif%3Fcid%3D790b76119oidsf3s1tsui9n572lp0h3kdce3skucnkr0kexl%26ep%3Dv1_gifs_search%26rid%3Dgiphy.gif%26ct%3Dg&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZDR1aGRzMGlxc3RoM2puZG9qeG5sN2g2dWFtcGVidTRtbGZ0MHpmeCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FMeIn1KDfJAyV357VgH%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/23a3eb74b74920eab19830271ee5b7fe/href">https://medium.com/media/23a3eb74b74920eab19830271ee5b7fe/href</a></iframe><p>A function without a name is <strong>anonymous function</strong>.</p><p>Now, Other related questions are::<br>What are <strong>first class functions</strong> in javascript?<br>What is <strong>difference between function statement and function expression</strong>?</p><p><strong>Let move on, we’ll be covering all below topics:</strong><br>1. Function Statement<br>2. Function Expression<br>3. Function Declaration<br>4. Anonymous Function<br>5. Named Function Expression<br>6. Difference between Parameters and Arguments ?<br>7. First Class Functions</p><p>First of all, let’s see <strong>What is Function Statement?</strong><br><em>If you write a function keyword and give it a name like below then it is a function statement.</em></p><pre>function a(){<br>}</pre><p>Let’s just say <strong>function “a”</strong> have nothing more then console like below:</p><pre>function a(){<br>console.log(&quot;Hello, I am calling a&quot;)<br>}</pre><p>So, this way of creating a function is called <strong>Function Statement 🤷🏻‍♀️</strong>.</p><p>Now, you can assign a function to a variable 😮 also :</p><pre>var b = function(){<br>console.log(&quot;Hello, b called&quot;)<br>}</pre><p>Above, We <strong>assigned a function to variable “b”</strong>. Now function acts like a value. Now this is known as <strong>Function Expression 🤷🏻‍♀️</strong>.</p><blockquote>So, Function Statement and Function Expressions, both are ways to create functions which we are doing from many years.</blockquote><p>Now, <strong>What the difference between Function Statement and Function Expression?</strong><br><strong>Answer is</strong>: Hoisting.. 🧐</p><p>Now, <strong>the question is how??</strong><br>So, when we try to call both functions on top of file and check output then what happens?</p><pre>a();<br>b();<br><br>//Function Statement<br>function a(){<br>  console.log(&quot;Hello, a called&quot;)<br>}<br><br>//Function Expression<br>var b = function(){<br>  console.log(&quot;Hello, b called&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AewKNXqJdCerR8ZaIA4JOw.png" /></figure><p><strong>Output</strong> : “<strong>b</strong>” throws an error<br><strong>Uncaught TypeError: “b” is not a function 😳🤨</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*mVtPjKMXiVVVpy1WoC5qBw.png" /></figure><p>As you already know from <a href="https://medium.com/@swati.developer17/part-3-hoisting-in-javascript-20c6290b2013">hoisting in previous articles</a>. <strong>Function “a”</strong> will create a memory in memory creation phase and function is assigned to a. But in case of <strong>Function expression</strong>, “b” will be treated like any another variable. So, “b” is assigned undefined initially until code hits the line 9. So, when JS engine executes line by line and reaches line no. 9 then only function will be assigned to variable “b” until then it is undefined.</p><p><strong>So, that’s the major difference between Function Statement and Function Expression.</strong></p><p><strong>What is Function Declaration?🧐</strong><br>It is same as Function Statement</p><p><strong>What are Anonymous Function?🧐</strong><br>A function without a name is Anonymous Function. These functions doesn’t have their own identity. This means if I do below then it will give you syntax error</p><pre>// Anonymous Function<br>function () {<br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Y2q38S0stmwbVbDVfozZw.png" /></figure><blockquote><strong>Why is the error?</strong><br>Because Anonymous Function looks exactly like a function statement but doesn’t have a name. As per ECMA Script specification, A function statement should always have a name.</blockquote><p>Now the question is <strong>what’s even the use of Anonymous Functions?🤔</strong><br>These functions are used in a place where functions are used as values. This means that you can use those to assign as values to some variables, like we did in Function expression.</p><blockquote><strong>What is Named Function Expressions?<br></strong>A named function expression is like a function expression but instead of anonymous function, we use a function with a name.</blockquote><pre>//Named Function Expression<br>var b = function xyz(){<br>  console.log(&quot;Hello, b called&quot;)<br>}</pre><p>So, if interviewer asks you <strong>“How can you have the name of function itself and then put it into an expression”?</strong><br><strong>Answer is:</strong> <em>Named function expression. Function “xyz” have name to itself and then assigned it to variable “b” and this makes named function expression.</em></p><p><strong>Next question: Can you call function “xyz”? What will happen then?</strong></p><pre>//Named Function Expression<br>var b = function xyz(){<br>  console.log(&quot;Hello, b called&quot;)<br>}<br><br>b(); // output here?<br>xyz(); // output here?</pre><p><strong>Output :<br>Uncaught ReferenceError: “xyz” is not defined 🧐 😮</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*e8Ru4REbDdxxEBfcVMkCyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*vOAH6IHD0_WII9Z9wM7oRw.png" /></figure><p><strong>So, What’s the reason? Why “xyz” is not defined?</strong><br><em>Because function “xyz” is used as value and not in global scope. But it is created in local scope. <br>So, if you try to access it inside the function then you can do that.</em> See below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*e9BbFc8h5fZSnTX8x9OCMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*XZPuXsfO7VHxARN_nRXBhQ.png" /></figure><p>Note: If you are not familiar how scoping works. <a href="https://medium.com/@swati.developer17/part-8-scope-chain-scope-and-lexical-environment-5214a5667ab7">Please read here</a>.</p><p><strong>What is difference between Parameters and Arguments?</strong></p><p>The local variable in function scope is called <strong>parameters</strong>. <br>See below example: You can not access param1, param2 outside the function</p><pre>var b = function(param1, param2){<br>  console.log(&quot;Hello, b called&quot;)<br> <br>}</pre><p>The values which we pass inside a function are called <strong>arguments</strong>.</p><pre>var b = function(param1, param2){<br>  console.log(&quot;Hello, b called&quot;)<br> <br>}<br><br>b(1,2); // 1 and 2 are arguments<br></pre><p><strong>What are First Class functions?</strong></p><p>The ability to use functions as values which means <br>1. can be passed as an arguments into another functions <br>2. and can be returned from the functions <br>is known as First class Functions.</p><p><strong>Example 1</strong>: When you can pass function inside another function as an arguments.</p><pre>var b = function(param1){<br>  console.log(&quot;Param 1 =&quot;,param1)<br> <br>}<br><br>b(function(){<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*zsBoEBdCOrFPBWGQWrFLyw.png" /></figure><p>You can also do this using Named function like below:</p><pre>// First Class function<br>var b = function(param1){<br>  console.log(&quot;Param 1 =&quot;,param1) // cheking here if accessible<br> <br>}<br><br>// Named function<br>function xyz(){<br><br>}<br><br>b(xyz); // passing named function as xyz</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*-HKebQP_ZsE2UWI8tFoTmg.png" /></figure><p><strong>Example 2</strong>: Another thing that we can do is return a function from a function. See below:</p><pre>var b = function(param1){<br>  console.log(&quot;Param 1 =&quot;,param1)<br> return function(){<br><br> }<br>}<br><br>function xyz(){<br><br>}<br><br>console.log(&quot;Return value of b = &quot;,b(xyz));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*BnAboveO7uVLqhL1PHjo_g.png" /></figure><p>This programming concept of First class function is exist in other languages also.</p><h3>⭐️Happy Coding. ⭐️</h3><p>Hopefully, you learned something today! Before you go:</p><ul><li>👏 Clap for the story and follow <a href="https://medium.com/@swati.developer17">Swati Redhu</a> 👩🏻‍💻</li><li>📰 View more content in the <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">JavaScript learning roadmap 2023 — The Ultimate Guide ❤️</a></li><li>🔔 Follow on : <a href="https://www.linkedin.com/in/swati-redhu-451723144/">LinkedIn</a></li></ul><p>🚀👉 <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">C<strong>lear your JS basics and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d4b3ab99485" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling the Magic of JavaScript Closures: Empowering Your Code]]></title>
            <link>https://medium.com/@swati.developer17/unveiling-the-magic-of-javascript-closures-empowering-your-code-150e6eed9ec1?source=rss-a0b4a561a04a------2</link>
            <guid isPermaLink="false">https://medium.com/p/150e6eed9ec1</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Swati Redhu]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 16:10:55 GMT</pubDate>
            <atom:updated>2023-08-07T16:10:55.854Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FGB4hXdXQGu1gBuUXNN%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FGB4hXdXQGu1gBuUXNN%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FGB4hXdXQGu1gBuUXNN%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b2362d0cea05e5138cc0044b1896ad7/href">https://medium.com/media/6b2362d0cea05e5138cc0044b1896ad7/href</a></iframe><p>Ever wondered how to make your JavaScript code more powerful and organised? Meet <strong><em>closures</em></strong> — the secret ingredient that can take your programming skills to a whole new level! In this article, we’ll demystify closures and show you how to wield their magic to create cleaner, smarter, and more efficient code. So, get ready for an exciting journey of discovery as we unravel the wonders of closures, and watch your code flourish like never before!</p><p>Explore the following articles to delve deeper into the subject:</p><ul><li><a href="https://medium.com/@swati.developer17/part-11-closures-in-js-%EF%B8%8F-e0874a86b2de">Part 11: Closures in JS 🤷🏻‍♀️</a></li><li><a href="https://medium.com/@swati.developer17/part-12-settimeout-closures-interview-questions-cfa0d402831f">Part 12: setTimeout + Closures Interview Questions 🤓</a></li><li><a href="https://medium.com/@swati.developer17/part-13-closure-js-interview-questions-f31c1be77d3e">Part 13: Closure JS Interview Questions 🤯</a></li><li><a href="https://medium.com/@swati.developer17/part-14-closure-js-interview-exercise-3759e1a73d89">Part 14: Closure JS Interview exercise 👩🏻‍🏫</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FeMsCxr6w35vjfI4zl5%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FeMsCxr6w35vjfI4zl5%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FeMsCxr6w35vjfI4zl5%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/e31501c69a6035c0a6ca462b8554aa72/href">https://medium.com/media/e31501c69a6035c0a6ca462b8554aa72/href</a></iframe><p>I value your feedback! If you found this article helpful in unraveling the mysteries of closures and enhancing your JavaScript knowledge, I’d love to hear from you. Feel free to share your thoughts and let me know if this content has made a positive impact on your coding journey. Your appreciation fuels my commitment to creating valuable content for my readers!</p><h3>⭐️ Happy Coding. ⭐️</h3><p>Hopefully, you learned something today! Before you go:</p><ul><li>👏 Clap for the story and follow <a href="https://medium.com/@swati.developer17">Swati Redhu</a> 👩🏻‍💻</li><li>📰 View more content in the <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">JavaScript learning roadmap 2023 — The Ultimate Guide ❤️</a></li><li>🔔 Follow on : <a href="https://www.linkedin.com/in/swati-redhu-451723144/">LinkedIn</a></li></ul><p>🚀👉 <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">C<strong>lear your JS basics and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=150e6eed9ec1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 14: Closure JS Interview exercise ‍]]></title>
            <link>https://medium.com/@swati.developer17/part-14-closure-js-interview-exercise-3759e1a73d89?source=rss-a0b4a561a04a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3759e1a73d89</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Swati Redhu]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 15:29:43 GMT</pubDate>
            <atom:updated>2023-08-07T15:31:23.951Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*_X--lfsuhpMkxfiW0XGHIQ.png" /></figure><p>Get ready for an exciting adventure into the world of JavaScript closures! By mastering closures through simple exercises, you’ll level up your JavaScript skills and discover their true potential. So, let’s dive in and explore closures together!</p><p><strong>If you don not have understanding of Closures, I highly recommend to go through below articles first</strong>.</p><p>- <a href="https://medium.com/@swati.developer17/part-11-closures-in-js-%EF%B8%8F-e0874a86b2de">Part 11: Closures in JS 🤷🏻‍♀️</a></p><p>- <a href="https://medium.com/@swati.developer17/part-12-settimeout-closures-interview-questions-cfa0d402831f">Part 12: setTimeout + Closures Interview Questions 🤓</a></p><p><a href="https://medium.com/@swati.developer17/part-13-closure-js-interview-questions-f31c1be77d3e">-Part 13: Closure JS Interview Questions 🤯</a></p><p>Let’s get started.</p><pre>function outerFunction() {<br> var outerVariable = &quot;Hi, &quot;;<br> function innerFunction(name) {<br>  console.log(outerVariable + name);  // What is logged?<br> }<br> return innerFunction;<br>}<br><br>var inner = outerFunction();<br>inner(&quot;Closure&quot;);</pre><pre>function outer() {<br>  var x = 10;<br>  function inner() {<br>    console.log(x);  // What is logged?<br>  }<br>  return inner;<br>}<br>var innerFunc = outer();<br>innerFunc();</pre><pre>function outer() {<br>  var x = 10;<br>  function inner() {<br>    console.log(x);  // What is logged?<br>  }<br>  var x = 20;<br>  return inner;<br>}<br>var innerFunc = outer();<br>innerFunc();</pre><pre>function outer() {<br>  var x = 10;<br>  function inner() {<br>    var y = 12;<br>    console.log(x+y); // What is logged?<br>  }<br>  return inner;<br>}<br>var innerFunc = outer();<br>innerFunc();</pre><pre>var a = 1; <br>function b() { <br>    a = 10; <br>    return; <br>    function a() {} <br>} <br>b(); <br>console.log(a); // What is logged?<br><br></pre><pre>function test() {<br>   console.log(a); // What is logged?<br>   console.log(foo()); // What is logged?<br>   <br>   var a = 1;<br>   function foo() {<br>      return 2;<br>   }<br>}<br><br>test();</pre><pre>var a = 1; <br><br>function someFunction(number) {<br>  function otherFunction(input) {<br>    return a;<br>  }<br>  <br>  a = 5;<br>  <br>  return otherFunction;<br>}<br><br>var firstResult = someFunction(19); // What is firstResult?<br>var result = firstResult(12); // What is result?</pre><pre>var fullname = &#39;Daisy Doe&#39;;<br>var obj = {<br>   fullname: &#39;Vera Singh&#39;,<br>   prop: {<br>      fullname: &#39;Amar Akbar Anthony&#39;,<br>      getFullname: function() {<br>         return this.fullname;<br>      }<br>   }<br>};<br><br>console.log(obj.prop.getFullname());<br><br>var test = obj.prop.getFullname;<br><br>console.log(test()); // What is logged?</pre><p>For practise, visit the <a href="https://github.com/swatiredhu17/interview-mentor-exercises/blob/main/exercises/javascript/closure-scoping-exercises.md">github exercise repo</a></p><p>I value your feedback! If you found this article helpful in unraveling the mysteries of closures and enhancing your JavaScript knowledge, I’d love to hear from you. Feel free to share your thoughts and let me know if this content has made a positive impact on your coding journey. Your appreciation fuels my commitment to creating valuable content for my readers!</p><h3>⭐️ Happy Coding. ⭐️</h3><p>Hopefully, you learned something today! Before you go:</p><ul><li>👏 Clap for the story and follow <a href="https://medium.com/@swati.developer17">Swati Redhu</a> 👩🏻‍💻</li><li>📰 View more content in the <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">JavaScript learning roadmap 2023 — The Ultimate Guide ❤️</a></li><li>🔔 Follow on : <a href="https://www.linkedin.com/in/swati-redhu-451723144/">LinkedIn</a></li></ul><p>🚀👉 <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">C<strong>lear your JS basics and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3759e1a73d89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 13: Closure JS Interview Questions ]]></title>
            <link>https://medium.com/@swati.developer17/part-13-closure-js-interview-questions-f31c1be77d3e?source=rss-a0b4a561a04a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f31c1be77d3e</guid>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Swati Redhu]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 14:04:57 GMT</pubDate>
            <atom:updated>2023-06-22T14:04:57.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*_uRTf6gl3-5z-vYA9NAGQw.png" /></figure><p><strong>If you don not have understanding of Closures, I highly recommend to go through below articles first</strong>.</p><p>- <a href="https://medium.com/@swati.developer17/part-11-closures-in-js-%EF%B8%8F-e0874a86b2de">Part 11: Closures in JS 🤷🏻‍♀️</a></p><p>- <a href="https://medium.com/@swati.developer17/part-12-settimeout-closures-interview-questions-cfa0d402831f">Part 12: setTimeout + Closures Interview Questions 🤓</a></p><p><strong>Question 1: What are closures In JS?</strong><br>A function alongs with it’s reference error together forms a Closure.</p><p><strong>Question 2. How you’ll explain more about it?</strong></p><ul><li>Each and every function in JS have access to it’s outer lexical environment that means it has access to variables and functions which are in environment of it’s parent.</li><li>Even If this function is executed in some other scope instead of original scope, it will still remember it’s outer lexical environment where it was originally present in the code.</li></ul><p><strong>Question 3. What about an example to explain all this?</strong></p><pre>function outer(){<br>  var a =10;<br>  function inner(){<br>    console.log(a);<br>  }<br>  return inner;<br>}<br><br>outer()();</pre><p>So, in above example, We have nested function <em>inner() </em>inside function<em> </em><em>outer() . </em><em>inner() </em>function have access to<em> </em><em>variable a </em>which is present in it’s outer environment.</p><p>Also, when you return <em>inner() </em>function and invoke<em> </em><em>outer() f</em>unction, it will still console value of<em> </em><em>variable a . </em>So, it remembered it’s outer lexical env even when called in other scope.</p><p>So, <em>inner() </em>function<em> = </em><strong><em>Closure</em></strong><em> </em>💡</p><p><strong>Question 4. What is</strong> <em>outer()() </em><strong>? Why there are two parenthesis?<br> </strong><em>Two parenthesis are used to call inner function.</em></p><p>Example : <br>- <em>outer() </em>will return below output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*6OZZybZbAr6aRCidrpkpyQ.png" /></figure><p>- <em>outer()() </em>will return below output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*_3tkDJUIdQKXssJTaV7-Pw.png" /></figure><p>Also, This can be done in other way as well</p><pre>function outer(){<br>  var a =10;<br>  function inner(){<br>    console.log(a);<br>  }<br>  return inner;<br>}<br><br>var close = outer(); // this will give you outer function<br>close(); // this will give you inner function and equivalent </pre><p><strong>Question 5. What if </strong><em>var</em><strong><em> </em>declaration is moved to Line 5, just before return statement. What will happen? Will it still be a Closure?</strong></p><pre>function outer(){ <br>  function inner(){<br>    console.log(a);<br>  }<br>  var a =10;<br>  return inner;<br>}<br><br>var close = outer(); // this will give you outer function<br>close(); // this will give you inner function and equivalent</pre><p>Answer is <strong>YES, it will still be. Closure. </strong>It doesn’t matter what the sequence is, means where the statement is. For closure, all matter is function has access to it’s lexical environment. Also, output will be same.</p><p><strong>Question 6. What if </strong><em>var</em><strong><em> is replaced by </em></strong><em>let</em><strong> in Line 5. What will happen?</strong></p><pre>function outer(){ <br>  function inner(){<br>    console.log(a);<br>  }<br>  let a =10; // let instead of var<br>  return inner;<br>}<br><br>var close = outer(); // this will give you outer function<br>close(); // this will give you inner function and equivalent</pre><p>Answer is <strong>It won’t affect anything.</strong> It ‘ll still be a closure and output will be same.</p><p><strong>Question 7. What if</strong> <em>outer() </em><strong>have a parameter? What happens then?</strong></p><pre>function outer(b){ <br>  function inner(){<br>    console.log(a, b); // try printing b here<br>  }<br>  let a =10; // let instead of var<br>  return inner;<br>}<br><br>// Passing argument here <br>var close = outer(&quot;Hi Closures&quot;); // this will give you outer function<br>close(); // this will give you inner function and equivalent</pre><p>Answer is <strong>It won’t affect anything.</strong> It ‘ll still be a closure and we can try printing value of <em>b </em>as well in console.</p><p>Reason: <em>b </em>is also the part of outer environment</p><p>Output will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*H0f353b9ObYaQJr0Wvdm0g.png" /></figure><p><strong>Question 8. What if </strong><em>outer() </em><strong>function is nested into another function? Will </strong><em>inner() </em><strong>function have access to</strong><em> </em><em>outer() </em><strong>function’s environment as well?</strong></p><pre><br>function outest(){<br>  var c = 12; <br>  function outer(b){ <br>    function inner(){<br>      console.log(a, b, c); // try printing b and c  here<br>    }<br>    let a =10; // let instead of var<br>    return inner;<br>  }<br>  return outer;<br>}<br><br><br>// Passing argument here <br>var close = outest()(&quot;Hi Closures&quot;); // this will give you outer function<br>close(); // this will give you inner function and equivalent</pre><p>Answer is <strong>YES, </strong><em>inner() </em><strong>function have access to</strong><em> </em><em>outer() </em><strong>function’s environment as well.</strong></p><p>Try printing <em>variable c </em>inside<em> </em><em>inner() </em>function<em>.</em></p><p>Output will be :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*xY_SxIl_rawW3OkHZMTg0w.png" /></figure><p><strong>Question 9. What if we have global variable with conflicted name?</strong></p><pre>function outest(){<br>  var c = 12; <br>  function outer(b){ <br>    function inner(){<br>      console.log(a, b, c); // try printing b and c  here<br>    }<br>    let a =10; // let instead of var<br>    return inner;<br>  }<br>  return outer;<br>}<br><br>let a =100;<br>// Passing argument here <br>var close = outest()(&quot;Hi Closures&quot;); // this will give you outer function<br>close(); // this will give you inner function and equivalent</pre><p><em>inner() </em>function has a closure with <em>variable a </em>on <strong>Line 7</strong> i.e<em> </em><em>let a = 10 </em>.So the<em> </em><em>inner() </em>function has <em>reference for </em><em>variable a </em>is at Line 7.<br><em>let a = 100; </em>at <strong>Line 13</strong> is in different scope. So, it will print output with value 10.</p><p>But <strong>if we comment Line 7, </strong><em>then it will go to outer environments looking for a and prints 100. </em>Check below:</p><pre>function outest(){<br>  var c = 12; <br>  function outer(b){ <br>    function inner(){<br>      console.log(a, b, c); // try printing b and c  here<br>    }<br>    //let a =10; // let instead of var<br>    return inner;<br>  }<br>  return outer;<br>}<br><br>let a =100;<br>// Passing argument here <br>var close = outest()(&quot;Hi Closures&quot;); // this will give you outer function<br>close(); // this will give you inner function and equivalent</pre><p>Also, <strong>if we comment Line 13, </strong><em>then it will print “ReferenceError: a is not defined”. </em>Check below:</p><pre>function outest(){<br>  var c = 12; <br>  function outer(b){ <br>    function inner(){<br>      console.log(a, b, c); // try printing b and c  here<br>    }<br>    //let a =10; // let instead of var<br>    return inner;<br>  }<br>  return outer;<br>}<br><br>// let a =100;<br>// Passing argument here <br>var close = outest()(&quot;Hi Closures&quot;); // this will give you outer function<br>close(); // this will give you inner function and equivalent</pre><p><strong>Question 10. What are the advantages of Closure?</strong></p><ol><li>Module Design Patterns</li><li>Currying</li><li>Function Like once</li><li>memoize</li><li>maintaining state in async world</li><li>setTimeouts</li><li>Iterators</li><li>Data Hiding and Encapsulation</li></ol><p><strong>Question 11. What are disadvantages of Closure?</strong></p><ol><li>There could be over consumption of memory because every time a closure is formed, it consumes a lot of memory.</li><li>Those closed over variables are not Garbage Collected, so it means it is accumulating a lot of memory</li><li>If not handled properly, it can lead to memory leaks.</li></ol><p><strong>Question 11. What is Garbage Collector?</strong></p><p>Garbage Collector is a program in browser or in JS engine, which free up unutilised memory.<br>In languages like c, c++, it is upto developers how we allocate and deallocate memory but in high level programming language like JS, most work is done by JS engine.<br>So, whenever there are some unused variables, Garbage collector takes those out of memory</p><p><strong>Question 11. How Closures and Garbage Collector related to each other?</strong></p><pre>function a(){<br>  var x = 10;<br>  return function b(){<br>   console.log(x);<br>  }<br>}<br>var y = a();</pre><p>In above example, <em>function b() </em>is closure. So, ideally after executing<em> </em><em>function a() </em>, all it’s memory including<em> </em><em>variable x </em>should be garbage collected. It wasn’t needed anymore. But because <em>function b() </em>is closure and<em> </em><em>variable x </em>is being referred and assigning value <em>variable y</em>, so it won’t free up as later on , we might call<em> y() .</em></p><p>This way more closures means keeping a lot of memory accumulating.</p><p>Although, some modern browsers like chrome and JS engines like V8, they have smart garbage collection mechanism, in which it somehow identify unreachable variables and collects these garbage variables.</p><p><strong>Question 13. What is Smartly garbaged variable, examples?</strong></p><pre>function a(){<br>  var x = 10, z = 20;<br>  return function b(){<br>   console.log(x);<br>  }<br>}<br>var y = a();</pre><p>In above example, <em>variable z </em>is not being used . So when<em> </em><em>function b() </em>is returned ,<em> </em><em>variable z </em>will be smartly garbaged but<em> </em><em>variable x </em>is not. So, <em>variable z </em>won’t be in memory.</p><p>With this, we covers basic questions with explanation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FKB8C86UMgLDThpt4WT%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FKB8C86UMgLDThpt4WT%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FKB8C86UMgLDThpt4WT%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1f68bface497e43d919a9c1259b53af/href">https://medium.com/media/c1f68bface497e43d919a9c1259b53af/href</a></iframe><p>Thanks for reading the article ❤️</p><h3>⭐️ Happy Coding. ⭐️</h3><p>Hopefully, you learned something today! Before you go:</p><ul><li>👏 Clap for the story and follow <a href="https://medium.com/@swati.developer17">Swati Redhu</a> 👩🏻‍💻</li><li>📰 View more content in the <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">JavaScript learning roadmap 2023 — The Ultimate Guide ❤️</a></li><li>🔔 Follow on : <a href="https://www.linkedin.com/in/swati-redhu-451723144/">LinkedIn</a></li></ul><p>🚀👉 <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">C<strong>lear your JS basics and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f31c1be77d3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 12: setTimeout + Closures Interview Questions ]]></title>
            <link>https://medium.com/@swati.developer17/part-12-settimeout-closures-interview-questions-cfa0d402831f?source=rss-a0b4a561a04a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfa0d402831f</guid>
            <category><![CDATA[js]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[settimeout]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[closure]]></category>
            <dc:creator><![CDATA[Swati Redhu]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 10:09:39 GMT</pubDate>
            <atom:updated>2023-06-22T14:06:16.687Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FCZGcUfnAy3ayJw2eZX%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FCZGcUfnAy3ayJw2eZX%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FCZGcUfnAy3ayJw2eZX%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="362" frameborder="0" scrolling="no"><a href="https://medium.com/media/73dfc7abbed3657d465ed78388f8e293/href">https://medium.com/media/73dfc7abbed3657d465ed78388f8e293/href</a></iframe><h3>Prerequisite:</h3><p>If you don’t understand concept of how Closures works, I highly recommend you to read below :</p><ul><li><a href="https://medium.com/@swati.developer17/part-11-closures-in-js-%EF%B8%8F-e0874a86b2de">Part 11: Closures in JS 🤷🏻‍♀️</a></li></ul><blockquote><strong>Basic Definition</strong> : The <em>setTimeout()</em> function is commonly used if you wish to run your function a specified number of milliseconds from when the <em>setTimeout()</em> method was called. The general syntax of the method is:</blockquote><blockquote><em>setTimeout(expression, timeout);</em></blockquote><blockquote>where <em>expression</em> is the JavaScript code to run after <em>timeout</em> milliseconds have elapsed.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*XKK5jfCdWeNybD86su_4Lg.png" /></figure><h4>If we run this program, What do you expect to see in console?</h4><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*Vs1wT8KXuc8t4LzOaamJxQ.png" /></figure><p>It’ll print value of <em>i </em>i.e 1 after 1 sec.</p><p>Similarly if you try doing below, it’ll print after 3 sec.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Dauto%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%252520x%2528%2529%25257B%25250A%252520%252520var%252520i%252520%25253D%2525201%25253B%25250A%252520%252520setTimeout%2528function%252520%2528%2529%25257B%25250A%252520%252520%252520%252520console.log%2528i%2529%25253B%25250A%252520%252520%25257D%25252C3000%2529%25253B%25250A%252520%252520console.log%2528%252522Learn%252520%252522%2529%25250A%25257D%25250Ax%2528%2529%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Dauto%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%25252520x%252528%252529%2525257B%2525250A%25252520%25252520var%25252520i%25252520%2525253D%252525201%2525253B%2525250A%25252520%25252520setTimeout%252528function%25252520%252528%252529%2525257B%2525250A%25252520%25252520%25252520%25252520console.log%252528i%252529%2525253B%2525250A%25252520%25252520%2525257D%2525252C3000%252529%2525253B%2525250A%25252520%25252520console.log%252528%25252522Learn%25252520%25252522%252529%2525250A%2525257D%2525250Ax%252528%252529%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2251c2ce8056d14fc722bc02f74f2bc/href">https://medium.com/media/c2251c2ce8056d14fc722bc02f74f2bc/href</a></iframe><p>You might be thinking that <em>setTimeout()</em> will wait for 3 sec first to print <em>i</em> and then print <strong>“Learn”</strong>. But <strong><em>NO, </em></strong>it will print <strong>“Learn” </strong>first then wait for 3 sec and print value of <em>i .</em></p><h4>What <em>setTimeout()</em> actually does?</h4><ul><li>At Line 3, function () forms a Closure. This function remember reference to <em>i</em>.</li><li><em>setTimeout()</em> is taking that callback function and stores it into some place and attaches timer to it. And JS proceeds and goes to next line.</li><li>Once that timer expires, it takes that function, put it back in call stack and runs it.</li></ul><p>Let’s take an example of complicated problem.</p><h4>Print in console 1, 2, 3, 4, 5 … 10, after each and every second. Means 1 after 1 sec, 2 after 2 sec, 3 after 3 sec and so on. How would you do it?</h4><p>First solution comes to mind is using for loop and move <em>setTimeout()</em> inside it. Like below, right ?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Djavascript%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%252520x%2528%2529%25257B%25250A%252520%252520for%252520%2528var%252520i%252520%25253D%2525201%25253B%252520i%252520%25253C%25253D%25252010%25253B%252520i%25252B%25252B%2529%25257B%25250A%252520%252520%252520%252520setTimeout%2528function%252520%2528%2529%25257B%25250A%252520%252520%252520%252520console.log%2528i%2529%25253B%25250A%252520%252520%252520%252520%25257D%25252C%252520i%252520%252A%2525201000%2529%25253B%25250A%252520%252520%25257D%25250A%252520%252520console.log%2528%252522Learn%252522%2529%25250A%25257D%25250Ax%2528%2529%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Djavascript%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%25252520x%252528%252529%2525257B%2525250A%25252520%25252520for%25252520%252528var%25252520i%25252520%2525253D%252525201%2525253B%25252520i%25252520%2525253C%2525253D%2525252010%2525253B%25252520i%2525252B%2525252B%252529%2525257B%2525250A%25252520%25252520%25252520%25252520setTimeout%252528function%25252520%252528%252529%2525257B%2525250A%25252520%25252520%25252520%25252520console.log%252528i%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%2525257D%2525252C%25252520i%25252520%25252A%252525201000%252529%2525253B%2525250A%25252520%25252520%2525257D%2525250A%25252520%25252520console.log%252528%25252522Learn%25252522%252529%2525250A%2525257D%2525250Ax%252528%252529%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e93846317984ec1a0fe008f352ae3efa/href">https://medium.com/media/e93846317984ec1a0fe008f352ae3efa/href</a></iframe><p>Let’s check output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*XjbI9DucMYqZi1C3_rOKFw.png" /></figure><p><strong>This is not what we expected. Why’s that? What happened?🧐</strong></p><p><strong>Two reasons:</strong></p><p>1. We learn <strong>Closures</strong> how it is a function along with it’s lexical environment. So, even when function is taken out from it’s original scope, still it will remember it’s original scope. It’ll have access to those variables of it’s lexical scope.</p><blockquote>Remember the example of Indian daughter’s that I give in <a href="https://medium.com/@swati.developer17/part-11-closures-in-js-%EF%B8%8F-e0874a86b2de">last article</a> to make it more relatable. If not, <a href="https://medium.com/@swati.developer17/part-11-closures-in-js-%EF%B8%8F-e0874a86b2de">read here</a>.</blockquote><p>So, When <strong><em>setTimeout()</em></strong> takes this function and stores it somewhere and attaches a timeout, it remember the reference to <em>i</em>.</p><blockquote>Remember, in <a href="https://medium.com/@swati.developer17/part-11-closures-in-js-%EF%B8%8F-e0874a86b2de">last article</a>, we understand how it remember reference to variable not value of it. In same way, a daughter remember her brother identity , not all the addresses he lived.</blockquote><p>So, when loop runs the first time, it mix a copy of function, attaches timer and remember the reference of <em>i .</em></p><p>Similarly, all 10 copies of functions, remember the reference of <em>i , </em>not the value. And <strong>all are pointing to same reference of </strong><strong><em>i</em></strong><em> .</em></p><h4>Why the hell they are pointing to same reference of <em>i ? 😳</em></h4><p>Because the environment for all these functions are same. All these copies of <em>setTimeout()’s</em><strong> callback functions</strong> refers to <em>i </em>in same memory space. 🤷🏻‍♀️</p><p>2. <strong>JS doesn’t wait for anything. </strong>So, it will run the loop again and again 🔄.<br>So, <em>setTimeout()</em>will store all 10 functions and JS will move on. It won’t wait for timers to expire. It’ll print <strong><em>“Learn”</em></strong> and when the timer expires, it is too late. <br>Now, value of <em>i </em>changed because the loop was constantly running. when this callback function runs, by that time, the value of <em>var i = 11 </em>in memory location.</p><p><strong>That’s why it prints 11 every time🤷🏻‍♀️. Because all of these copies of callback functions are referring to same spot in memory🤦🏻‍♀️. Which now have run 10 times and it’s value became 11 because of increment in for loop🙄.</strong></p><h4>Now, how we can fix this? 💡💡</h4><p>use <em>let instead of </em><em>var because </em><em>let has block scope. So for each and every loop iteration, </em><em>i will be new variable every time. New copy of </em><em>i will be in memory every time.<br>When </em><em>setTimeout() runs , callback function will have new copy of </em><em>i with it.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Dauto%26width%3D614%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%252520x%2528%2529%25257B%25250A%252520%252520for%252520%2528let%252520i%252520%25253D%2525201%25253B%252520i%252520%25253C%25253D%25252010%25253B%252520i%25252B%25252B%2529%25257B%25250A%252520%252520%252520%252520setTimeout%2528function%252520%2528%2529%25257B%25250A%252520%252520%252520%252520console.log%2528i%2529%25253B%25250A%252520%252520%252520%252520%25257D%25252C%252520i%252520%252A%2525201000%2529%25253B%25250A%252520%252520%25257D%25250A%252520%252520console.log%2528%252522Learn%252522%2529%25250A%25257D%25250Ax%2528%2529%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Dauto%26width%3D614%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%25252520x%252528%252529%2525257B%2525250A%25252520%25252520for%25252520%252528let%25252520i%25252520%2525253D%252525201%2525253B%25252520i%25252520%2525253C%2525253D%2525252010%2525253B%25252520i%2525252B%2525252B%252529%2525257B%2525250A%25252520%25252520%25252520%25252520setTimeout%252528function%25252520%252528%252529%2525257B%2525250A%25252520%25252520%25252520%25252520console.log%252528i%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%2525257D%2525252C%25252520i%25252520%25252A%252525201000%252529%2525253B%2525250A%25252520%25252520%2525257D%2525250A%25252520%25252520console.log%252528%25252522Learn%25252522%252529%2525250A%2525257D%2525250Ax%252528%252529%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/624028d554a886ebc801783c62c2b72e/href">https://medium.com/media/624028d554a886ebc801783c62c2b72e/href</a></iframe><p>Let’s run and see output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*j2LD4RHaVcdoXhiJqVKiLw.png" /></figure><p>It worked 🎉🎉</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FTluN63Wgq3ivIqpeqa%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FTluN63Wgq3ivIqpeqa%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FTluN63Wgq3ivIqpeqa%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a573ae499a80ba91209c6c4debe3d54/href">https://medium.com/media/3a573ae499a80ba91209c6c4debe3d54/href</a></iframe><h4>Let’s just revise again, what actually happened because of <em>let</em>:</h4><p>1. When loop started with <em>i = 1</em> , function formed a closure with new variable itself.<br>2. After <em>i++</em> , when function formed closure again, it does have new variable with value 2 and saves it.<br>3. And so on. This way it forms it makes 10 copies of <em>variable i </em>and forms closure with each and every function.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FXR9Dp54ZC4dji%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FXR9Dp54ZC4dji%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FXR9Dp54ZC4dji%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="261" frameborder="0" scrolling="no"><a href="https://medium.com/media/555aa009f0f2a80ceb08a30b0ca0029d/href">https://medium.com/media/555aa009f0f2a80ceb08a30b0ca0029d/href</a></iframe><h4>So, Next time someone asks you what will be the difference in output of below two cases and why? You know the answer 😎</h4><h4>Case 1:</h4><pre>function x(){<br>  for (var i = 1; i &lt;= 10; i++){  // using var here <br>    setTimeout(function (){<br>    console.log(i);<br>    }, i * 1000);<br>  }<br>  console.log(&quot;Learn&quot;)<br>}<br>x();</pre><h4>Case 2:</h4><pre>function x(){<br>  for (let i = 1; i &lt;= 10; i++){  // using let here <br>    setTimeout(function (){<br>    console.log(i);<br>    }, i * 1000);<br>  }<br>  console.log(&quot;Learn&quot;)<br>}<br>x();</pre><p><strong>Answer</strong>: <em>let is Block Scoped and it’s creates a new copy every time until loop is executed.</em></p><h4>And Twist again 🤭 : What If you have to only use <em>var and prints 1,2,3,..10 every second? What to do?</em></h4><p>Think a bit , what could be the solution?<br><strong>Trick is , we have to make a new copy of </strong><strong><em>variable i </em>every time.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528171%252C%2B184%252C%2B195%252C%2B1%2529%26t%3Dseti%26wt%3Dnone%26l%3Dauto%26width%3D614%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%252520x%2528%2529%25257B%25250A%252520%252520for%252520%2528let%252520i%252520%25253D%2525201%25253B%252520i%252520%25253C%25253D%25252010%25253B%252520i%25252B%25252B%2529%25257B%25250A%252520%252520%252520%252520function%252520close%2528i%2529%25257B%25250A%252520%252520%252520%252520%252520%252520setTimeout%2528function%252520%2528%2529%25257B%25250A%252520%252520%252520%252520%252520%252520console.log%2528i%2529%25253B%25250A%252520%252520%252520%252520%252520%252520%25257D%25252C%252520i%252520%252A%2525201000%2529%25253B%25250A%252520%252520%252520%252520%25257D%25250A%252520%252520%252520%252520close%2528i%2529%25253B%252520%252520%25250A%252520%252520%25257D%25250A%252520%252520console.log%2528%252522Learn%252522%2529%25250A%25257D%25250Ax%2528%2529%25253B&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528171%25252C%2B184%25252C%2B195%25252C%2B1%252529%26t%3Dseti%26wt%3Dnone%26l%3Dauto%26width%3D614%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dfalse%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3Dfunction%25252520x%252528%252529%2525257B%2525250A%25252520%25252520for%25252520%252528let%25252520i%25252520%2525253D%252525201%2525253B%25252520i%25252520%2525253C%2525253D%2525252010%2525253B%25252520i%2525252B%2525252B%252529%2525257B%2525250A%25252520%25252520%25252520%25252520function%25252520close%252528i%252529%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520setTimeout%252528function%25252520%252528%252529%2525257B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520console.log%252528i%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%25252520%25252520%2525257D%2525252C%25252520i%25252520%25252A%252525201000%252529%2525253B%2525250A%25252520%25252520%25252520%25252520%2525257D%2525250A%25252520%25252520%25252520%25252520close%252528i%252529%2525253B%25252520%25252520%2525250A%25252520%25252520%2525257D%2525250A%25252520%25252520console.log%252528%25252522Learn%25252522%252529%2525250A%2525257D%2525250Ax%252528%252529%2525253B&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/366e75cb67a2fb9facb3958fd8e28743/href">https://medium.com/media/366e75cb67a2fb9facb3958fd8e28743/href</a></iframe><p>So, we will create a new function <strong><em>close() </em></strong>and wrap<strong><em> </em></strong><em>setTimeout() </em>inside that. And pass <em>i </em>every time in calling.</p><h4>Why it will work? 😬</h4><p>Because every time you call <strong><em>close()</em></strong> function with<strong><em> </em></strong><em>i , </em>it creates a new copy of<em> </em><em>i </em>for<em> </em><em>setTimeout() </em>😎.</p><p>And that’s it. We covered how <em>setTimeout() </em>works and connected to closures. 👏🏼</p><blockquote>Note: I found one more article <a href="https://medium.com/swlh/playing-with-javascript-settimeout-11201cd0d0c">here</a> which also explains setTimeout() with good examples. Try reading it.</blockquote><h4>Next 👩🏻‍🏫 ⏭️ : <a href="https://medium.com/@swati.developer17/part-13-closure-js-interview-questions-f31c1be77d3e">Part 13: Closure JS Interview Questions 🤯</a></h4><p>Thanks for reading the article ❤️</p><h3>⭐️ Happy Coding. ⭐️</h3><p>Hopefully, you learned something today! Before you go:</p><ul><li>👏 Clap for the story and follow <a href="https://medium.com/@swati.developer17">Swati Redhu</a> 👩🏻‍💻</li><li>📰 View more content in the <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">JavaScript learning roadmap 2023 — The Ultimate Guide ❤️</a></li><li>🔔 Follow on : <a href="https://www.linkedin.com/in/swati-redhu-451723144/">LinkedIn</a></li></ul><p>🚀👉 <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">C<strong>lear your JS basics and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfa0d402831f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 11: Closures in JS ‍♀️]]></title>
            <link>https://medium.com/@swati.developer17/part-11-closures-in-js-%EF%B8%8F-e0874a86b2de?source=rss-a0b4a561a04a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0874a86b2de</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[closure-in-javascript]]></category>
            <category><![CDATA[closure]]></category>
            <dc:creator><![CDATA[Swati Redhu]]></dc:creator>
            <pubDate>Wed, 21 Jun 2023 09:47:57 GMT</pubDate>
            <atom:updated>2023-11-24T02:39:33.867Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FB0yuJkSMziXeK6SoFe%2Fvideo&amp;display_name=GIPHY&amp;url=https%3A%2F%2Fgiphy.com%2Fclips%2FAnimationOnFOX-the-simpsons-fox-foxtv-B0yuJkSMziXeK6SoFe&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2FB0yuJkSMziXeK6SoFe%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="480" height="270" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f2f1813ec7755c73a7bf079cf2bbf1f/href">https://medium.com/media/7f2f1813ec7755c73a7bf079cf2bbf1f/href</a></iframe><h3>Prerequisite:</h3><p>If you don’t understand concept of how Lexical scope works, I highly recommend you to read below :</p><ol><li><a href="https://medium.com/@swati.developer17/part-8-scope-chain-scope-and-lexical-environment-5214a5667ab7">Part 8: Scope Chain, Scope and Lexical Environment 🧐</a></li><li><a href="https://medium.com/@swati.developer17/part-9-let-const-and-temporal-dead-zone-in-js-65ce34431bb8">Part 9 : let, const and Temporal Dead Zone in JS 🧐</a></li><li><a href="https://medium.com/@swati.developer17/part-10-block-scope-function-scope-and-shadowing-in-js-eb0043b93588">Part 10 : Block Scope, Function Scope and Shadowing in JS</a>.</li></ol><p>— — — — — — — — — — — — — — — — — — — — — —— — — — —</p><p>Let’s start with an example</p><pre>function x(){<br>  var a = 10;<br>  function y(){<br>    console.log(a);<br>  }<br>  y();<br>}<br>x();</pre><p>Because of JS lexical scope concept, so when <em>y()</em> function is invoked and executed, it ‘ll try to find <em>a i</em>nside local memory scope. If not found there, then it goes to <strong><em>Lexical Parent</em></strong> and search there.</p><p><strong>What should be the output?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*xdHQi_PRD8ByZre7K4ddpg.png" /></figure><p>Let’s put debugger and check what is happening in background:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*GrBSBSRUUJpJfIMOILZK6w.png" /></figure><blockquote><strong>Closure</strong> means that a function bind together with its lexical environment or you can say “<strong><em>function along with it’s lexical scope”</em></strong></blockquote><h4>Why it says Closure (x) in above screenshot?</h4><p>We hold program on to <em>y() at line 4 so inside </em><em>y() , it forms closure with the variable </em><em>a which was part of function </em><em>x() lexical scope.</em></p><p>Or you can say, function <em>y() is bind to variable of function </em><em>x() . So , it forms a closure and it has access to it’s parent lexical scope.</em></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p>Let’s take another example:</p><pre>function x(){<br>  var a = 10;<br>  function y(){<br>    console.log(a);<br>  }<br>  return y;<br>}<br>var z = x();<br>console.log(z);</pre><blockquote>Closures come into picture when you try to return these functions outside.</blockquote><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*_D4zJ1RDqL09rf5j5gvO1w.png" /></figure><p>So, as you can see function <em>y()</em>is returned in to <em>variable z </em>now.</p><p>At Line 8, function x<em>()</em>is gone from memory space, completely vanish and no longer in call stack.<br>So, now <em>variable z</em> contains function <em>y()</em>.</p><h4>Question: As function y( ) is returned and no longer reside inside function x( ). How will this behave in other lexical scope?</h4><p>Let’s try calling function <em>z()</em>. See below:</p><pre>function x(){<br>  var a = 10;<br>  function y(){<br>    console.log(a);<br>  }<br>  return y;<br>}<br>var z = x();<br>console.log(z);<br>z();  // call function here</pre><p>As function <em>y()</em> is trying print variable a but variable a is not in global scope and function <em>x()</em>is not in call stack anymore.<strong><em> What will happen to variable a? What will invoking function </em></strong><em>z()</em><strong><em> will print now?</em></strong></p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*1K0TcdqH0Fgq_8nuPYSDtg.png" /></figure><p>As you can see, <strong><em>it printed 10.</em></strong></p><p>Here comes <strong>concept of closure</strong>, When a function is returned from another function, they still maintains their Lexical Scope. They remember where they were actually present.</p><p>We can say when function <em>y()</em> was returned, not only function code was returned but closure was returned.</p><p>That closure enclosed function along with Lexical scope is returned.</p><p><strong>******************************<br>IDK Why but I like to compare Closures to daughters in Indian family’s. 🤷🏻‍♀️</strong></p><p><strong>Like when a daughter got married and went to in-laws house , she remembers from where she came , family member names and other family details and history.</strong></p><p><strong>In same way , when function is returned, it not only return code but returns lexical scope as well which is called Closures.</strong></p><p><strong>Physical body represents function body<br>Memory/details from her parents represents Lexical scope<br>Daughter represents Closures 🫣</strong></p><p><strong>*********************************</strong></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><h4>Let’s take another example:</h4><pre>function x(){<br>  var a = 10;<br>  function y(){<br>    console.log(a);<br>  }<br>  a = 100;<br>  return y;<br>}<br>var z = x();<br>console.log(z);<br>z();</pre><p>What should be output now?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*39Kq4lYIgn8dqDSD5HgtJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*MCgFR-dtASr5f4jkrkrxJA.png" /></figure><p>Because <strong>console.log(a) doesn’t refers 10</strong>. <strong><em>It is reference to the variable not the value. So, reference to variable persist.</em></strong></p><p><strong>***********************************<br>Again let’s take daughter’s example🫣<br>She remember her brother so first brother was staying at place A but then moved to place B. So, reference is to the brother not to the address. Address can keep changing.<br>Reference to the variable persist not the value.</strong></p><p><strong>*************************************</strong></p><p>So, now variable a’s reference points to 100 . That means 100 is still in memory preserved because of closure. When function <em>x()</em> was gone , it is not garbage collected, because it has to be used later. That’s why 100 printed not 10.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><h4>Let’s take another example again :</h4><pre>function z(){<br>  var b = 20;<br>  function x(){<br>    var a = 10;<br>    function y(){<br>      console.log(a,b);<br>    }<br>    y(); // call function here<br>  }<br>  x(); // call function here<br>}<br><br>z(); // call outer function here</pre><p>Run it and add debugger in browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*Oc4Rl9gyILIdrjWH23UBsA.png" /></figure><p>As you can see in above, there are two closures : Closure (x) and Closure (z).</p><p>Closure (x) =&gt; for parent<br>Closure (z) =&gt; For parent’s parent</p><p>So, if <em>y()</em> is being returned anywhere then value of <em>variable a </em>and <em>variable b </em>are not garbage collected.</p><p><strong>********************************************<br>If I may again take daughter’s example🫣<br>Daughter remembers her mother’s family as well i.e grand parents .<br>Her mother was also someone’s daughter so she can also be represented as Closure.</strong></p><p><strong>Mother = </strong><em>function x()</em><strong>=&gt; knows </strong><em>variable b</em><strong>because it is it’s Lexical scope which is </strong><em>function z()</em><strong><br>Daughter = </strong><em>function y()</em><strong>=&gt; knows </strong><em>variable a</em><strong> because it is it’s Lexical scope which is </strong><em>function x()</em><strong>, then further </strong><em>function x()</em><strong> knows </strong><em>variable b </em><strong>in same way</strong></p><p><strong>********************************************</strong></p><blockquote>So, Because of Closures, as these functions remember things even when they are not in their lexical scope, this makes JS language very powerful.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FyWli7pIg5myys%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FyWli7pIg5myys%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FyWli7pIg5myys%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/173a407b34f4160312a530a6e4dea723/href">https://medium.com/media/173a407b34f4160312a530a6e4dea723/href</a></iframe><h4>Few Common usage of Closures are :</h4><ol><li>Module Design Patterns</li><li>Currying</li><li>Function Like once</li><li>memoize</li><li>maintaining state in async world</li><li>setTimeouts</li><li>Iterators</li><li>Data Hiding and Encapsulation</li></ol><h4>Disadvantages of Closures:</h4><ol><li>There could be over consumption of memory because every time a closure is formed, it consumes a lot of memory.</li><li>Those closed over variables are not Garbage Collected, so it means it is accumulating a lot of memory</li><li>If not handled properly, it can lead to memory leaks.</li></ol><h4><strong>Next 👩🏻‍🏫 ⏭️ :</strong> <a href="https://medium.com/@swati.developer17/part-12-settimeout-closures-interview-questions-cfa0d402831f">Part 12: setTimeout + Closures Interview Questions 🤓</a></h4><p>Thanks for reading the article ❤️</p><h3>⭐️ Happy Coding. ⭐️</h3><p>Hopefully, you learned something today! Before you go:</p><ul><li>👏 Clap for the story and follow <a href="https://medium.com/@swati.developer17">Swati Redhu</a> 👩🏻‍💻</li><li>📰 View more content in the <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">JavaScript learning roadmap 2023 — The Ultimate Guide ❤️</a></li><li>🔔 Follow on : <a href="https://www.linkedin.com/in/swati-redhu-451723144/">LinkedIn</a></li></ul><p>🚀👉 <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">C<strong>lear your JS basics and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0874a86b2de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What does “use strict” do in JavaScript, and what is the reasoning behind it?]]></title>
            <link>https://medium.com/@swati.developer17/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it-3ea5c14328a6?source=rss-a0b4a561a04a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ea5c14328a6</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[strict-mode]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Swati Redhu]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 14:08:42 GMT</pubDate>
            <atom:updated>2023-06-21T12:09:40.489Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Problem</h3><p>JavaScript developers often add the string &quot;use strict&quot; in their code. What does &quot;use strict&quot; do in JavaScript? What is the reason behind using it? Are there any benefits of using it?</p><h3>The Solution</h3><p>The &quot;use strict&quot; directive enables <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">JavaScript’s strict mode</a>.</p><p>JavaScript’s strict mode was introduced in <a href="https://en.wikipedia.org/wiki/ECMAScript">ECMAScript 5</a>. It enforces stricter parsing and error handling on the code at runtime. It also helps you write cleaner code and catch errors and bugs that might otherwise go unnoticed.</p><h3>Usage</h3><p>You can enable strict mode in two different ways, <strong>globally and locally.</strong></p><p>Enable strict mode globally by adding the string &quot;use strict&quot; as the first statement in your file. All subsequent code in the script will execute in strict mode.</p><pre>// First line inside a .js file<br>&#39;use strict&#39;;<br>// rest of the script</pre><p>Enable strict mode locally by adding the string &quot;use strict&quot; as the first statement inside a function. Using strict mode locally inside the function will enforce stricter parsing only within the context of that function.</p><pre>// Inside a function<br>function strict_function() {<br>  &#39;use strict&#39;; // rest of the function<br>}</pre><p><strong>It is important to note that JavaScript modules are in strict mode by default.</strong></p><h3>Benefits of Using Strict Mode</h3><p>Enabling strict mode in your code has many benefits.</p><p>Here are some examples:</p><p><strong>Prevent accidental creation of global variables</strong></p><p>Strict mode is useful in situations where you can accidentally create a global binding. Accidental global variables can create bugs in the code. For example:</p><pre>&#39;use strict&#39;;<br>x = 9; // ReferenceError: x is not defined<br>function strict_function() {<br>  &#39;use strict&#39;;<br>  x = &#39;I am a strict function&#39;;<br>  console.log(x);<br>}<br>strict_function(); // ReferenceError: x is not defined</pre><p>A common scenario in which you can accidentally create global variables is within for loops. With strict mode enabled, JavaScript will throw an error if you forget to add the let keyword before the loop counter variable (counter in the following example):</p><pre>function catchTheProblem() {<br>  &#39;use strict&#39;;<br>  for (counter = 0; counter &lt; 10; counter++) {<br>    console.log(&#39;Catch me if you can!&#39;);<br>  }<br>}<br>catchTheProblem(); // ReferenceError: counter is not defined</pre><p>If you don’t use strict mode here, JavaScript will create a global variable with the name counter.</p><p><strong>Catch typing mistakes in variable names</strong></p><p>If you don’t use strict mode, a typing error can create a new variable, which can cause bugs down the line. For example:</p><pre>&#39;use strict&#39;;<br>let misspelledVariable;<br>misspelleVariable = 9; // This line will throw en error due to // misspelling of &quot;misspelledVariable&quot;</pre><p><strong>Prevent accidental deleting</strong></p><p>Deleting a variable, a function, or an argument will result in an error:</p><pre>&#39;use strict&#39;;<br>let a = 9;<br>delete a; //This will cause an error<br>function testFunction() {}<br>delete testFunction; // This will cause an error<br>function testWithArgs(arg) {<br>  delete arg; // This will cause an error<br>}</pre><p><strong>Prevent duplicating parameter names in a function</strong></p><p>Duplicating the parameter’s names will result in an error:</p><pre>function test(arg1, arg1) {} // This will cause an error</pre><p><strong>Prevent writing to read-only properties</strong></p><p>If you set an object’s writable value to false, and then try to assign a new value to the object, strict mode will throw an error:</p><pre>&#39;use strict&#39;;<br>const obj = {};<br>Object.defineProperty(obj, &#39;x&#39;, { value: 0, writable: false });<br>obj.x = 9; // This will cause an error<br></pre><h3>Happy Coding. ⭐️</h3><p>Hopefully, you learned something today! Before you go:</p><ul><li>👏 Clap for the story and follow <a href="https://medium.com/@swati.developer17">Swati Redhu</a> 👩🏻‍💻</li><li>📰 View more content in the <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">JavaScript learning roadmap 2023 — The Ultimate Guide ❤️</a></li><li>🔔 Follow on : <a href="https://www.linkedin.com/in/swati-redhu-451723144/">LinkedIn</a></li></ul><p>🚀👉 <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">C<strong>lear your JS basics and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ea5c14328a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 10 : Block Scope, Function Scope and Shadowing in JS.]]></title>
            <link>https://medium.com/@swati.developer17/part-10-block-scope-function-scope-and-shadowing-in-js-eb0043b93588?source=rss-a0b4a561a04a------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb0043b93588</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[function-scope]]></category>
            <category><![CDATA[block-scope]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Swati Redhu]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 13:44:57 GMT</pubDate>
            <atom:updated>2023-06-21T12:09:11.557Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 10 : Block Scope, Function Scope and Shadowing in JS.</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FSvFocn0wNMx0iv2rYz%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FSvFocn0wNMx0iv2rYz%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FSvFocn0wNMx0iv2rYz%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/80d344ea193f7eec9f5280b36366322b/href">https://medium.com/media/80d344ea193f7eec9f5280b36366322b/href</a></iframe><h4>What is Block ?</h4><ol><li>Block is defined by curly braces i.e { .. }</li><li>Block is also know as <strong>Compound Statement.</strong></li></ol><h4>Why Block is required in JS?</h4><p>Block is used to combine multiple javascript statements into one group.</p><h4>Why we need to group multiple statements at one place?</h4><p>we group multiple statements in a block so that we can use it where JS expects one statement</p><p>Example: if statement only expecting one statement but we provided multiple statements using curly braces. This is a Block.</p><pre>if(true){<br>// Compound Statement<br>var a = 10;<br>console.log(a);<br>}</pre><h3>— — — — — — — — — — — — — — — — — — — — — — —</h3><h3>What is Block Scoped?</h3><p>Block Scoped means what all variables and functions we can access inside block.</p><p>To understand in details, let’s take an example and run it:</p><pre>{<br>var a = 10;<br>let b = 20;<br>const c = 30;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*BV3fqx0VpMezPqrOHqn5Ow.png" /></figure><p>So, “b” and “c” are inside Block Scope which is separate space which is reserved for block only. But “a” is hoisted inside global object.<br>From here the statement comes in picture that:</p><blockquote>let and const are block scoped.</blockquote><p>Therefore, you can’t access <em>let </em>and <em>const</em> type variable outside the scope .</p><pre>{<br>var a = 10;<br>let b = 20;<br>const c = 30;<br>console.log(&quot;Inside Block a= &quot;,a);<br>console.log(&quot;Inside Block b= &quot;,b);<br>console.log(&quot;Inside Block c= &quot;,c);<br>}<br>console.log(&quot;Outside Block a= &quot;,a);<br>console.log(&quot;Outside Block b= &quot;,b);<br>console.log(&quot;Outside Block c= &quot;,c);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*i4szCtvhrnM5bjMNNCkuqA.png" /></figure><p>So, it is saying <strong><em>“Reference Error: b is not defined” . Because “b” is not in global scope.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*-nwGN2uYcurFANwiiOimTg.png" /></figure><h4>— — — — — — — — — — — — — — — — — — — — — — — — — — — —</h4><h4>What is Shadowing in JS?</h4><p>If we have same named variable outside the block, then block variable will shadowed outside block variable.<br>Example:</p><pre>var a = 12;<br>{<br>var a = 10;<br>let b = 20;<br>const c = 30;<br>console.log(&quot;Inside Block a= &quot;,a);<br>console.log(&quot;Inside Block b= &quot;,b);<br>console.log(&quot;Inside Block c= &quot;,c);<br>}</pre><h4>What will log print for “a” now?</h4><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*btNSS30BHF7Fc77UmIEEgA.png" /></figure><p>It prints 10. That means line 3 variable shadowed Line 1 variable.</p><h4>* What If I try to print var “a” outside block ? What should it print 10 or 12?</h4><pre>var a = 12;<br>{<br>var a = 10;<br>let b = 20;<br>const c = 30;<br>console.log(&quot;Inside Block a= &quot;,a);<br>console.log(&quot;Inside Block b= &quot;,b);<br>console.log(&quot;Inside Block c= &quot;,c);<br>}<br>console.log(&quot;Outside Block a= &quot;,a);</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*KmMuP8RwGJ9fYsqN4M624A.png" /></figure><p>So , it prints 10 again. Line number 3 shadowed line 1 and also modified the value for variable. <strong><em>Because they both are pointing to same memory location.</em></strong></p><h4>* Now what happens with “let” type variable?</h4><pre>let b= 12;<br>{<br>var a = 10;<br>let b = 20;<br>const c = 30;<br>console.log(&quot;Inside Block a= &quot;,a);<br>console.log(&quot;Inside Block b= &quot;,b);<br>console.log(&quot;Inside Block c= &quot;,c);<br>}<br>console.log(&quot;Outside Block b= &quot;,b);</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*bFyw7m0i4GIqEyEexxCZhA.png" /></figure><p>Now, Inside block variable “b” prints 20 but outside block , it prints 12.<br>Because scopes are different in case of <strong><em>let </em></strong>type variable. Try adding debugger and check scope of variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*Xo2VniBW7sLcoLtkaqxGPg.png" /></figure><p><strong><em>In above screenshot, you can see three scopes ::::</em></strong></p><ol><li><strong><em>Global: memory reserved for var</em></strong></li><li><strong><em>Script: separate memory for</em></strong><em>let</em><strong><em>and const outside block scope</em></strong></li><li><strong><em>Block: separate memory for variables inside scope</em></strong></li></ol><h4>* Now what happens with “const” type variable?</h4><pre>const c= 12;<br>{<br>var a = 10;<br>let b = 20;<br>const c = 30;<br>console.log(&quot;Inside Block a= &quot;,a);<br>console.log(&quot;Inside Block b= &quot;,b);<br>console.log(&quot;Inside Block c= &quot;,c);<br>}<br>console.log(&quot;Outside Block c= &quot;,c);</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*1miCAMOgVl3kijk-kzYG2A.png" /></figure><p>Now, Inside block variable “c” prints 30 but outside block , it prints 12.<br>Because scopes are different in case of <em>const</em><strong><em> </em></strong>type variable. Try adding debugger and check scope of variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*qRMAvFb_i0YNAuXIVphz4Q.png" /></figure><p>Again, in above screenshot, we can see 3 scopes.</p><h4>— — — — — — — — — — — — — — — — — — — — — — — — — — — —</h4><h4>Does Shadowing behaves same way in functions?</h4><pre>const c= 12;<br><br>function a() {<br>const c = 30;<br>console.log(&quot;Inside Function c= &quot;,c);<br>}<br><br>a();<br><br>console.log(&quot;Outside Function c= &quot;,c);</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*LSg-oBo5R9YiW1Q9jsoQmw.png" /></figure><p>Now, Inside function variable “c” prints 30 but outside function, it prints 12.<br>Because scopes are different in case of <em>const</em><strong><em> </em></strong>type variable. Try adding debugger and check scope of variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*Tr229MNSbf064RdJ_pjp7A.png" /></figure><h4>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —</h4><h4>What is Illegal shadowing?</h4><h4>Case 1: If outside block variable is “let” and inside is “var” type? Will it still gives error?</h4><pre>let a = 20;<br>{<br>    var a = 10;<br>}</pre><p>Can we do this? What will be the output now?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*U8Z421y4JY-FwsKLzIgTWA.png" /></figure><p>So, this is known as Illegal Shadowing.</p><h4>Case 2: But what If outside block variable is “var” and inside is “let” type? Will it still gives error?</h4><pre>var a = 20;<br>{<br>    let a = 10;<br>}<br>console.log(a);</pre><p>Answer is <strong>NO</strong> .It won’t give any error and work perfectly fine.</p><h4>WHY?</h4><p>Because if a variable is shadowing something, it should not cross the boundary of it’s scope.</p><p>In Case 1: <em>var</em> is not blocked scope. <strong><em>“var” is function scoped. So you can do it inside a function.</em></strong></p><pre>let a = 20;<br>function b() {<br>    var a = 10;<br>}<br>b();</pre><p>Now, in this case, <em>var a </em>is not interfering with <em>let a </em>as both have different memory.</p><h4>Now, Try below on your own, add debugger and see how scopes work:</h4><p>Case 1:</p><pre>const a = 20;<br>{<br>  const a = 30;<br>  console.log(&quot;Inside Block 1, a = &quot;,a);<br>  {<br>    const a = 40;<br>    console.log(&quot;Inside Block 2, a = &quot;,a);<br>  }<br>}<br>console.log(&quot;Outside Block, a = &quot;,a);</pre><p>Case 2:</p><pre>const a = 20;<br>{<br>  const a = 30;<br>  console.log(&quot;Inside Block 1, a = &quot;,a);<br>  {<br>    console.log(&quot;Inside Block 2, a = &quot;,a);<br>  }<br>}<br>console.log(&quot;Outside Block, a = &quot;,a);</pre><p><strong><em>These examples also cover </em></strong><a href="https://medium.com/@swati.developer17/part-8-scope-chain-scope-and-lexical-environment-5214a5667ab7"><strong><em>Lexical Scope Chain pattern we covered in previous article</em></strong></a><strong><em>.</em></strong></p><p>With this, we cover our basics for Block Scope, Function Scope and Shadowing.</p><h3>⭐️Happy Coding. ⭐️</h3><p>Hopefully, you learned something today! Before you go:</p><ul><li>👏 Clap for the story and follow <a href="https://medium.com/@swati.developer17">Swati Redhu</a> 👩🏻‍💻</li><li>📰 View more content in the <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">JavaScript learning roadmap 2023 — The Ultimate Guide ❤️</a></li><li>🔔 Follow on : <a href="https://www.linkedin.com/in/swati-redhu-451723144/">LinkedIn</a></li></ul><p>🚀👉 <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">C<strong>lear your JS basics and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb0043b93588" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 9 : let, const and Temporal Dead Zone in JS ]]></title>
            <link>https://medium.com/@swati.developer17/part-9-let-const-and-temporal-dead-zone-in-js-65ce34431bb8?source=rss-a0b4a561a04a------2</link>
            <guid isPermaLink="false">https://medium.com/p/65ce34431bb8</guid>
            <category><![CDATA[hoisting]]></category>
            <category><![CDATA[const]]></category>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Swati Redhu]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 10:55:39 GMT</pubDate>
            <atom:updated>2023-06-24T03:58:57.137Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 9 : let, const and Temporal Dead Zone in JS 🧐</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1u01IRKm3cKUH4GU1U%2Fvideo&amp;display_name=GIPHY&amp;url=https%3A%2F%2Fgiphy.com%2Fclips%2Fwork-computer-laptop-1u01IRKm3cKUH4GU1U&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2F1u01IRKm3cKUH4GU1U%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="480" height="270" frameborder="0" scrolling="no"><a href="https://medium.com/media/d763794399086faa24ab5597ef779971/href">https://medium.com/media/d763794399086faa24ab5597ef779971/href</a></iframe><h4><strong>Prerequisite:</strong></h4><ol><li><a href="https://medium.com/@swati.developer17/part-3-hoisting-in-javascript-20c6290b2013">Hoisting in javaScript</a></li><li><a href="https://medium.com/@swati.developer17/part-5-this-keyword-in-js-3e99bdf5b6d2">“this” keyword in JS</a></li></ol><h4>In this article, we’ll cover : :</h4><ol><li>What is Temporal Dead Zone?</li><li>Are let and const declaration hoisted?</li><li>Difference between Syntax Error / Reference Error and Type Error?</li></ol><h4>— — — — — — — — — — — — — — — — — — — — — — — — — — — <br><strong>Are let and const declaration hoisted?</strong></h4><p>Answer is : <strong>YES 👍🏼</strong></p><p>But they are hoisted very differently then var declarations.<br>In interviews, you can say that these are in <strong>Temporal Dead Zone.</strong></p><p>Let’s understand taking an example:</p><pre>let a = 10;<br>var b = 100;</pre><p>In previous hoisting article, we learn that we can access variable “b” even before we have initialised it. Like below</p><pre>console.log(b);<br>let a = 10;<br>var b = 100;</pre><p><strong><em>Reason</em></strong>: Because in JS, memory has been allocated even before any line of code is executed. So, we can access variable “b” even before initialising or declaring.</p><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*Zt2L2QDDTJ57w8kkeTvohA.png" /><figcaption>output</figcaption></figure><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><h4>Question: <strong>What If I try to access variable “a” in same way ? As it is hoisted , Will it give undefined too?</strong></h4><p>Answer is <strong>NO</strong> 👎🏼</p><pre>console.log(a);<br>let a = 10;<br>var b = 100;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*0RXKLgojIN8Z-ax9yuhCuQ.png" /></figure><p>SO, it is saying<strong><em> “Reference Error: Cannot access ‘a’ before initialisation” . </em></strong>i.e you can access “a” only after you assigned or initialised some value to “a”.</p><p>Let’s try below code:</p><pre>let a = 10;<br>console.log(a);<br>var b = 100;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*koFbPtQ9trDcrFctjdk5ew.png" /></figure><p>Now, you can see we were able to access “a”. console prints value 10.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><h4>Question: How to know whether any variable is hoisted or not??</h4><p>Let’s see that in browser, add a debugger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*SawFE0gwSSkOL1lZMHZCOA.png" /></figure><p>Now, If you see both variables “a” and “b” are in scope with value <strong>undefined</strong> but <strong><em>“a” is under “script” where “b” is in Global memory space.</em></strong></p><p>To summarise: “<strong><em>let</em></strong>” and “<strong><em>const</em></strong>” type variables will be allocated memory but that is not in Global Space. They are hoisted but not stored in global space. And this memory is not accessible until you put some value into that.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h4>Question: What is Temporal Dead Zone??</h4><p>It is the time since when <em>let</em> variable was hoisted and till it is initialised some value.</p><p>So, <em>whenever you try to access any let or const variable in Temporal Dead Zone, it gives you </em><strong><em>Reference Error.</em></strong></p><pre>console.log(a);<br>let a = 10;<br>console.log(a);<br>var b = 100;</pre><p>So, In above example, until Line 2 : <em>let a = 10; . </em><strong><em>“a” is in Temporal Dead Zone and gives you Reference Error at Line 1. <br></em></strong>After Line 2, at Line 3: you can access variable a.</p><h4>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br><a href="https://medium.com/@swati.developer17/part-5-this-keyword-in-js-3e99bdf5b6d2">In previous article of “this” keyword in JS</a>, we tried to access variables using “this” and “window” keywords. Let’s just try that too.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*WbVZ88VXpEYqT_q-uHyNmA.gif" /></figure><p>As you can see above, <strong><em>we are not able to access “a” using “window” and “this” keyword. It keeps giving “undefined”.</em></strong></p><p>Reason: “this” and “window” represents global space and memory allocated to “a” was different then global object. So, this shows, <strong><em>“let” is strict then “var”.</em></strong></p><h4>— — — — — — — — — — — — — — — — — — — — — — — — — — -</h4><h4>Question: Can we re-declare “let” variable?</h4><p>Answer is <strong>NO</strong> 👎🏼</p><pre>let a = 10;<br>let a = 100;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*Pe7PYQKJK8mA1HzGK_-Gag.png" /></figure><p>SO, it is saying<strong><em> “Syntax Error: Identifier ‘a’ has already been declared” .</em></strong></p><p>Also, JS will not run any line of code if it sees redeclaration. It will not reach any line of code.</p><h4>what If I try below ?</h4><pre>let a = 10;<br>var a = 100;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*IPfDnid40KajpCOOLci2YQ.png" /></figure><p>Same again: <strong><em>“Syntax Error: Identifier ‘a’ has already been declared” . “let” variable can’t be declared again with same name again in same scope.</em></strong></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><h4>Question: Can we re-declare “var” variable?</h4><p>Answer is <strong>YES</strong> 👍🏼</p><pre>var a = 10;<br>var a = 100;</pre><p>No error when you run code.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><h4>Question: Can we re-declare “const” variable?</h4><p>Answer is <strong>NO</strong> 👎🏼</p><pre>var a = 10;<br>const b= 100;<br>const b= 1000;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*h3hgvhVkjScO4l-XGl9ctQ.png" /></figure><p>“const” variable can’t be declared again with same name in same scope.</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><h4>What If I run below code?</h4><pre>let a;<br>const b;<br>var c;<br><br>a = 10;<br>b = 100;<br>c = 1000;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*EJWsmQU0plFQiQqi4QsUMw.png" /></figure><p>SO, it is saying<strong><em> “Syntax Error: Missing Initializer in const declaration.” This means “const” variable needs to be intialised and declared in same line.</em></strong></p><blockquote>“const needs to be initialised and declared in same line”</blockquote><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><h4>What If I try to assign some value again to “const” variable?</h4><pre>let a = 10;<br>const b = 100;<br><br><br>a = 20;<br>b = 200;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*zlgMk8hksWpF4a7E47cYgQ.png" /></figure><p>SO, it is saying<strong><em> “Type Error: Assignment to constant variable.” You can not assign value again to “const” type variable.</em></strong></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -</p><p>Now, As we have three different ways to declare a variable using let, var and const.</p><h4>Which one we should use?</h4><ol><li>const : whenever you put some value which is not going to change later, use const.</li><li>let: As let has Temporal dead zone and you won’t run into unexpected errors.</li><li>var: Try to put it aside and not use.</li></ol><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><h4>How to avoid Temporal Dead Zone errors?</h4><p>Try to put all declaration and initialisation on top of scope. This will minimise unexpected errors when logic get called.</p><blockquote>If you still have any queries related to hoisting of var, let and const. Please write down in comments.</blockquote><h3>⭐️Happy Coding. ⭐️</h3><p>Hopefully, you learned something today! Before you go:</p><ul><li>👏 Clap for the story and follow <a href="https://medium.com/@swati.developer17">Swati Redhu</a> 👩🏻‍💻</li><li>📰 View more content in the <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">JavaScript learning roadmap 2023 — The Ultimate Guide ❤️</a></li><li>🔔 Follow on : <a href="https://www.linkedin.com/in/swati-redhu-451723144/">LinkedIn</a></li></ul><p>🚀👉 <a href="https://medium.com/@swati.developer17/javascript-learning-roadmap-2023-the-ultimate-guide-%EF%B8%8F-b13708137f42">C<strong>lear your JS basics and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65ce34431bb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>