Hoisting
JavaScript only hoist declarations, not initializations.
That is, during compile time,
JavaScript only stores
function and variable declarations in the memory, not their assignments (value).
But why undefined?
When JavaScript engine finds a var variable declaration during the compile phase,
it will add that variable to the lexical environment and initialize it with undefined
and later during the execution when it reaches the line where the actual
assignment is done in the code, it will assign that value to the variable.
let and const variables not hoisted ?
All declarations (function, var, let, const and class) are hoisted in JavaScript, while the var
declarations are initialized with undefined, but let and const declarations remain uninitialized.
They will only get initialized when their lexical binding (assignment) is evaluated during
runtime by the JavaScript engine.
This means you can’t access the variable before the engine
evaluates its value at the place it was declared in the source code.
This is what we call
“Temporal Dead Zone”,
A time span between variable creation and its initialization where they can’t be accessed.
If the JavaScript engine still can’t find the value of let or const variables at the line where they were declared, it will assign them the value of
undefined or return an error (in case of const).