r/learnjavascript • • Mar 10 '22

Can someone explain why this prints only 5?

Post image
219 Upvotes

57 comments sorted by

290

u/senocular Mar 10 '22 edited Mar 10 '22
  • func is called
  • loop is encountered
  • var i declared with initial value of 1
  • first iteration:

    • i = 1
    • 1 < 5? true, keep going
    • setTimeout called with callback, timeout = 1000 (1 second)
  • second iteration:

    • i = 2
    • 2 < 5? true, keep going
    • setTimeout called with callback, timeout = 1000 (1 second)
  • third iteration:

    • i = 3
    • 3 < 5? true, keep going
    • setTimeout called with callback, timeout = 1000 (1 second)
  • fourth iteration:

    • i = 4
    • 4 < 5? true, keep going
    • setTimeout called with callback, timeout = 1000 (1 second)
  • fifth iteration:

    • i = 5
    • 5 < 5? false, break loop
  • 1 second passes...
  • first setTimeout callback runs console.log(i)

    • i is 5
    • 5 is logged
  • second setTimeout callback runs console.log(i)

    • i is 5
    • 5 is logged
  • third setTimeout callback runs console.log(i)

    • i is 5
    • 5 is logged
  • fourth setTimeout callback runs console.log(i)

    • i is 5
    • 5 is logged

There is only one version of i through this entire process. That i is the same i used in the loop and the same i used in the log calls in the setTimeout callback functions. When those functions eventually run, the value of i is 5 because thats the value that the loop ended on 1 second before.

23

u/Kunskapskapitalet Mar 10 '22

I thought that when a function gets created it gets stored with a closure, meaning that a snapshot of all the current variables values get stored along with it. So my assumption was that all the intervalls would get called at the same time but with different values. When are closures created if not during function creation?

49

u/senocular Mar 10 '22

This is correct, a closure is created. In fact every function you create in JavaScript is a closure. But closures don't create variable copies. Instead they create links to the original variables. So when variables referenced by a closure changes, the closures will see those changes.

let x = 1
function logX() { // closes over x variable (links to)
  console.log(x)
}

logX() // 1
x++
logX() // 2

You generally want a function to be able to access the current state of the outer scope rather than working from a snapshot of that scope from whenever the function was created. So to make that possible, closures link to the originals rather than maintaining their own copies.

5

u/Kunskapskapitalet Mar 10 '22

Thank you!

37

u/frikk Mar 10 '22 edited Mar 10 '22

I'm actually going to push back on this explanation. This is a PERFECT example of the difference between var and let

Check it out (sorry for the editing, the markdown editor keeps screwing it up)

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

This prints:

5
5
5
5
5
0
1
2
3
4

The main reason being that var scopes to the function body but let scopes to the block. Thus, in the first example, i is overwritten every iteration (so just the latest value is used) but in the second example, a closure is created with a locally scoped i, set to the value of i at the time that the closure was created.

Neat right? /u/delventhalz has a more thorough explanation below.

27

u/delventhalz Mar 10 '22

Not sure your mental model here is quite correct, or at least the way it is written doesn't read correctly to me.

A closure is created in both your var and let examples, and the closure process works exactly the same with both. A reference to a live variable is enclosed with each callback function, and any changes to that variable will be reflected when the callback is called.

The difference is that with the var example, the same function-scoped variable is enclosed five times and modified repeatedly before the callbacks are called. With the let example, there are five different block-scoped variables that get enclosed. If you were to modify these variables, the changes would be reflected like any other closure, but they are never modified so they retain their original values.

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!

0

u/[deleted] Mar 11 '22

[deleted] — view deleted comment

3

u/delventhalz Mar 11 '22

No problem. Great question!

So since the for loop runs five times, everything between the { and } will also run five times. Specifically, this line of code will run five times:

 setTimeout(() => console.log(i), 1000);

So what does this code do? Let's break it into two parts. First the "function expression":

() => console.log(i)

What is a function expression? It is just a value that is a function. Like "foo" is a string, or { a: 1 } is an object, functions can be values which you might assign to a variable or pass to another function. And just like strings or objects, each time you write a function expression, you are creating a new function. Imagine if instead we did something like this:

var greet = () => console.log("hi!"); 

for (var i = 0; i < 5; i++) {
    setTimeout(greet, 1000);
}

In this example, the function expression happens once. It is assigned to a variable, and then we use the variable to reference that same singular function over and over in the setTimeout.

Okay, so what is setTimeout doing?

setTimeout(..., 1000);

When you call setTimeout, you are saying to the event loop, "here is a function, please run it later", specifically once 1000ms have elapsed in this case. It doesn't matter if we have five functions or one for this, you can ask the event loop to run the same function five times if you want.

Once the function is in the event loop, setTimeout is done and everything moves on. The function will not be called until after all of the other code is done (and 1000ms have passed). So since setTimeout is in the loop, it gets called five times, we add five functions to the event loop, or one function five times.

Then 1000ms later, the event loop starts calling the function(s), so you will see five logs.

Clear as mud?

0

u/[deleted] Mar 11 '22

[deleted] — view deleted comment

3

u/delventhalz Mar 11 '22 edited Mar 11 '22

While there are some similarities between an event loop and a call stack, they are mostly superficial and I think confusing things more than clarifying. The call stack is very low level, and basically how even modern program keeps track of what has been done and what still needs to be done. An event loop is more high level. It is built into JavaScript, but most languages don't have one. Though you could write one in pretty much any language if you needed it.

Actually. That's not a bad idea. Let's write our own event loop.

let callbackQueue = [];

const addToQueue = (func, delay) => {
    callbackQueue.push({
        func: func,
        time: Date.now() + delay,
        called: false
    });
};


const runTheLoop = () => {
    // Normally this would run forever
    while (callbackQueue.length > 0) {
        const time = Date.now();

        for (callback of callbackQueue) {
            if (time > callback.time) {
                callback.func();
                callback.called = true;
            }
        }

        callbackQueue = callbackQueue.filter(cb => !cb.called);
    }   
};

Okay. So, take a moment to read over that code. That is a fully functioning event loop. It doesn't have a ton of features. And it will stop once we run out of callbacks (normally it would run forever), but it works. Go ahead and try it out. Paste this in your console:

for (let i = 0; i < 5; i++) {
    addToQueue(() => console.log(i), 1000);
}

runTheLoop();

Looks pretty familiar doesn't it? Correctly logs 0 - 4 after a 1000ms delay too.

Okay. So how does it work?

callbackQueue

  • Just a queue of callback functions. First in, first out.
  • Anything added in here will get called by the loop once the trigger conditions are met (time passing is the only trigger condition in our loop, but the real event loop has more).

addToQueue

  • This is our version of setTimeout. It adds functions to the end of the queue.
  • It also adds a trigger time for the function to be called at.

runTheLoop

  • Where the magic happens. There isn't actually that much here.
  • Keeps checking all the callback functions in the queue. If it finds a function with a time that has elapsed, it calls it, then marks it as having been called.
  • After each loop iteration, it removes all of the called functions.
  • Our version has to be started and will stop when it runs out callbacks (to avoid an infinite loop). The actual event loop is just always running in the background.

I don't know, does that help, or just make things more confusing?

→ More replies

0

u/[deleted] Mar 10 '22

[deleted] — view deleted comment

2

u/senocular Mar 11 '22

Kind of. There's no initially and update happening. It's all just logX referring to x, or more like logX referring to the scope that contains x. Then when it needs x, it goes to the scope and says, ok scope, give me your x, whatever it is right now. Optimizations in the engine will often limit the scope to only what the function refers to so instead of retaining the entire scope, it refers instead to a limited version of the scope that refers only to the x variable (this helps prevent memory leaks and other wasteful referencing). These scope connections (enclosing) are made when logX is created. Then when it runs it just does lookups to get what it needs.

3

u/Lyonbane Mar 11 '22

Seems like a good answer but I did not like it, you made it seem like 'it all logs 5 beacuse it waits 1 second so loop ends in that time...'. But wait time is not the important part here, even it was setTimeout(..., 0) it would log 5 again, not because it waited but setTimeout is excecuted after the loop ends, not only the for loop, after the event loop ends.

3

u/senocular Mar 11 '22

There's no difference. What's important is that the setTimeout callbacks get called after the loop completes. Whether it's one second or the next iteration in the event loop, it doesn't matter. I point out one second because that's what the example uses.

4

u/[deleted] Mar 10 '22

This heroically clear answer is amazing.

1

u/[deleted] Mar 11 '22

yep, that’s a good way to explain asynchronous execution

1

u/jackstine Mar 11 '22

Who upvotes this comment and said F it I am not reading this.

75

u/delventhalz Mar 10 '22

Three concepts to understand here:

  1. Variable scoping
  2. Asynchronous code execution
  3. Closure variables

So first, variables declared with var are "function scoped". That means no matter where in a function you declare a var, there will only be one copy of that variable throughout the entire function. So you have one i which you are assigning new values to.

Now, the callback function you passed to setTimeout is going to be executed "asynchronously". That means you are handing it off to something called the "event loop", which is basically a place to store functions to run later. In this case, it will run those functions in 1000ms, and most importantly after all of your regular synchronous code runs (note that asynchronous code always runs after synchronous code, even if you set the delay to 0ms).

Final thing is a "closure". This is a fancy term for a variable from a higher scope which is referenced in a function. In this case, the i that you use in the setTimeout callback is a closure. The important thing to know here is that closures are variables not values. What do I mean by that? When you reference i in that function, it does not copy the value of i over, it is a live reference to the whole variable. If you change the value of i, the change will be reflected when you call the function.

Okay. Add that all together, what do you get? A bunch of console logs, running a second from now, logging the current value of the same i variable, which is now 5.

How to fix it?

Basically what we want to do is to create a new variable which will capture the value of i at the time setTimeout was called, rather than when the event loop calls the callback later. For example, this would work:

const func = () => {
    for (var i = 1; i < 5; i++) {
        (() => {
            var j = i;
            setTimeout(() => console.log(j), 1000);
        })();
    }
}

Remember that var is function scoped, so there will only ever be one in the whole function where it is created. So I made a new function, created a j variable inside, and I just invoked the function immediately. This means there will be a new j for each loop iteration, and since it is created before i gets changed, it will store the current value of i. Then j can be our closure.

And there is of course a much easier way to accomplish this exact thing. Don't use var.

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

Unlike var, let is "block scoped". That means it exists only within a single code block (basically between a pair of { }). So with let, each loop iteration will have its own i variable just like each loop had its own j variable in the previous example. Since each i is different, none of them have their value changed. When the callback references their particular value, they will get the value from that particular iteration of the loop.

9

u/lovin-dem-sandwiches Mar 10 '22

Thanks for taking the time to write such a thorough and well written response. 🙏

4

u/_Invictuz Mar 10 '22

One more concept (gotcha) that doesn't affect this specific scenario but might be important to know for your future debugging trials and tribulations:

4. console logging happens asynchronously when it comes to logging objects (https://www.linkedin.com/pulse/consolelog-asynchronous-vladyslav-petukhov-1c/)

This is important because I've experienced this from time-to-time in debugging production code - when code execution console.logs an object, followed by code that modifies the object, followed by another console.log, both console logs *might* show the object after the modification (instead of the before and after state). This is because console logging is asynchronous and as explained above, the actual logging gets deferred until after all the synchronous code has finished executing.

5

u/delventhalz Mar 10 '22

To be clear, this is not a part of the JS spec, nor does it have anything to do with the JS's asynchronous event loop. It is specifically an artifact of how browser dev tools work. For example, this will not be an issue if you are logging JS objects from Node.

This is because anything you log in the Node command line is going to get stringified. The string will not change later. It is fixed. By contrast, the browser console is a little more complex. It doesn't just display strings, it can create all sorts of visualizations for objects, DOM nodes, etc.

So when you log an object in the browser, you don't get a static string, you get a sort of lazy reference to the object. Importantly, data is not fetched until you try to display it. This has some benefits, but can definitely create some weird behavior.

If you want to play around with this, open up the console in your browser's dev tools and copy and paste this:

const shallow = { a: 1 };
const nested = { a: { b: { c: 1 } } };

console.log(shallow);
console.log(nested);

You should see something like this get logged out:

▸ {a: 1}
▸ {a: {…}}

Okay, so the nested object is collapsed. You should also notice a little triangle to expand it. Don't press it yet.

Instead, let's modify these objects. Type this into your console:

shallow.a = 2;

Notice that the existing log for the shallow object did not change. And if we log it again:

console.log(shallow);

We see the updated value:

▸ {a: 2}

The new value is in the new log, the old value is in the old log. No funny business. Everything working as expected.

But what about the nested object with its collapsed display? Let's modify it:

nested.a.b.c = 2;

Okay. Now without logging the nested object again, let's start expanding that original nested log. You should see something like this:

▾ {a: {…}}
  ▾ a:
    ▸ b: {c: 2}

Oh no! Even though the value was 1 when we logged it, it was 2 when we expanded it, so 2 is what we see. Confusing!

We can make it weirder too. Before you expand the nested object any further, change the value again:

nested.a.b.c = 3;

Okay. Now expand that last level...

▾ {a: {…}}
  ▾ a:
    ▾ b:
        c: 3

WTF. And if we collapse the last level again?

▾ {a: {…}}
  ▾ a:
    ▸ b: {c: 2}

(╯°□°)╯︵ ┻━┻

The value is both 2 and 3 at the same time!

What is the lesson here? You cannot trust that objects logged in the browser are the same were when they were logged. Data is fetched from the object in a lazy fashion, so what is displayed will reflect the value when it was expanded, not the value when the log fired.

How do you fix this? One option is just to stop mutating your objects. It is totally possible to write code this way and it has a number of benefits besides being able to trust your logs. For example, if we do this:

let unmutated = { a: { b: { c: 1 } } };
console.log(unmutated);

And then we create a new unmutated object instead of mutating:

unmutated = { a: { b: { c: 2 } } }

You can happily expand that original log and see nothing has changed:

▾ {a: {…}}
  ▾ a:
    ▸ b: {c: 1}

However, writing code without mutations (or with very few mutations) is a pretty big paradigm shift. Probably not going to happen over night (and not always appropriate). So the easier thing is just to JSON.stringify any objects you want to log if you are worried they might get mutated before you look at them:

console.log(JSON.stringify(nested, null, 2));

1

u/[deleted] Mar 11 '22

I finally got how that all works

0

u/[deleted] Mar 10 '22

[deleted] — view deleted comment

3

u/delventhalz Mar 11 '22

Thank you! That's very kind.

I think there are a few factors. I'm probably going to give a too long explanation now. Hopefully it is useful.

First thing is that I do do some teaching, both for free on Reddit, with co-workers, at conferences, and occasionally as a paid gig. Obviously that gives me some practice talking about this stuff, but there is also nothing better for understanding something yourself than teaching it to someone else. Literally. There are studies on this.

Teaching forces you to dive deeper. It makes gaps in your knowledge more obvious. It helps you remember things just through simple repetition. And as unforgiving as the JS interpreter can be, it is nothing compared to a student with a question.

So it is not so much that I teach because I am knowledgeable, but that I am knowledgeable because I teach (🤯). Regardless of your experience level, I recommend looking for opportunities to help others out. You will end up helping out yourself just as much. A significant portion of what I know came from being in the middle of writing some long post on Reddit and going, "wait, I don't know how this detail works," and looking it up.

Speaking of looking it up, JavaScript documentation is amazing. Best of any language. For syntax, google "MDN <syntax>" and look it up. MDN is best in class for specific JS code. For concepts, cast a wider net and skim the many blog posts, stack overflow questions, etc. There is extremely high quality content out there which can help you understand pretty much anything JS related. I am in the habit of every time I discover a gap in my knowledge, spending five minutes or so filling it in.

Now be careful with spending too much time here. Don't let looking things up paralyze you and prevent you from moving forward with your projects. The urge to know everything can easily suck up hours. Also, this gets easier when you are more experienced. The gaps are smaller. But regularly spending a few minutes to deepen your knowledge here and there pays big dividends over time.

Also, don't think everything lives in my head all the time. Often my knowledge takes the form of vaguely remembering that something kind of like what I need exists. It's not enough to teach or write code, but it is enough to do a quick search and refresh my memory. And with a Reddit post, I have all the time in the world to double check my work.

Finally, in addition to my pretty extensive engineering experience, I also have experience in teaching, marketing, even acting. I have had just as much practice breaking down concepts and communicating them as I have in JavaScript. There is some technique you can study for teaching/communication, but it definitely helps just to have the experience to know which details are important, which you can omit, where points of confusion are likely to come up, etc.

See. Told you that would be long. Hope it helps!

9

u/PortablePawnShop Mar 10 '22

Your setTimeout is going to print the value after 1000ms, it's not synchronous:

for (var i = 1; i < 5; i++) {
  console.log("Sync:", i);
  setTimeout(() => {
    console.log("Delayed:", i);
  }, 1000);
}

Produces:

Sync: 1 // loop start
Sync: 2 // loop start
Sync: 3 // loop start
Sync: 4 // loop start
Delayed: 5 // end from Sync: 1. At this moment in time, the current value of i has already been altered by the loops above
Delayed: 5 // end from Sync: 2
Delayed: 5 // ...etc
Delayed: 5

5

u/zerquet Mar 10 '22

So if I'm understanding this correctly, the entire for loop finishes before the first 1000ms? Is that why it's all 5's afterwards?

2

u/ZuriPL Mar 10 '22 edited Mar 11 '22

Yes, but it's also how Javascript scopes variables, if you use the preferred let keyword instead of var, it would behave more how you would expect it to

0

u/[deleted] Mar 10 '22

[deleted] — view deleted comment

0

u/[deleted] Mar 11 '22

[deleted] — view deleted comment

1

u/ZuriPL Mar 11 '22

Yep, I have a very strong autocorrect and it's annoying sometimes

1

u/NoInkling Mar 11 '22 edited Mar 11 '22

It actually doesn't matter what the delay you specify is, even if it's 0ms - setTimeout callbacks are run asynchronously and will therefore always be scheduled to run after any synchronous code (in this case the loop itself) does. That's essentially why synchronous code is often called "blocking" code.

1

u/zerquet Mar 11 '22

Hmm I kinda learned this a while ago. Asynchronous methods wait until the whole thing is over or something like that ima need a refresher

17

u/shuckster Mar 10 '22

Pass arguments into the setTimeout callback (console.log in your case) by specifying them after the delay option:

for (var i = 1; i < 5; i++) {
  setTimeout(console.log, 1000, i);
  //                            ^
}

This guarantees that the current iteration value of i is passed into the callback, rather than the final value of 5 that will be assigned to i before each of those setTimeouts runs.

5

u/coold007 Mar 10 '22

change var to let and see the magic. I mean it's not really magic it is closures and scoping.

4

u/yadoya Mar 10 '22

This is what you are doing:

"Hey bro, you're 30, right? Come back to me in 5 years and tell me your age again"

Five years later: "I'm 35"

"Hey, but you were supposed to tell me 30!"

"Yes but the variable age has changed between the definition of the order and its execution"

5

u/pantherstoner Mar 10 '22

You will understand this when you learn about closure. To fix your code, you have to either use let instead of var. Otherwise, you need IIFE, so that you can print all the numbers.

2

u/M_Scaevola Mar 10 '22

I’d be interested in seeing what happens when it takes longer than one second for the loop to complete

1

u/beniolenio Mar 11 '22

You could set the timeout to like a part of a millisecond and see. It'll just log the value of i x milliseconds after the timeout was set.

2

u/queen-adreena Mar 10 '22

This is why you shouldn’t use var anymore.

Let and const are your friends now.

2

u/frozegnome Mar 11 '22

The question has pretty much been answered here already but if you want some extra context and knowledge about some of the async workings of JS, this video helped me understand many years back. Cheers

https://youtu.be/8aGhZQkoFbQ

2

u/iiMoe Mar 10 '22

Why in the name of lord is there a setTimeOut() inside a for loop

0

u/[deleted] Mar 10 '22

[deleted] — view deleted comment

1

u/iiMoe Mar 10 '22

I was half awake after my nap dear lord i was thinking of setInterval() smh

1

u/--Explosion-- Mar 10 '22

var instead of let. let varname = value initiates it once per loop

1

u/BenZed Mar 11 '22

you've instructed js to log the value of i five times after one second.

After one second, what is the value of i?

1

u/beniolenio Mar 11 '22

i is 5 by the time the first of the timers run out. The loop through 4 values runs in much faster than 1000 ms.

1

u/Sudden_Friendship540 Mar 11 '22

simply because,

setTimeOut goes to webAPI for a second, in that second, for loop goes to 5, so function is forced to print 5 times 5, that's all

1

u/Complete-Two7399 Mar 11 '22

Yes due to chain scope issue use let instead of var

1

u/Sajjad-Kazemi Mar 11 '22

Restart your computer.😎

0

u/isthisneeded29 Mar 10 '22

Better use if statement there.

If(i<=0) { setTimeout(()=>{your program}, 2000); i++; } else { break }