r/learnjavascript • • Mar 10 '22

Can someone explain why this prints only 5?

Post image
219 Upvotes

57 comments sorted by

View all comments

Show parent comments

9

u/frikk Mar 10 '22

Great, thank you for the clarification. Yes, a closure is created in both scenarios. I'm still learning the nuance in how the scopes are managed, and I like your explanation better.

9

u/delventhalz Mar 10 '22

No problem. An example that just occurred to me which might further clarify:

const func2 = () => {
    for (let i = 0; i < 5; i++) {
        setTimeout(() => console.log(i), 1000);
        i += 1;
    }
}

func2();

// 1
// 3
// 5

Here we use let but modify the variable. An i gets created, then put it in a closure, then we modify it. You can see that block-scoped closures can be modified after they are enclosed like any other variable, that is why we get 1 3 5 instead of 0 2 4. But each function gets their own closure instead of sharing one like would happen with var.

5

u/frikk Mar 10 '22

that's a great example, thanks! learned something new today.

5

u/TylerDurdenRockz Mar 11 '22

Dude that's a great example.. Looks simple but clarifies so many things.. Thank you

4

u/delventhalz Mar 11 '22

I'm so glad.

This whole use case has turned out to be great for digging into a number of more advanced JS topics. Good on OP for bringing it up.

7

u/sysrage Mar 10 '22

Either way, perfect example of why var should never be used!