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.
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.
Initialization & hoisting
Important Note: JavaScript only hoists declarations, not initializations.
y = "undefined", why ?
Because only the declaration (var y), not the initialization is hoisted to the top.
It is the same as writing:
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)
Phd Candidate in Quantum Computing | Software Engineer
4yHamdi Ben yaflah we were taught Hoisting in 3rd year 😂