A Tricky JavaScript Interview Question Asked by Google and Amazon
Daniel Borowski
11.4K44

There is always more than one way to code something.

const arr= [10,12,15,21];
function timed(i){
setTimeout(function(){
console.log(`Index: ${i} element: ${arr[i]}`)},3000)
}
/* one way, use a function */
for (var i=0; i <arr.length; ++i){
timed(i)
}
/* another way, you can pass a variable to setTimeout */
for (var i=0; i < arr.length; ++i){
setTimeout(function(i){
console.log(`Index: ${i} element: ${arr[i]}`)
},3000,i)
}

Personally I prefer using the function. It breaks things up a bit and makes it easier to read, at least to me. And there are various reasons to not create functions inside a loop.