Hoisting is JavaScript's default behaviour of moving declarations to the top (not literally).
What is hoisting?
In simple words, hoisting is using variable and function before they are declared. Meaning variables and function declarations moved to the top of their scope before any other code execution, no matter where they are declared. This doesn't mean literally moving your code to top but, the compilers put the declaration into the memory first in the compile phase. The declarations are processed before any other code executed.
Undefined:
In the above example, when we do
console.log(name)
at first, we get ReferenceError
because name
is not declared previously. But when we check, console.log(typeof name)
we get undefined
as output. It is because undeclared variables are assigned undefined
at the time of execution. The undefined
is a primitive type in JavaScript, just like String, Boolean, and Numbers. It means you have not explicitly assigned any value to that variable.
Variables:
Here, we have used the variable
firstName
before it is declared. And console.log(firstName)
returns undefined
. This doesn't give ReferenceError
. When we do console.log(firstName)
the second time, we get the expected output. Why? Because JavaScript has hoisted variables. And the code looks like below in the interpreter.Only function and variable declarations are hoisted in JavaScript. That is the reason we get undefined when we do
console.log(firstName)
for the very first time. Initializations are not hoisted.
Functions
Similarly, function declarations are moved to the top means they are executed before any other code in the program. Check below code snippet.
It works perfectly fine as if the function
getName()
is defined first and then called. This because the declaration is moved to the top. Below is how the compiler reads through the above code.ES5 - strict mode
By using the strict mode of JavaScript introduced in es5. We can be more careful and alert about using variable declaration. It helps to prevent us from using undeclared variables.
When we are using
firstName
without declaring, we get an error. Read more about strict mode here.
ES6 - let and const
ES6 introduced two new ways of declaring variables in JavaScript let
and const
. Both let
and const
does not support hoisting. Let's see it n practice.
We get an error when using
let
or const
before the declaration. Learn more about let and const in the below article.Understanding let and const.
Kamlesh Chavan ・ May 1 '20 ・ 3 min read
Let us recollect things we learned up above.
- Declaration of functions and variables are moved to the top of their scope in JavaScript. Meaning compiler executes this declaration before any other code.
- Only declarations are hoisted, not the initializations.
- Using strict mode helps us prevent the use of a variable before the declaration.
- Both
let
andconst
does not support hoisting.
Thank you for reading. 🎉
Oldest comments (0)