Skip to content

Hoisting

Hoisting means to bring up scope declaration variables. This mechanism occurs only for variables declared using the keyword var and function declaration. This means that we can call a function or use such a variable even before its declaration.

The following examples show this mechanism:

console.log(foo);
var foo = "Lorem ipsum";

In the above example, the console will display undefined.

In the next example:

foo = 'hello'
console.log(foo);
var foo = 'Lorem ipsum';
console.log(foo)
in the console, we will see the lines displayed: hello and lorem ipsum.

add = function(a, b) {
  return a + b;
}
console.log(add(2, 3)); // in the console screen we will see 5, although the add variable is declared in the next line of code
var add;

In turn, trying to use hoisting with the variable declared with the let:

console.log(foo);
let foo = "Lorem ipsum";

We get an error: Uncaught ReferenceError: Cannot access 'foo' before initialization.