Differences between var, let and const
Variables declared using var
can be used within the whole function where they were initialized, but variables declared using let
and const
can only be inside the block where they were created.
The values of variables declared using var
and let
can be reassigned, but in the case of const
that's not possible.
Variables declared with var
can have the same name, but in the case of let
and const
it's not possible and you will get a Syntax Error. It's only possible to do it for the latter options if they are declared in a different scope.
Variables declared with var
and let
without an initial value will have undefined
assigned as default. In the case of const
it's not possible to declare a variable and not assign a value to it, JavaScript will return a Syntax Error.
Variables declared with var
are assigned as a property of the global object, unlike in the case of let
and const
.
Hoisting
Variables declared using var
are read by the JavaScript interpreter as if they were declared at the beginning of the function or scope. This means that the value of the variable can be referenced before it is declared in the code.
The same thing goes for let
and const
but in these cases they are declared without an initial value until they have an assigned value in the code. This time between the beginning of the scope and the assignment of a value to the variable is called Temporal Dead Zone. During this time a variable can't be referenced until a value is assigned to it.
This is possible because JavaScript saves in memory in the Lexical Environment the references to the declarations as undefined and then assign the value to it later when they are initialized in the code. This is only possible for the following cases:
- Class
- Function
- Const
- Let
- Var
Scope
This is an important concept because it manages the accessibility of variables in the code depending on how we handle their declaration. There are three type of scopes:
- Global
- Function & Local
- Block
Global Scope
This is the scope outside a function, all variables declared here can be used anywhere in the code.
Function & Local Scope
This is the scope inside a function, all variables declared here can only be used inside the scope of the function.
Block Scope
This is the scope inside a pair of curly braces since JavaScript ES6, all variables declared here, except for var
, can only be used inside this block.
Latest comments (0)