<?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 Muhammad Ali on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Ali on Medium]]></description>
        <link>https://medium.com/@alidiplana?source=rss-237c52b79675------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mcUOWSeqe39TX6NF</url>
            <title>Stories by Muhammad Ali on Medium</title>
            <link>https://medium.com/@alidiplana?source=rss-237c52b79675------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:24:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alidiplana/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[Closure — All you need to know for interview]]></title>
            <link>https://medium.com/@alidiplana/closure-all-you-need-to-know-for-interview-487aeb2869de?source=rss-237c52b79675------2</link>
            <guid isPermaLink="false">https://medium.com/p/487aeb2869de</guid>
            <category><![CDATA[closure-examples]]></category>
            <category><![CDATA[advanced-closure]]></category>
            <category><![CDATA[master-closure]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[closure-interview]]></category>
            <dc:creator><![CDATA[Muhammad Ali]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 10:14:32 GMT</pubDate>
            <atom:updated>2024-03-21T10:14:32.840Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0gcFeyH8p689ZSFt" /><figcaption>Photo by <a href="https://unsplash.com/@sandym10?utm_source=medium&amp;utm_medium=referral">Sandy Millar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Closure — All you need to know for interview</h3><p>Closures play a crucial role in enabling powerful programming techniques and are widely used in various JavaScript frameworks and libraries. In this article, we’ll deep dive into closures, exploring what they are, how they work, and why they are important</p><h3>What is Closure</h3><p>In JavaScript, a function close itself it lexical environments (or its surrounding) is called closure. In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.</p><pre>const num = 10;<br>const fun = () =&gt; {<br>  console.log(num); // 10<br>}</pre><p>In above code snippet, we have created a closure. Bravo 🚀</p><p>Now, let’s look deeper into what lies within these lines of code.</p><p>When we reference the value of num, it is effortlessly accessible within the fun function; otherwise, it would result in an error. Now tricky part is, variable num has enclosed its self with fun function and now it’s part of fun lets see in this example.</p><p>When we reference the value of num, it is effortlessly accessible within the fun function; otherwise, it would result in an error. However, the intriguing aspect arises when we consider the following example:</p><pre>const num = 10;<br>const fun = () =&gt; {<br>  return a;<br>};<br><br>console.dir(fun);</pre><p>In this code snippet, we declare a variable num with a value of 10, and define a function fun . However, we do not invoke the function. Instead, we inspect its properties and structure using console.dir(fun) to examine what the function fun contains.</p><blockquote>console.dir(): Displays an interactive listing of all properties of a specified JavaScript object in a structured format for detailed examination.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*H4PsSGHsdeBDDvGfdm2H5g.png" /></figure><p>Two scopes are at play in this scenario. The first is the Script (local) scope, which contains both the fun function itself and the variable num. The second scope is the global scope, which includes variables and functions declared outside of any function.</p><p>If you&#39;re keen on expanding your understanding of scope, I encourage you to explore this <a href="https://medium.com/@alidiplana/mastering-the-variables-and-their-scope-in-javascript-844b8a1833d4">article</a> further.</p><p>Let’s see another example</p><pre>const fun = () =&gt; {<br>  let num1 = 10;<br>  let num2 = 20;<br>  return () =&gt; {<br>    console.log(num1);<br>  };<br>};<br><br><br>console.dir(fun());</pre><p>In the given code snippet, a function fun is defined which returns another anonymous function. Within fun, two variables num1 and num2 are declared, but only num1 is utilized within the returned inner function. Upon inspection using console.dir(fun())</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*JAd4VeaJYY1xuesjNFeFzg.png" /></figure><p>Specifically, within the closure created by the fun function, the variable num1 is encapsulated, meaning it retains its value and accessibility within the inner function returned by fun(). This encapsulation ensures that num1 remains accessible even after the outer function fun has completed execution.</p><p>On the other hand, num2 exists outside of this closure. As a result, it is not enclosed within the inner function and thus is not accessible or affected by the closure. This differentiation highlights the selective encapsulation facilitated by closures in JavaScript, where only variables referenced within inner functions are retained within the closure scope.</p><h3>Tricky Examples</h3><p>lets see another tricky example</p><pre>const fun = () =&gt; {<br>  let num = 10;<br>  const fun2 = () =&gt; {<br>    console.log(num);<br>  };<br>  num = 20; <br>  return fun2;<br>};<br><br>console.log(fun);</pre><p>In this scenario, what will be printed as we are updating num after functions definition?</p><p>Answer is 20 in question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*LlcG11TVnb4ePTv_EwdSQQ.png" /></figure><p>In this case, when the code runs, it prints out 20.</p><p>Here’s why: even though we update the num variable after defining the fun2 function, fun2 still remembers and uses the updated value. This happens because of how JavaScript handles scope, known as lexical scoping. So, fun2 looks for the value of num not just within its own function, but also in the scope of its parent function, fun, where it finds the updated value of 20.</p><p>If I ever need to use the values from these closures outside of the function, it’s straightforward and effortless to do so. These are all clousers is.</p><h3>Benefits of Closures</h3><p>Closures offer several benefits in JavaScript programming:</p><ol><li>Encapsulation: Closures help with encapsulation by letting inner functions access variables from their parent functions. This means that these variables can be used within the inner function without exposing them to the rest of the program. It’s like keeping certain tools in a toolbox where only the person using the toolbox knows what’s inside, rather than leaving them out in the open for anyone to see.</li><li>Data Privacy: Closures allow for the creation of private variables and methods within functions. This means that variables within the outer function’s scope cannot be accessed from outside. It’s like having a secret stash of goodies inside a locked box — only the function itself can access and manipulate them, keeping them safe from prying eyes.</li><li>Callback Functions: Closures are incredibly useful in scenarios like asynchronous programming, event handling, and callback functions. They help keep track of the context and state of the program even when the code is executed at a later time. It’s like leaving a note for yourself to remember what you were doing and where you left off, so you can pick up right where you left off later on.</li><li>Module Pattern: Closures play a key role in implementing the module pattern in JavaScript. This pattern allows developers to create self-contained, reusable modules with their own private state and methods. It’s like building a mini-fortress around your code, keeping it safe from outside interference and making it easier to manage and reuse.</li></ol><h3>Common Pitfalls</h3><p>While closures are powerful, they can also lead to unintended behavior if not used carefully. Some common pitfalls include:</p><ol><li>Memory Leaks: Closures can keep references to variables in memory even after they are no longer needed, leading to memory leaks if not managed properly.</li><li>Accidental Variable Sharing: Due to the nature of closures, inner functions may unintentionally modify variables in the outer function’s scope, leading to unexpected behavior.</li><li>Performance Overhead: Using closures excessively or unnecessarily can introduce performance overhead, especially in scenarios where large amounts of data are retained in memory.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=487aeb2869de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the Variables and their Scope in Javascript]]></title>
            <link>https://medium.com/@alidiplana/mastering-the-variables-and-their-scope-in-javascript-844b8a1833d4?source=rss-237c52b79675------2</link>
            <guid isPermaLink="false">https://medium.com/p/844b8a1833d4</guid>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[mastering]]></category>
            <category><![CDATA[advanced]]></category>
            <category><![CDATA[javacript]]></category>
            <category><![CDATA[scopes]]></category>
            <dc:creator><![CDATA[Muhammad Ali]]></dc:creator>
            <pubDate>Thu, 28 Jul 2022 09:24:20 GMT</pubDate>
            <atom:updated>2022-07-28T09:29:11.703Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mfpZQTp7UCtla3b-" /><figcaption>Photo by <a href="https://unsplash.com/@blakeconnally?utm_source=medium&amp;utm_medium=referral">Blake Connally</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Variables</h3><p>In ES6, variables are used to store values like strings, numbers, and boolean. For using the variable, we first need to declare it. There are three types to declare variables in javascriptvar, let, const.</p><blockquote>Note: Javascript dynamic typed language i.e. it can automatically determine the data type of the variable based on the value assigned to it.</blockquote><ul><li>var variable that can be re-declared and re-initialized in the program because it has global scope.</li><li>let variable can’t be re-declared but it can be re-initialized in the same scope.</li><li>const variable can’t be re-declared nor be re-initialized in the same scope.</li></ul><p>Let’s see what is scope and how variables work in different scopes.</p><h3>Scope</h3><p>These are the following scopes in JavaScript and let&#39;s discuss them one by one.</p><ul><li>Function Scope</li><li>Block Scope</li><li>Global Scope</li></ul><h4>Function Scope</h4><p>Variables declared inside the function have function scope. They can’t be accessible outside the function because when the function is called, an execution context is created on the stack and all variables that are declared inside the function will be stored in the execution context. When the function is ended, the execution context is deleted from the stack and the data stored in it will be deleted as well. So var, let, const, have function scope. Variables declared inside the function have a <strong>local scope.</strong></p><pre>function greet() {<br>    var a = 1;<br>    let b = 2;<br>    const c = 3;<br>}<br>greet();<br>console.log(a, b, c);</pre><p>It will throw an error that the variable is not declared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*l8Mg8JUr8-Wm2cvIEAH36A.png" /></figure><p>However, we can use a variable outside the function by initializing it as follows:</p><pre>function greet() {<br>    a = 1;<br>}</pre><pre>greet();<br>console.log(a);  //output: 1</pre><p>This way the variable a is initialized in the global execution context. After deleting the execution context (of function), it will still be there in the global execution context.</p><blockquote>Warning: It is bad programming practice. Usually initializing variables in globally is considered a bad practice.</blockquote><h4>Block Scope</h4><p>Variable declared with let and const inside the curly brackets {}, if elseor loops has block scope. It can’t be accessed outside the block scope. <br>Variable declared var does not have block scope. It can be accessed outside the block scope.</p><pre>{<br>    var a = 1;<br>    let b = 2;<br>    const c = 3;<br>}</pre><pre>console.log(a, b, c);</pre><p>It will throw an error for variables b and c that they are not defined.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*3MRKCQQP3uTuqbJRUQMtlw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*SWYP7oasj-ys4wPNtvpv-A.png" /></figure><p>It will not throw an error for var, because var will be stored in the global scope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r6LUoX3bcqQQzER7Vw_Ngw.png" /></figure><h4>Global Scope</h4><p>A variable declared outside the blocks and functions have a Global Scope. Global variables are accessible from anywhere in the file.</p><pre>var a = 1;<br>let b = 2;<br>const c = 3;<br>{<br>    console.log(a, b, c); //output: 1 2 3<br>}</pre><pre>function greet() {<br>    console.log(a, b, c); //output: 1 2 3<br>}<br>greet();</pre><p>var type variable will be stored in global scope but here is an interesting thing. In chrome debugger let and const will be stored in the script scope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxYoT8KvpTyqvBpr3M07Tg.png" /></figure><p>and in the firefox debugger let and const will be stored in block scope.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_8JZb7jd2NtJtJAOGclvA.png" /></figure><p>But it doesn’t matter whether it&#39;s stored in script scope or block scope. If a variable is declared in global scope it can be accessed from anywhere i.e. all the child scopes that are part of the current scope.</p><h4>Summary</h4><p>We have discussed different variable types and their scopes in ES6 and later versions of JS.</p><p>Now I will wrap up the discussion by choosing which one is the best. let and const has an edge over var because they have a limited scope (function and block scope) and are more secure to use in comparison to var which can be accessed globally and a little change in that variable can have a catastrophic effect that may break many flows of the application where that variable is being used.</p><p>Here is a quick visual comparison between var, let and const.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edc0985622c19445796e17ff70f98235/href">https://medium.com/media/edc0985622c19445796e17ff70f98235/href</a></iframe><p>Thank for reading it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=844b8a1833d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>