Scope & Closure
Tags: javascript, beginners, tutorial, webdev
Published: 2020-10-15 20:15:16

<!-- wp:paragraph -->
<p>If each dead person became a ghost, there’d be more than 100-billion of them haunting us all. Creepy, but cool.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>— Neil deGrasse Tyson</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In today's article we will be going through some basic javascript <strong>fundamentals</strong> to help us understand <strong>Scope &amp; Closure</strong>. When working with future projects that maintain frameworks or even just vanilla js, it's everywhere in today's world wide web. We will break things down into a few sections to have a deep understanding on what different types of levels of scope there are, there is to much information to be cramped in one article so for times sake, we will only talk about Scope and Closure for todays reading, later on we will dig deeper into Array Methods, Prototypes &amp; Inheritance, and Classes for powerful paradigms. Let's begin!</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center"} -->
<h2 class="has-text-align-center">Contents</h2>
<!-- /wp:heading -->

<!-- wp:list {"ordered":true} -->
<ol><li>Global Scope</li><li>Function Scope</li><li>Block Scope</li><li>Hoisting (declaring &amp;  initialize)</li><li>Closure</li><li>Conclusion</li></ol>
<!-- /wp:list -->

<!-- wp:heading {"align":"center"} -->
<h2 class="has-text-align-center">Intro</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>How Scope and Closure works in javascript? <strong><em>Scope is defined as which variables we currently have access to and where.</em></strong> It is very important to know how these fundamentals work as they tend to come up everywhere in code majority of the time and interview questions for new developers to make sure they have an understanding on how the <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures" target="_blank">lexical environment</a> works.  </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center"} -->
<h2 class="has-text-align-center">Global Scope</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>There are different levels of scope that helps us write better code. Scope is a big concept if we were to get really in depth with it, but our goal is to understand the basic concepts on how functions and methods work with each other to get a specific output. There is global scope that I'm assuming we are all familiar with. <strong>Global</strong> scope is where we can access any variable we have created, anywhere in our code.  It should be a bit more clear when you see more code in depth.  <br><br>In the example below we are declaring a variable outside of the function and declaring one inside the function. The <strong>var1</strong> stores a string ('hello') and <strong>var2</strong> inside out greeting function is also storing a string ('world'), we <strong>console.log()</strong> our variables and get two outputs. The first output we get back is 'hello' because we are calling our console.log out in the <strong>Global level</strong> where everything is outside of our functions or accessible any where in our code.  Our second <strong>console.log()</strong> outputs <strong>'undefined'</strong> because we are trying to access a variable stored inside a function. We will dig deeper on why that is going on in the next step. </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>#Javascript Scope and Closure<br><br># Global Scope<br># declare variable<br>const var1 = 'hello';<br><br># Function Scope<br>function greeting(){<br>    const var2 = 'world';<br>};<br>console.log(var1); #output = 'hello'<br>console.log(var2); #output = 'undefined'</code></pre>
<!-- /wp:code -->

<!-- wp:quote {"align":"center"} -->
<blockquote class="wp-block-quote has-text-align-center"><p>Evolution is the fundamental idea in all of life science - in all of biology.</p><cite>Bill Nye</cite></blockquote>
<!-- /wp:quote -->

<!-- wp:heading {"align":"center"} -->
<h2 class="has-text-align-center">Function Scope</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>How do we access our variables inside functions? <strong>Function Scope</strong> allows us to declare variables inside functions, where functions <strong>exists inside</strong> functions but not elsewhere in your code. Functions that are <strong>private</strong> to that function specifically. The only bad thing about this is that we can <strong>not access</strong> into a function from the <strong>outside</strong> and get access to these variables, but functions can reach out and grab variables outside of their scope.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>#Javascript Scope and Closure<br><br># Global Scope<br># declare variable<br>const var1 = 'hello';<br><br># Function Scope<br>function greeting(){<br>    const var2 = 'world';<br>    console.log(var1); # output 'hello';<br>    console.log(var2); # output 'hello';<br>};<br><br># Invoke function<br>greeting();</code></pre>
<!-- /wp:code -->

<!-- wp:heading {"align":"center"} -->
<h2 class="has-text-align-center">Block Scope</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><strong>Block</strong> level scope is used when we tend to use <strong>if / else</strong> statements &amp; <strong>for loops</strong>. Variables declared with either <strong>let</strong> or <strong>const</strong> is only available within the statement or loop (like <strong>i </strong> in a <strong>for</strong> loop). Combining statements (other languages call it compound statements) into blocks is a common practice in javascript. Block scope is another topic on working with <strong>var, let, </strong>and <strong>const</strong> to declare our variables are block scope works differently for them. <a rel="noreferrer noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block" target="_blank">Block Statement MDN</a> docs has a great wiki article. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center"} -->
<h2 class="has-text-align-center">Hoisting</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Normally when we declare our variables we tend to do it on the same line like this. </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>var greeting = 'hello world';</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Typically we don't have to do this according to the rules of javacript, you can also declare them separately and get the same thing which is acceptable. </p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code># declare variable<br>var greeting; <br><br># store string<br>greeting = 'hello world';</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The compiler under the hood takes care declaring all variables before initializing them and before running the rest of the script. This can get tricky once we start to have a lot of lines of code on our file. Given the following information, what will happen if we were to try this code below. What would the output be?</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code># use variable<br>console.log(myVar);<br># declare and initialize variable<br>aar myVar = 'variable';</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The answer to this is <strong>undefined</strong>. Why? Because when our compiler runs, it first declares the variable with a value of undefined, then runs the script. The compiler would interpret this code like this</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>var myVar; # undefined<br>console.log(myVar); # output myVar<br>myVar = 'variable'</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Another example.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>sayHello();<br><br>function sayHello(){<br>    console.log('hello')<br>}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>The output for the code above will be <strong>'hello'</strong>. Why? This means that functions can be used before they are <strong>declared or initialized</strong>.<strong> </strong>This only works with declared functions, not function expressions. Declarations with <strong>var</strong> &amp; <strong>function</strong> keyword are hoisted and can therefore be used anywhere in a script. These will return <strong>undefined</strong> if not yet initialized. <br>Keywords <strong>let</strong> &amp; <strong>const</strong> are not hoisted which means they can not be used anywhere without throwing a <strong>ReferenceError</strong>. So at the end you can't use <strong>let</strong> &amp; <strong> const</strong> variables before given them a value. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center"} -->
<h2 class="has-text-align-center">Closure</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>What is <strong>closure</strong>? How does closure help us understand javascript? When a function is declared it also creates a new <strong>scope.</strong> Variables that are <strong>declared</strong> within that function's scope will be <strong>enclosed</strong> in a lexical/private scope that belongs to that function. Functions also look <strong>outward</strong> for context, if some variables are not defined inside the function scope, the function will look outside the scope <strong>chain</strong> and search for a variable that is referenced in the outer scope. This is what <strong>closure</strong> is all about. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"align":"center"} -->
<h2 class="has-text-align-center">Conclusion</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I hope by the end of this article you managed to learn how to create and understood what is going on in every line of code. It is very important to understand how your code fully works, not only does it help you become a better developer but can also help you use the tools you are working with more efficient.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>These articles are mostly intended for personal use on becoming a better programmer, writer, and grow my programming skills. Feel free to drop any feedback or corrections that you believe that should be made to help me and others. Thank you for your time for sticking this far!</p>
<!-- /wp:paragraph -->