DEV Community

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

Collapse
 
sarathsnair profile image
Sarath S Nair • Edited
  • 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);
};

Collapse
 
kenbellows profile image
Ken Bellows

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)).