What is Hoisting?
Hoisting is JavaScript’s default behavior of moving declarations to the top.
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.
Conceptually, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of the code, but this is not in fact what happens. Instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where typed them in code.
One of the advantages of JavaScript putting function declarations into memory before it executes any code segment is that it allows to use a function before declaring it in code.
undefined vs ReferenceError
The global undefined property represents the primitive value undefined. It is one of JavaScript's primitive types.
The undefined property indicates that a variable has not been assigned a value, or not declared at all.
This JavaScript exception variable is not defined occurs if there is a non-existent variable that is referenced somewhere.
There is a non-existent variable that is referenced somewhere in the script. That variable has to be declared, or make sure the variable is available in the current script or scope.
JavaScript only hoists declarations, not initializations. If a variable is declared and initialized after using it, the value will be undefined.
For example,
console.log(myNum); // Returns undefined, as only declaration was hoisted, no initialization has happened at this stage
var myNum; // Declaration
myNum = 9; // Initialization
The example below only has initialization. No hoisting happens so trying to read the variable results in ReferenceError exception.
console.log(myNum); // Throws ReferenceError exception
myNum = 6; // Initialization
Declarations using let
and const
are also not hoisted.
// Example with let:
x = 1; // initialization.
let x; // Throws SyntaxError: Identifier 'a' has already been declared
// Example with const:
y = 1; // initialization.
const y; // Throws SyntaxError: Missing initializer in const declaration