Declaring a variable in JS
Well, there is a thing that always confused me; which method should we use to declare a variable π΅?
Well, if you are like me, then get ready to dive deep!
var
var
was introduced in the earliest version of Javascript, and you will find it in legacy codebases (also in Stack Overflow answers π).
You might be thinking, "Then what is the problem with it?"
The first problem is re-declaration
In var
you can not only reassign the variable but also re-declare it.
Here's an example:
var time = "4pm";
time = "5pm"; // re-assignment
var time = "8pm"; // re-declaration
You may be thinking "Hey! What's the problem with that?" Let me tell you a straightforward answer :- Re-declaring does nothing but induces π. Creepy onesπ±.
The second problem is its Scope
var
has a global scope(except when it's in a function), which means it can be used anywhere in the code. See this code:
var day = "Wednesday";
if (40 > 3) {
var day = "Monday";
}
In this code, you will think that you made a new variable day, but didn't notice it was assigned before. This can cause many bugs so in ES6, let
and const
were introduced.
let
You can think of let
as the ES6 version of var
. You can do similar things, but it fixes the problems.
The first problem fixed is that you cannot re-declare a variable.
For a demo, see this:
let time = "4pm";
// re-assignment works
time = "5pm";
// re-declaration throws an error
let time = "8pm"; //does not work
The second problem fixed is that let
, when defined in a code block, has a scope of only that block.
const
const
should be your way of assigning variables all the time when you know the value should not change. It is similar to let
, but its value is constant.
Conclusion
Always use const
as default, and when you know the value would be changed in the future, use let
. Never use var
as it will induce bugs in your code.
A quick note
This is my first blog, so if it has any errors, please tell me π. THANKS FOR READING !!!