When starting to learn JavaScript, one of the first things we learn is the how to declare variables. Choosing between var
, let
and const
can be the start of frustration when you are beginning to learn JavaScript for the first time.
The first thing you learn is that var
can be redeclare and undated and you will not get any errors.
var name = "Remy";
var name = "Danny";
Now the problem with using var
is after writing hundreds of lines of code, you reuse the same variable name you will not get an error but it will lead to bugs in your code.
This is where let
comes in it fixes the problems with using var
. Variables declared with let
can be updated just like var
but they can not be re-declared.
let name = "Remy";
let name = "Kathy"; // Identifier 'name' has already been declared
It is also good to remember that you can declare the same variable if they are in different scopes. This means you can re-declare the variable inside a function or anywhere that is surrounded by {}
.
The other option we have to declare variables is const
they maintain their constant value. const
unlike var
and let
can not be re-declared or updated with in its scope, and we are unable to have this problem.
const name = "Kathy";
const name = "Danny"; // Identifier 'name' has already been declared
In the small amount of time I have been writing and learning JavaScripts, this was one of the things I always had to keep in mind when declaring variables. Always keeping in mind which one will be the right one for the job.
Top comments (2)
Great explanation!
However, when it comes to const you should be aware that an object's properties can still be mutated.
Same for Arrays arrays elements can be mutated and even you can add or remove items.
Mdn link: Mdn on const in objects and arrays
Nice post.
The best explanation of variable declarations that I’ve read until now, clear and objective.