Preface: I’m going to try and explain this in… i’m going to call it logical operation terms. Note that this may not be exactly what Javascript does “under the hood”, but the operations should be near enough identical that i’m okay with not being 100% accurate to the engine. None of you JS Engine nerds come at me
So the concept is that the block (the bit inside the {}'s) has its own variable reference table (I’ma shorthand this to VRT now, because typing its a pain).
let b = 2;
In the ‘global’ block, we defined a variable called b
. So it’s in the global block’s VRT.
{
Then we enter the block. That block creates a VRT as part of its startup procedure. That VRT is blank.
b = 4
We tell the block’s VRT that we want to change the value of b.
The block looks at its VRT. It has nothing there called b
. (or anything there at all, but thats moot)
It calls its parent (the global block, in this case), and asks it to resolve the reference to b
.
The global block looks at its VRT, sees an entry for b
, and changes its value to 4 by discarding the 2 and replacing it.
The global block then hands the value back to the code (in case we wanted to do something complex like defining a value and using it at the same time).
b;
Repeat the above lines, but at the end, instead of replacing the value, the global block just hands back the value that is currently stored at that memory address.
}
We leave the block. The block’s VRT goes away.