By: Pankaj Madaan, Founder ITCity Solution
History about variable declaration
What is Var ?
Variables declared using var keyword. This means If they are inside a function we only can access them inside the function scope only and If they are not they are part of the global scope which we can access anywhere. See example below:
In this, Mango is scoped to function scope and Apple belongs to the global scope right. If we try to access a global variable it is possible to do so. but if we try to access a function scoped variable it is not possible. Check this below example:
One of the issues with using the var keyword is they can be redeclared inside the same scope only. This will bring up some issues if we declare another variable using the same name inside the same scope level, the new variable will replace the old one.
And one more issue with var is these variables are not blocked level scoped which means if we have conditions in the statements those are not scoped to that statement but to the entire function or to the global scope level.
What is Let ?
This is the improved version of var declarations in ES6. Variables declaration using this way can eliminate all the issues that we discussed above. let creates variables that are block-level scope. Also, they can not be redeclared and can be updated. This example shows it is the best choice to use let than var.
Check out the below example to understand the behavior of let in the block scope.
What is Const ?
Const variables are cannot be updated or redeclared once we declared. This way is used to declare constants. Same as the let declarations const declarations are block-level scoped. Unlike var and let, If we are using const to declare a variable that needs to be initialized.
I personally prefer to use let and const over var and use const to declare constant variables and always use let to declare variables if it is not a constant.