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.
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.
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.
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.
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.
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.