LinkedIn Interview Question

Analyze a horrible JavaScript function to determine the problems. Essentially a nasty for loop with a setTimeout inside that did a console.log of the loop iterator's value.

Interview Answers

Anonymous

Apr 22, 2015

Just add a Closure to it. for (var j=0; j< 10; j++) { (function(j) { return setTimeout[function() { console.log(j); }, 100) })(j); }

2

Anonymous

Jul 3, 2014

Trick question of course, the setTimeout makes it so that the iterator has gone to the full value of N by the time the setTimeout fires, so all statements print the same value. The fix? Use closures/self executing function to capture the value when the setTimeout is first set so that it maintains the correct corresponding value.

6