Hoisting
Hoisting is a feature of JavaScript where a variable may be accessible outside of the code block it was created and defined in. Not understanding the nature of hoisting can potentially cause serious errors that are difficult to diagnose. This module will explain how hoisting works, and introduce the idea of "block scope".
What is hoisting?
Variables declared using the var
keyword (or without using a keyword at all) are hoisted, or lifted, to the top of the code in which it is scoped when the code is compiled. Simply put, it jumps to the top of the global scope. Consider the following:
Remember, there are two parts of the variable:
The Declaration:
var x;
The Initialization:
x = 7;
These parts may be performed at different times, just as written above or at the same time: var x = 7;
.
Hoisting affects the declarion portion exclusively. Meaning that the code block from above with the console.log(x)
will print undefined
, but will not say there's a reference error.
What is block scope?
Introduced in ES 2015, the let
and const
keywords allow for the idea of block scope of code, which attempts to combat the issue of scope leakage. Using the keyword var
to create a variable, or assigning a value to a variable without using a keyword, allows a compiler to establish that variable in the global scope. This leads to the potential for certain information to be available outside of the areas in which it is intended for use, the result of which can be error-prone, insecure code.
Here is an example:
In this example, the variable y is hoisted outside of the code block in which it is declared, thus allowing for it to be accessed in other parts of the application. Replacing the second declaration with let
, however, would restrict the variable to that block of code, and the second console.log(y)
statement would return an undefined error, similar to the end of the previous module. It is best practice to list any variable declarations at the top of each code block in order to reduce scope leak as much as possible.
An additional feature of block scope is that variables with the same name are not treated as the same variable. Consider:
The second x declaration only applies within its code block, and thus is a separate variable from the first x declaration. Similarly, if we were to change the value of x within the code block, it would not affect the value of x outside the code block.
File Location
Practice
In
hoisting.js
, create a variable using each of the three keywordsconst
,let
,var
, and assign them each a value.Inside of a code block, create two additional variables using the
var
andlet
keywords.Print to the console the values of each variable. What happens? Why?
Come up with an example of scope leak, and find a way to prevent the leak from happening.
Last updated