Hoisting is the JavaScript interpreter’s action of moving all variable and function declarations to the top of the current scope. There are two types of hoisting:
- variable hoisting – rare
- function hoisting – more common
Wherever a var
(or function declaration) appears inside a scope, that declaration is taken to belong to the entire scope and accessible everywhere throughout.
var a = 2;
foo(); // works because `foo()`
// declaration is "hoisted"
function foo() {
a = 3;
console.log( a ); // 3
var a; // declaration is "hoisted"
// to the top of `foo()`
}
console.log( a ); // 2