DEV Community

Discussion on: What’s your favorite JS interview question?

Collapse
 
fervero profile image
Maciej Bójko • Edited

Fun trivia: setTimeout can have more than two arguments. After the callback function, and the duration, you can pass args for the callback, as well. Instead of working around setTimeout, use setTimeout.

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

(Although I don't even write the for loop, like, ever. It's all map, filter, reduce etc. So I'd rewrite it into something like this:

new Array(10)
   .fill(0)
   .map((x, i) => i)
   .forEach(x => setTimeout(console.log, 100*x, x))