So letās cover a few basics.
the curly braces are being used to define a block. A segment of code that is a sub-section of the main execution space. All functions are blocks, etc.
In effect, inside of a block, javascript maintains a variable reference table specific to that block. Anything defined inside the block is local to that block, also called scoped to that block. let
, const
, var
define variables.
When resolving a variable reference, the code will first try to resolve the variable against the current blockās table; if it does not find a resolution, it will bubble up and check the parent scope (repeat as necessary until you come to the main scope; if it fails to resolve in the main scope, an error is thrown as the variable is undefined in any scope.)
So lets look at the example.
let b = 2;
{ b = 4; b; }
First line is pretty simple, it defines a variable. For sake of ease, I will assume this is in the main scope (but it could be any number of layers deep, the result holds true regardless of how many parents are above this scope!). So b
is defined in the main scope as a variable (ie: not a constant), with value 2
.
The second line is a bit jammed together. It may help if i spread it out a bit.
let b = 2;
{
b = 4;
b;
}
so;
{
opens a new block (scope).
b = 4
tries to set a value to the variable b
. Note that thereās no let
here, so weāre not defining a new variable, weāre trying to set a value of an existing one. So Javascript looks at the blockās variable table. Thereās nothing there, because the block hasnt defined any variables. So it goes to the parent. The parent has a variable called b
. So the code latches on to that reference, and assigns the value 4
to that variable.
b;
just outputs the current value of b
. Again, javascript will look locally, find nothing, and go to the parent.
}
closes the block; when the code gets here, javascript can dump anything in the variable reference table for the block; its no longer relevant.
But what if we DID define a new variable inside the block?
Letās change the example a little bit.
let b = 2;
{
let b = 4;
console.log(b);
}
b;
(Q: āWhy do you need console.log?ā A: Because I want to output multiple times, I cant rely on the inherent console return until the very end of the code.)
This time, I define b
inside the block. This puts it into the local scope for the block.
Give the code a try, but before you push enter, what do you think will happen? Why?