- Hoisting is when during the compilation phase, JS moves the declaration to the top of the code. For example
// Code 1
a = 2;
var a;
console.log(a); // 2
// This will be processed as
var a; // declaration moved to top
a = 2;
console.log(a);
// Code 2
console.log(a);
var a = 2;
// This will be processed as
var a; // declaration moved to the top
console.log(a); // undefined
a = 2;
- In the second example above,
var a = 2
is first broken into var a
(the declaration) and a = 2
(assignment). The declaration part only moves to the top, not the assignment because of this tokenization during compilation.
- Hoisting happens per-scope.
- The functions are always hoisted first and then the variables.
foo(); // 1
var foo;
function foo() {
console.log(1);
}
foo = function() {
console.log(2);
};
// This will be interpreted as
function foo() {
console.log(1);
}
foo(); // 1
foo = function() {
console.log(2);
};
// Here var foo; was just a redundant line