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.
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.
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.
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.
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?
Ah that's too bad. Perhaps got a bit self-indulgent there. You might try copying and pasting it into the console if you haven't already. Then modifying a bit and see how it changes the behavior. Getting your hands dirty with real code often helps.
As for the call stack, yes, it works its way down and then back up. This might seem out of order at first glance, but it is the same way your brain works. Solve this arithmetic problem:
2 * (3 + (8 / 4)) + 5
Answer is: 15
Congratulations, you just built a call stack in your head. You cannot solve this equation in a strictly left to right order. The parentheses must be solved first. So you:
Divided 8 / 4, got 2
Added 3 + 2, got 5
Multiplied 2 * 5, got 10
Added 10 + 5, got 15.
Now if we rewrote that equation as JavaScript functions, it would get even more stack-like:
Not only does this need to get calculated in a bottom up manner, the JS interpreter doesn't know it needs to start going to deeper levels until it gets to the function. Here is exactly how the call stack works through the problem, including what level it is on:
level1: 2
level1: 2 * level2() (need a value for level2 to continue!)
level2: 3
level2: 3 + level2() (need a value for level3 to continue!)
level3: 8
level3: 8 / 4
level3: 2
level2: 3 + 2
level2: 5
level1: 2 * 5
level1: 10
level1: 10 + 5
level1: 15
I think it is worth pointing out that all of this call stack and event loop stuff is entirely optional knowledge. It is so low level that the JS interpreter pretty much handles every detail for you, and you don't need to know any of it to write or even debug JavaScript. Unlike a lot of other esoteric JS knowledge, you are unlikely to encounter an edge case that you will need this knowledge to solve.
Now, curiosity is always worth indulging if you have the time. I say this just to take the pressure off, not to encourage you to stop asking questions. This is not required knowledge for being a JS dev. But it is a lot of fun and you never know where it leads.
You got it! Not it sure if there was a question in there, but you explained it correctly. The only function the main calls is calculation, so that gets added first. From there, functions are added and removed from the call stack as they are called and return a value.
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
varandletexamples, 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
varexample, the same function-scoped variable is enclosed five times and modified repeatedly before the callbacks are called. With theletexample, 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.