Closures: var vs let
Link: https://www.youtube.com/watch?v=vKJpN5FAeF4&t=19s
I do understand that during 100 milliseconds timeout, it evaluates the value of i by running complete for loop. But, I am confused if the closure variable is in heap, why is it unaffected?
3 Replies
Is it because during every for loop its value resets?
And when we hit 100 seconds timeout, we start again from 0?
unlike global var
Lets say we have a timeout of 50 minutes, now at the 50th minute a new for loop starts but since its blocked scoped, its previous values wont be stored anywhere so we will get 0, 1, 2
wait a minu- with that logic, why we need heap in the first place, just put it in stack, we dont need to track it right? ðŸ˜
Short answer
You're using
var, don't. It doesn't work the way you think it does
Longer Answer
var is either global scoped or function scoped. Since for loops are not functions your var i = 0 is in the global scope so by the time your log runs i is no longer what it was when you started. So it logs the current value of i.
let, on the other hand, can be global, function, or block scoped. And that last one is important! Any time you see { } that's a block. So your for loop instantiates a new i variable in the for block, so when the timeout is run i is what you expect it to be. Mostly.
Since you're using timeouts things can be a bit wonky, still.But, I am confused if the closure variable is in heap, why is it unaffected?The closure variable isn't in the heap, though, it's on the stack. Variables used in a function are always on the stack. Though non-primitives are stored on the stack as pointers to the values in the heap. But that's some lower-level stuff you really don't need to worry about just yet. It goes back the the "pass by reference/value" issue we discussed yesterday. As to how it's on the stack after it's been popped off…that's due to the JS event loop. The
setTimeout is put in the event queue with its closure "stack" all wrapped up in a nice box with a yellow bow. Once the callback time expires the function (along with a snapshot of the closure environment at the time it was set to timeout) is pushed onto the stack and run.