Doubts about the following code

1

Hello reviewing the typescript documentation I found these code blocks and would like to know more in detail why these results occur, the first for print only 10 and the second prints the sequence ?????

for (var i = 0; i < 10; i++) {
    setTimeout(function() { console.log(i); }, 100 * i);
}

for (let i = 0; i < 10 ; i++) {
    setTimeout(function() { console.log(i); }, 100 * i);
}
    
asked by Ronny Medina 07.01.2018 в 05:24
source

2 answers

0

Basically it's the different scope of var with respect to let , here You can find documentation of it in Spanish.

Now, here is the explanation, as mentioned in the documentation, the scope of var is greater than let , so for example in the code when you declare in the% var i = 0 the reach is global , the variable is "raised" to the window object in the case of the browser. This behavior does not occur with let , since let i = 0 is not "raised", but belongs to the for, its scope is only inside the for.

for (var i_var = 0; i_var < 10; i_var++) {
    setTimeout(function() { console.log(i_var); }, 100 * i_var);
}
console.log("Valor de var: "+i_var);
for (let i_let = 0; i_let < 10 ; i_let++) {
    setTimeout(function() { console.log(i_let); }, 100 * i_let);
}
console.log("Valor de let: "+i_let);

When executing that code, the error comes out that i_let is not defined, because it was not raised to window, once this is clarified now the answer does come:

At the end of the first for is shown the value of i_var , that is 10 and each console.log() of setTimeout will refer to that value, because as you will have noticed, first print "Value of var: 10 ", then the error and then the others console.log() are executed.

And in the second for it is different, because if the for and the variable i_let no longer exists, what is happening? simply every console.log() of the second for is referring to a different variable, each iteration represents a different value.

Therefore, even though the console.log() is executed when the for and i_let finished, it no longer exists, you can print a value, this is the variable that was created in the cycle and its value corresponds to the number of iteration.

    
answered by 07.01.2018 / 06:19
source
1

The reserved word var , creates a variable which can be used by its own scope (reach) and functions INSIDE of its scope, instead the word let , it is limited only to its own scope.

Example of var :

(function() {
var f = "Hola";
(function(){
console.log(f); // Muestra correctamente
})(); 
})();

Example of let :

(function() {
    let f = "Hola";
    (function(){
    console.log(f); // NO muestra correctamente
    })(); 
    })();
    
answered by 07.01.2018 в 15:25