Skip to main content

Command Palette

Search for a command to run...

Hoisting in Javascript

Updated
•2 min read•View as Markdown
Hoisting in Javascript

In JavaScript, variable can be declared after it has been used, so this means that a variable can be used before it has been even declared. As shown in the code below, the number of students can be printed onto console before it has been declared as the output appears to be 20.

students = 20;
console.log(students);
var students;

// Console
// 20

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. Inevitably, this means that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local. Of note however, is the fact that the hoisting mechanism only moves the declaration. The assignments are left in place.

Hoisting with let and const does not work the same way as var, we have to declare our variable before actually initializing it as shown in the image below:

let hoisting.png

In the image below, it prints the output as 20 because the variable is declared before it is being used in the function displayNoOfStudents() i.e where the number of students has been initialized.

let hoisting.png

Be on safe guard

In JavaScript, the use strict directive can be used to execute the codes in strict mode. With strict mode, undeclared variables cannot be used, like in the image below which results in an error.

The following error will be displayed if strict mode is activated:

let hoisting.png

More from this blog

I

Is A Web Learning

54 posts