+ 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?
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
+ 3
maf I think you are answering a different question and dropped it here ?
#scratching_my_head
+ 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
+ 1
Adding a little more to what BroFar said.
String template ES6
https://developers.google.com/web/updates/2015/01/ES6-Template-Strings
+ 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}`
+ 1
BroFar HAHAH nah man he asked us to explain this code.