JavaScript – Hoisting

In JavaScript, you can use a variable even before declaring it. By default, JavaScript moves all the declarations to the top i.e., hoisting. The declarations are moved to the current scope’s top.

The var for variable declaration

With var, you can use a variable even before declaring it. Let us see an example. We have used the var keyword for variable declaration:

Output

The above works for the var, but won’t work for let and const keywords.

The let for variable declaration

Unlike var, you cannot use a let variable before declaring it. If you use it, a ReferenceError will be thrown. Let us see an example:

Output

ReferenceError can be seen:

let for variable declaration

The const for variable declaration

Unlike var, you cannot use a const variable before declaring it. If you use it, SyntaxError will be thrown. Let us see an example:

Output

SyntaxError can be seen:

const for variable declaration

JavaScript Date
JavaScript Strict Mode
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading