Md Nahidul I.’s Post

Simple JavaScript challenge 🧑💻 What will be the output of this code? for ( var i = 0; i < 3; i++ ) {   setTimeout( () => {     console.log( i );   }, 0 ); } What's your answer? And why? #JavaScript #WebDevelopment #Frontend

  • No alternative text description for this image

Nice and simple but tricky challenge My answer is: 3 3 3 This happens because var has function scope, not block scope. The loop runs completely first and the value of i becomes 3. The setTimeout callbacks run later, and they all use the same final value of i, which is 3. If we use let instead of var, then it would print 0, 1, 2 because let creates a new value of i for each loop. If you have any other easy explanation, please share. I would love to learn more. Thanks for sharing this interesting question.

To view or add a comment, sign in

Explore content categories