How does Hoisting work on ES6?

Asked

Viewed 459 times

4

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

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

funcao();

Will return undefined because of the Hoisting, that moves the variable foo to the top of the function without defined 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 these new ES6 specs also suffer Hoisting (let, const, class...). My question is what would be the difference between one thing and another, what kind of Hoisting (if one can say so) that the let suffers if it returns error, when in the case of var nay?

  • Possible duplicate of var, const or Let? Which to use?

  • @Marcelobatista What is the relationship of the question with Hoisting to be duplicated?

  • 1

    Maybe of that

  • As far as I know there is no such thing as let and const. This argument is indicated in documentation although it does refer to ES5 "... In Ecmascript 2015, Let bindings are not Subject to Variable Hoisting, which Means that Let declarations do not move to the top of the Current Execution contex..."

  • @Isac So it is... there are places and people who say yes... my question was to know the difference between Isting before ES6 and after. But they closed the question by relating to another that has nothing to do with the question.

  • It is interesting that although the documentation refers to what I said, that there is no let, there are posts on Soen saying precisely the opposite.

  • @dvd is a very interesting mechanism the Hoisting because thanks to it it is possible to use a variable or function before the declaration. You want to understand how this is done internally, it will be this?

  • @cat Before ES6 I know how it works. I still don’t understand how it works in ES6, with Let.

  • Yesterday I spent all morning researching this and I did not come to a clear conclusion. Then today I come here to try a help and close the question. You will understand.

  • Is your doubt even about Hoisting, or about function scope vs block scope?

  • @bfavaretto Dude, it’s really about Hoisting. About scope it’s already clear to me.

Show 6 more comments

2 answers

3


The Hoisting is a Javascript behavior of moving statements to the top of the scope, can be the global scope or a function.

In es6 there are these two key words let and const. Let’s see how the Hoisting affects these two new features.

Statement with Let

console.log(hoist);

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

Exit:

Referenceerror: Hoist is not defined

A reference error means that the variable was not for the computer’s memory and does not yet exist, it is different from what happens with the var who 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";

Exit:

Undefined

Therefore, in addition to terms that declare the variable before being used, we also have to initialize it.

Statement with const

console.log(hoist);

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

Exit:

Referenceerror: Hoist is not defined

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

We should also keep an eye out for a statement like this:

const hoist;

console.log(hoist);

hoist = "A variavel foi levada ao topo";

Exit:

Syntaxerror: Missing initializer in const declaration

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

Concluding

Javascript tops 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 the execution, although variables declared with var are initialized with the value undefined.

Sources:

Hosting
Understanding Hoisting in Javascript

1

To begin, it is worth mentioning some concepts:

The declaration of variables of the type var can be a big problem for the simple fact that it can be changed regardless of where it is, see in 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 would take their value wherever it was, this is the case of let. With the let, if we declare him inside a função, the same will be available only in it, without hosting occurrence out of it, example:

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 cannot be changed, example:

const a = 1;

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

In this example, in the output the error will be displayed "Assignment to constant variable" meaning that a value is being assigned to the type variable const, what is not possible.

CONCLUSION

Thanks to Hoisting, variables declared with the keyword var may be used even before your declaration.

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

In addition to variables declared with var we have the possibility to use constants through the keyword const or use block-scoped variables via lett .

I personally recommend that you always use const, because it leads to fewer mistakes. I still don’t 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 reallocation. Anywhere else, use const.

  • But the var if declared within a function, it will not be taken out either, it will be taken to the top of the function. In the case of the let This does not happen, but they claim that he also suffers Hoisting. This is what I did not understand right.

  • @dvd edited the conclusion, take a look.

  • @dvd the difference, is that the let is a variable with block scope, that is, can only be used inside the block, if you give a return variavelLet within the function, it returns the value as soon as the function is called, but if you give a console.log(variavelLet), will be displayed the error that the variable was not defined.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.