The answer would be Option 2: 55555
because
var i
in the loop will be defined in outer scope which is equal to
var i;
for (i = 0; i < 5; i++) { ... }
- Loop will run from
0
to4
but will break wheni
will be5
. setTimeout
will schedule 5 callbacks which will run after at least 10 secs.- Since,
i
is defined in the outer scope, its value will be overwritten on each iteration and final value will be5
. - When callbacks are executed, they will get the final value of
i
i.e.5
.
To capture each value of i
in the respective callbacks, there are two popular solutions to the question.
- Changing
var
tolet
which we redeclarei
on every iteration.
for (let i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i);
}, 10);
}
- Returning an inner function and using closures.
for (var i = 0; i < 5; i++) {
setTimeout(function(i) {
return function() { console.log(i); }
}(i), 10);
}
For useful and amazing frontend and programming tutorials: https://bit.ly/devtools-yt
Recommended Resources
- Top JavaScript Array Interview Questions | Problem Solving | Array Polyfills
- Top JavaScript Multiple Choice Questions (MCQ) with Answers | Frontend Interview Questions | Beginner Friendly
- Build an Autocomplete using React.js | Type One | Frontend Coding Challenge | JavaScript Interview Question
- How to build a Password Strength Checker in React.js | Frontend Interview Question | JavaScript
- Implement Accordion Component in React.js | JavaScript Interview Question
- Build a custom timer hook in React.js?
- How would you implement createStore function from Redux?