Thursday, February 28, 2019

function - How am getting this output ? Javascript ES6





Please find my snippet here,



for (var i=0;i<11;i++) {
setTimeout( () => console.log(i), 10);
}






How it print 11 for 11 times? since i was set < 11?



if i console it without function it print 1-10 .



for (var i=0;i<11;i++) {
setTimeout( console.log(i), 10);
}


this gives me 1-10. i am wonder how its getting changed if i include function without condition?



Answer



Root case for:



for (var i=0;i<11;i++) {
setTimeout( console.log(i), 10);
}


that console.log will be triggered directly (without any delay), so it should be:




for (var i=0;i<11;i++) {
setTimeout(function () { console.log(i); }, 10);
}


that will give directly the same result as for ES6



Right way will be by using closures:






for (var i=0;i<11;i++) {
((i) => {
setTimeout(() => console.log(i), 10);
})(i);
}






The reason for that that we have a single-threaded model in JavaScript. So, all setTimeout will be executed after for-cycle.



In addition it can be used let:



for (let i=1; i<=11; i++) {
setTimeout(() => console.log(i), 10);
}

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...