Variables in JavaScript are like containers that hold reusable data. These data containers need to be declared with some specific keywords in Javascript.
Right now there are 3 ways to declare a keyword in JavaScript:
- var (older way)
- let (introduced in ES6 ✨)
- const (introduced in ES6 ✨)
Before the standardization of ES6 (ES2015), everyone used to declare variables with the var
keyword. Now we have
let
and const
for every possible case.
Rules for using const and let
Follow these two rules to decide:
- Use
const
as a constant when you are sure that the variable will not be redeclared. - Use
let
for everything else.
Rules for naming variables
Variable names are case-sensitive, so name
and Name
both will be considered different variables.
Variable names cannot begin with a number but the numbers can be used in the middle and end of the variable name.
A variable declared with const
must be initialized.
Variables can start, end, or contain the following:
- Uppercase strings
- Lowercase strings
- Underscores
_
- Dollar sign
$
Variables cannot start, end, or contain symbols and special characters:
Multiple variables can be chained by comma, but it’s not considered good practice to do this.
Subsequent declaration of a variable is possible with var
but not with let
and const
.
Notice in the above last example that we are just modifying one of the keys in the object and not replacing the entire object, so it’s working perfectly fine.
Why should we prefer let and const over var
It is good practice to avoid using var
declaration in your code. let
was introduced to provide a
level of organization while managing the large data structures as it is safer knowing that your variable cannot
be reassigned anywhere in its scope.
Thanks for reading! 🎉