Explain | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Explain

arr=[1,2,3,4,5]; for(var i=0; i<arr.length; i++){ setTimeout(function(){ console.log(`index:${i} value:${arr[i]}`); }, arr[i]); }; Can anyone please explain the output of this code?

28th Jul 2020, 12:47 AM
Samir Singh
Samir Singh - avatar
6 Answers
+ 5
Emanuel Maliaño this is a bit better as a brief explanation between let and var as many use var which should be let https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
28th Jul 2020, 1:26 AM
BroFar
BroFar - avatar
+ 3
maf I think you are answering a different question and dropped it here ? #scratching_my_head
28th Jul 2020, 2:39 AM
BroFar
BroFar - avatar
+ 2
Samir Singh instead of var change to let arr=[1,2,3,4,5]; for(let i=0; i<arr.length; i++){ setTimeout(function(){ console.log(`index:${i} value:${arr[i]}`); }, arr[i]); }; // Output index 0 value 1 index 1 value 2 index 2 value 3 index 3 value 4 index 4 value 5
28th Jul 2020, 1:13 AM
BroFar
BroFar - avatar
+ 1
Adding a little more to what BroFar said. String template ES6 https://developers.google.com/web/updates/2015/01/ES6-Template-Strings
28th Jul 2020, 1:18 AM
Emanuel Maliaño
Emanuel Maliaño - avatar
+ 1
Here is an array which has 5 elements [1,2,3,4,5] We are cycling through each of them using a for loop and logging them to the console. Index means at which position an element is, index always start with 0, the first element (1) has an index of 0, last element (5) has an index of 4. we can access them using this: arr[4] // 5 U can insert variables inside of strings without using this syntax: "My name is " + name + " and I am " + age + " years old." The better way is to use ` ` instead of " " coz with backticks ( ` ` ) u can insert variables inside. `my name is ${name} and my age is ${age}`
28th Jul 2020, 2:36 AM
maf
maf - avatar
+ 1
BroFar HAHAH nah man he asked us to explain this code.
28th Jul 2020, 2:41 AM
maf
maf - avatar