drawing


Goal


The goal of this tutorial is to know what is hoisting in JavaSript and how to avoid it


Syntax


First of all we need to know what hoisting is. Hoisting is the “ability” that JS has to move all the declarations at the top of the code.

Only declarations not inicializations.

Let’s see an example:

x = 5;

console.log(x);

var x;

The output is 5 But why?

5

Cause JS is moving the declaration of the var at the top of the code in an invisible way.

var x;

x = 5;

console.log(x)


And what about this?

var x;

console.log(x)

x = 5;

We can see this output:

undefined

The key here is that JS “moves” al the declarations to the top NOT the asignations.


Conclusion


You can use the strict mode to force JS to work in the “Fair Play” mode, without moving any var declaration without our permission.

"use strict"
var x;

x = 5;

console.log(x);