I know that one of the ways to log 0 to 9 with this code:
EDIT: Source
for(var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}), 10)
}
is to make setTimeout
self invoking and pass i
as a parameter, like so:
for(var i = 0; i < 10; i++) {
setTimeout((function(i) {
console.log(i);
})(i), 10)
}
but I've tested making setTImeout
self invoking without passing i
, and it still works:
for(var i = 0; i < 10; i++) {
setTimeout((function() {
console.log(i);
})(), 10)
}
My questions:
- Why does it work even without passing
i
as a parameter? - Is it necessary to pass
i
?