Let vs var in javascript

I understand that let has a scope block and var has a functional scope. But I do not understand in this case how using let will solve the problem.

const arr = [1,2,3,4];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
   console.log(arr[i]) 
}, 1000);
} // Prints undefined 5 times

const arr = [1,2,3,4];
for (let i = 0; i < arr.length; i++) {
setTimeout(function() {
   console.log(arr[i]) 
}, 1000);
} // Prints all the values correctly
+4
source share
3 answers

First of all, the output will be four times, not five times (as indicated in your comment). I pasted your code in Babel REPL, and this is what I got,

"use strict";

var arr = [1, 2, 3, 4];

var _loop = function _loop(i) {
setTimeout(function () {
   console.log(arr[i]);
}, 1000);
};

for (var i = 0; i < arr.length; i++) {
_loop(i);
}

Do you see how now you can work inside ?:-)

+1
source

All this is related to the scope of the variable. Try to wrap both parts in a function and watch the output:

function test() {
  // `i` will be declared here, making it a non-for-loop scoped variable
  const arr = [1, 2, 3, 4];
  for (var i = 0; i < arr.length; i++) {
    setTimeout(function() {
      console.log(arr[i])
    }, 1000);
  } // Prints undefined 5 times
}

test();
Run codeHide result

, i , - setTimeout, i 4, . arr[i] undefined .

i , i console.log. , :

function test() {
  const arr = [1, 2, 3, 4];
  for (let i = 0; i < arr.length; i++) {
    setTimeout(function() {
      console.log(arr[i])
    }, 1000);
  } // Prints all the values correctly

}

test();
Hide result
+3

var setTimeout. (IIFE) setTimeout, i setTimeout.

const arr = [1,2,3,4];
for (var i = 0; i < arr.length; i++) {
(function(i){
setTimeout(function() {
   console.log(arr[i]) 
}, 1000)})(i);
}
Hide result
0

Source: https://habr.com/ru/post/1691443/


All Articles