Variable- Formally known as binding as a name is bound to a value inside a scope.
Block Level Scoping- Variables that are inaccessible outside a given block scope. Also known as lexical scope. Created inside these following places:
- Inside a function
- Inside a block(
{}
)
Introducing let declarations- The syntax is same as the var
. let
declarations are not hoisted onto the top of enclosing block. It’s best to place them first in the block so they are accessible to the entire block.
Cannot Redeclare the variable like we do in var
|
|
const declaration - Variables declaring const
are considered constants meaning their values cannot be changed once set. const
is block level variable and it’s declarations is not hoisted as well.
|
|
The value a const
hold can be modified if it’s an Object. const
prevents modification of the variable not modification of the bound value.
|
|
Temporal dead zone(TDZ) - let
and const
bindings are not hoisted so they can’t accessible before their declaration. Any attempt to access the variable results in runtime error.
|
|
Block binding in loops- Only the loop will have access to the count variable and is meant to use only inside the loop.
|
|
const
behaves differently in loops. If we use const
in a for
loop it will throw an error after the first iteration but it can be used with for-in
loop(because the loop creates a new binding on each itertion ) and works the same way as let
.
Global block binding - When var
is used in the global scope it creates a new global variable which is a property on the global object(window in browser) that means we can accidentally overwrite an existing global using var.
|
|
if we use let
or const
instead in the global scope a new binding is created in the global scope but no property is added to the global object. This means we cannot overwrite a global variables. This makes let
and const
much safer to use in the global scope.
Best practice - use const
by default and only use let
when you know a variable value need to change. The rationale is the most variables should not change their value after initialization because unexpected value changes are a source of bugs.