JavaScript moves declarations to the top of their scope. This means that variables and functions in JavaScript can be used before they are declared.
The key things to know about hoisting are:
Only declarations are hoisted, not initializations. This means variable names are hoisted, but their assigned values are not.
Function declarations are fully hoisted and can be used before they are declared.
var
variables are hoisted and initialized with the valueundefined
.let
andconst
variables are hoisted but not initialized. They enter a "temporal dead zone" from the start of their scope until they are declared.
Here is an example of hoisting with var
:
console.log(x);
var x = 2;
// Prints undefined
Here, the var x
declaration is hoisted to the top of its scope, but the initialization = 2
is not hoisted. So x
is undefined
when it is logged.
With let
and const
, hoisting works differently:
console.log(y);
let y = 2;
// ReferenceError: y is not defined
Here, a ReferenceError
is thrown because let
and const
variables enter a temporal dead zone until they are declared.
Function declarations are fully hoisted, meaning they can be used before they are declared:
sayHi();
function sayHi(){
console.log('Hi!');
}
// Prints Hi!