Hi all, I just want to share something which is currently best practice in the industry and recommended by various online coding forums too.
We have been using var keyword in our javascript codes for defining variables that might be storing some database fields or some values which may or may not change in the defined function scope or are globally constant. From 2015, ES6 introduced two new variable declaration keywords namely ‘let’ and ‘const’.
var initialization
First thing first lets us talk about var. So var is a variable declaration keyword and is function scoped which means that its existence is only inside the function it was declared in or globally if defined so.
For example :
Function scope nature of variables defined with var
As you can see in the output below ‘b is not defined’ is due to the fact that the variable ‘b’ is scoped inside the function print() and is not accessible outside the scope of the function.
let initialization
When we declare a variable using ‘let’ keyword the particular variable unlike ‘var’ becomes block scoped meaing it will be accessible from any point inside the block.
For example :
In the example, we can see that there are two variables one which is firstName(globally declared) and the other is age(declared inside the block). When logged inside the block we get the desired result but when we try to log them outside age which has the scope of the block it was defined is undefined outside it.
const initialization
When it comes to initializing any variable whose value is supposed to be constant throughout the program then ‘const’ keywords are the best go-to keywords as it minimizes the risk of changing the value accidentally as it is immutable.
For example :
In this example, you see the value of pi is set with const keyword as constant and any attempt to change gives us a TpyeError because of the fact that const variable post declaration becomes immutable, thus meaning it can’t be reassigned to any other value as in the case of var or let.