r/learnjavascript • u/directmailadvertise • Mar 10 '22
Can someone explain why this prints only 5?
75
u/delventhalz Mar 10 '22
Three concepts to understand here:
Variable scoping
Asynchronous code execution
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
1when we logged it, it was2when we expanded it, so2is 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: 3WTF. And if we collapse the last level again?
▾ {a: {…}} ▾ a: ▸ b: {c: 2}(╯°□°)╯︵ ┻━┻
The value is both
2and3at 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
0
Mar 10 '22
[deleted]
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: 55
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
letkeyword instead ofvar, it would behave more how you would expect it to0
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 -
setTimeoutcallbacks 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
ix 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
2
u/iiMoe Mar 10 '22
Why in the name of lord is there a setTimeOut() inside a for loop
0
1
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
1
1
0
u/isthisneeded29 Mar 10 '22
Better use if statement there.
If(i<=0) { setTimeout(()=>{your program}, 2000); i++; } else { break }
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.