Scope & Closure
Oscar Ortiz
Posted on October 15, 2020
If each dead person became a ghost, there’d be more than 100-billion of them haunting us all. Creepy, but cool.
— Neil deGrasse Tyson
In today's article we will be going through some basic javascript fundamentals to help us understand Scope & Closure. 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 & Inheritance, and Classes for powerful paradigms. Let's begin!
Contents
- Global Scope
- Function Scope
- Block Scope
- Hoisting (declaring & initialize)
- Closure
- Conclusion
Intro
How Scope and Closure works in javascript? Scope is defined as which variables we currently have access to and where. 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 lexical environment works.
Global Scope
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. Global 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.
In the example below we are declaring a variable outside of the function and declaring one inside the function. The var1 stores a string ('hello') and var2 inside out greeting function is also storing a string ('world'), we console.log() our variables and get two outputs. The first output we get back is 'hello' because we are calling our console.log out in the Global level where everything is outside of our functions or accessible any where in our code. Our second console.log() outputs 'undefined' 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.
#Javascript Scope and Closure
# Global Scope
# declare variable
const var1 = 'hello';
# Function Scope
function greeting(){
const var2 = 'world';
};
console.log(var1); #output = 'hello'
console.log(var2); #output = 'undefined'
Evolution is the fundamental idea in all of life science - in all of biology.
Bill Nye
Function Scope
How do we access our variables inside functions? Function Scope allows us to declare variables inside functions, where functions exists inside functions but not elsewhere in your code. Functions that are private to that function specifically. The only bad thing about this is that we can not access into a function from the outside and get access to these variables, but functions can reach out and grab variables outside of their scope.
#Javascript Scope and Closure
# Global Scope
# declare variable
const var1 = 'hello';
# Function Scope
function greeting(){
const var2 = 'world';
console.log(var1); # output 'hello';
console.log(var2); # output 'hello';
};
# Invoke function
greeting();
Block Scope
Block level scope is used when we tend to use if / else statements & for loops. Variables declared with either let or const is only available within the statement or loop (like i in a for 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 var, let, and const to declare our variables are block scope works differently for them. Block Statement MDN docs has a great wiki article.
Hoisting
Normally when we declare our variables we tend to do it on the same line like this.
var greeting = 'hello world';
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.
# declare variable
var greeting;
# store string
greeting = 'hello world';
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?
# use variable
console.log(myVar);
# declare and initialize variable
aar myVar = 'variable';
The answer to this is undefined. 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
var myVar; # undefined
console.log(myVar); # output myVar
myVar = 'variable'
Another example.
sayHello();
function sayHello(){
console.log('hello')
}
The output for the code above will be 'hello'. Why? This means that functions can be used before they are declared or initialized. This only works with declared functions, not function expressions. Declarations with var & function keyword are hoisted and can therefore be used anywhere in a script. These will return undefined if not yet initialized.
Keywords let & const are not hoisted which means they can not be used anywhere without throwing a ReferenceError. So at the end you can't use let & const variables before given them a value.
Closure
What is closure? How does closure help us understand javascript? When a function is declared it also creates a new scope. Variables that are declared within that function's scope will be enclosed in a lexical/private scope that belongs to that function. Functions also look outward for context, if some variables are not defined inside the function scope, the function will look outside the scope chain and search for a variable that is referenced in the outer scope. This is what closure is all about.
Conclusion
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.
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!
Posted on October 15, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.