Hoisting¶
Hoisting consists in bringing up [scope] (scope_zakres_variety.md) declaration [variables] (variables.md). This mechanism is only for variables declared with the var
keyword and function declaration. This means that we can call a function or use such a variable before its declaration.
The following examples show this mechanism:
console.log(foo);
var foo = "Lorem ipsum";
In the example above, the console will display undefined
.
In turn, in the next example:
foo = 'hello'
console.log(foo);
var foo = 'Lorem ipsum';
console.log(foo)
hello
andLorem ipsum
. add = function(a, b) {
return a + b;
}
console.log(add(2, 3)); // on the console screen we will see 5, even though we declare the add variable in the next line of code
var add;
In turn trying to hoisting with a variable declared with let
:
console.log(foo);
let foo = "Lorem ipsum";
we will get the error: Uncaught ReferenceError: Cannot access 'foo' before initialization
.