How does hoisting work on ES6?

5

For example, using var , when calling the function below this way:

function funcao(){
   console.log(foo);
   var foo = "mensagem";
}

funcao();

It will return undefined because of hoisting , which moves the variable foo to the top of the function with no set value.

And in the case of let , for example:

function funcao(){
   console.log(foo);
   let foo = "mensagem";
}

funcao();

Will return the error Uncaught ReferenceError: foo is not defined .

I know that these new ES6 specifications also suffer hoisting ( let , const , class ...). My question is what would be the difference between one thing and another, what kind of hoisting (if it can be said so) that let suffers if error returns, when in the case of var no?

    
asked by anonymous 27.02.2018 / 14:06

2 answers

2

Hoisting is a behavior of JavaScript to move declarations to the top of the scope, it can be the global or function scope.

There are no these two keywords let and const . Let's see how hoisting affects these two new features.

Declaration with let

console.log(hoist);

let hoist = "A variável foi levada ao topo";

Output:

  

ReferenceError: hoist is not defined

A reference error means that the variable was not in the memory of the computer and does not yet exist, is different from what happens with the var that would return undefined .

This ensures that we always have to declare our variables first.

However, an implementation like this results in undefined and we have to be more attentive:

let hoist;

console.log(hoist);

hoist = "A variavel foi levada ao topo";

Output:

  

undefined

So, in addition to having to declare the variable before it is used, we also have to initialize it.

Declaration with const

console.log(hoist);

const hoist = "A variavel foi levada ao topo";

Output:

  

ReferenceError: hoist is not defined

Just like let the interpreter says that the variable does not exist by casting a ReferenceError . The same will occur inside a function.

We should also be aware of a statement like this:

const hoist;

console.log(hoist);

hoist = "A variavel foi levada ao topo";

Output:

  

SyntaxError: Missing initializer in const declaration

This shows us that a constant must be declared and initialized before using.

Completing

JavaScript takes to the top the variables declared with let and const of es6, and the difference is how they are initialized.

Variables that are declared with let or const are not initialized at the start of execution, although variables declared with var are initialized with undefined value.

Sources:

Hosting
Understanding Hoisting in JavaScript

    
27.02.2018 / 17:04
1

To start, it's worth highlighting some concepts:

Declaring variables of type var can be a big problem simply because it can change regardless of where it is, see the example, I left some comments with explanations:

var a = 1; //aqui a variável é declarada e iniciada com o valor 1
console.log(a)

for(a; a<3; a++){ //aqui, é pego a mesma variável, e no loop, é somado o  valor 2, resultando em 3
  console.log(a)
}


function r () { 
  return   a+ 1; //aqui, a mesma variável, agora com o valor 3, irá ser somada com +1, resultando em 4 

}
console.log(r())

Having this problem of statements, the staff saw the need to create variables that assumed their value where it was, this is the case of let . With let , if we declare it within a função , it will only be available on it, without the hosting occurring outside of it, eg:

var r = 1;
function result () {
   let r = 1+1;
   return r;
}
console.log(r); //aqui irá exibir 1, pois estamos chamando a variável global

console.log(result()); //aqui é exibido o valor 2, pois foi chamado a função que contém a variável di tipo let

The variable const has the same behavior as let , what changes is that once declared, its value can not be changed, eg:

const a = 1;

 a = a+2;
console.log(a)

In this example, the output will show the error "Assignment to constant variable" which means that a value is being assigned to the variable of type const , which is not possible.

CONCLUSION

Thanks to hoisting, variables declared with the var keyword can be used even before their declaration.

On the other hand, variables created with let can only be used after their declaration because, although they are high, they are not initialized.

In addition to the variables declared with var we have the possibility to use constants by means of the keyword const or use variables with block scope through let t.

I personally recommend that you always use const , as this leads to fewer errors. I still do not see a situation where I need to use var .

As a general rule, use let only for loop counters or only if you really need reassignment. Elsewhere, use const .

    
27.02.2018 / 14:31