re: What’s your favorite JS interview question? VIEW POST

TOP OF THREAD FULL DISCUSSION
re: What will output these example? Why? for (var i=0; i < 10; i++){ setTimeout(function(){ console.log(i); }, 1000); } How t...
 
  • Using let

for(let i=0; i<10; i++) {
setTimeout(()=>console.log(i),i*500);
};

  • Using bind

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

  • Or you can use IIFE

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

 

On the bind example, heads up that in some older browsers you need to pass console as the first argument to any console.<method>.bind(). Not that this is a particularly real-world thing to do, but it's bitten me a few times when trying to debug a promise chain in an older browser; I always love to do promise.then(console.log), but in old browsers this breaks until you do promise.then(console.log.bind(console)).

code of conduct - report abuse