Hoisting In JavaScript

I faced a hard time understanding why I am getting "undefined" everywhere.

It was before I knew what is hoisting in JavaScript mean.

In JavaScript, a variable can be declared after it has been used.

In other words; a variable can be used before it has been declared.

No alt text provided for this image
No alt text provided for this image

Both of the above examples are lead to the same result "5".

To understand this, you have to understand the term "Hoisting".


Hoisting is moving all declarations to the top of the current scope (to the top of the current script or the current function).


Const & Let

ES6 came with the 2 keywords 'let' & 'const'.

Variable defined with those 2 keywords are hoisted to the top of the block but with no initial value.

You cannot use a variable before it has been declared.

No alt text provided for this image
No alt text provided for this image

Initialization & hoisting

Important Note: JavaScript only hoists declarations, not initializations.

No alt text provided for this image

y = "undefined", why ?

Because only the declaration (var y), not the initialization is hoisted to the top.

It is the same as writing:

No alt text provided for this image

Rule of thumb:

To avoid this kind of behavior that might lead to bugs in your code, always declare your variables at the beginning of every scope (script/function)

Iyadh Chaker

Phd Candidate in Quantum Computing | Software Engineer

4y

Hamdi Ben yaflah we were taught Hoisting in 3rd year 😂

Like
Reply

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics