Earlier, pre-ES6 era, only var keyword was introduced for declaration of variable.
With ES6, the let and const keyword introduced.
without keywords, It is same as var and not allowed in 'strict' mode.
// without keyword
name = 'Jack';
// using var
var price = 100;
// using let
let isPermanent = false;
// using const
const publication = 'Article';
console.log(name, price, isPermanent, publication); // Jack 100 false Article
We will discuss:
- Scope
- Reassigning new value
- When you access a variable before declaring it
The variable may exist in a block, inside function or outside function.
A block
is section of code inside { }
// It has Block Scope
{
let name = 'John Kabir';
}
A function is a bunch of code you want to place logically together.
It is declared using function keyword.
// It has Function Scope
function test() {
let name = 'Tahsan';
}
Everything declared outside of block and function is global Scope.
// It has Global Scope
const skyColor = 'blue';
{
console.log(skyColor); // blue
}
function printSkyColor() {
console.log(skyColor); // blue
}
printSkyColor();
So, there are three types of Scope:
- Block Scope
- Function Scope
- Global Scope
The three keyword var, let and const work around these scopes.
We can use var, let and const to declare global variable. But it is recommended not to do it. By doing this, variable are accessible everywhere.
So to restrict scope of variable using var, let and const keywords, here's order of accessibility in scope starting with lowest:
var
: The functional Scope levellet
: The Block Scope levelconst
: The Block Scope level
You can reassign var or let variables, but you can't reassign a new value to const variable.
(const = constant)
One Tricky part
When object is declared and assigned value with const, you can still change value of its properties.
But you can not reassign any object value to same variable.
With var in non-strict mode, the variable will have an undefined value.
This means variable declared but not assigned.
In strict mode, you will get ReferenceError that variable is not declared.
With let and const, you will always get ReferenceError.
Some Tips:
- Don't use var
- Use let or const
- Use const more often
- Use let, when you need to reassign