var vs let vs const in JS !
August 14, 2020
Let us discuss the Usage
var and let are basically used for creating a variable (Whose value can change during runtime!)
const as the name suggests is short for constant variable (whose value is fixed and won’t change during runtime)
var is available to us from the inception of JS whereas, const and let are relatively new feature available to us from ES6(2015) onwards
If you all are familiar with other languages like (C, C++, Java) you might notice that while allocating space to the variable we don’t specify the Type of value which should be stored in that. This is Because JS is a weakly Typed Dynamic Language which simply means that the variables are not bounded towards a particular type/value (unless u declare it as const)
Difference Between Them
let and const for instance have all the properties same except from reassignability. Interesting Variations can be seen in case of let and var.
First Improvement in let over var was that the redeclaration of variable in the same scope was not allowed using the modern construct!
var - Global and Function Scope
let - Block Scope
Scope Basically signifies the access or availability of the variable within particular sections of the code
Global Scope refers to the Scope where all the top level code gets executed or registered in memory(in case of Async Events) when that file/module is mounted. The variables declared in this scope is globally accessible from anywhere in your code
Function Scope refers to the Area enclosed by the Function Body. The variables declared in this scope can only be accessible in this body as well as in its nested functions and scopes due to closure (Topic to be discussed in some other post!)
From ES6 onwards a new concept called block level scoping was introduced.
Block scope is comprised of any area that is enclosed between curly Braces {} This includes area within if, switch conditions or for and while loops!
This feat led to more specificity towards usage and declaration of variables and thus, overcome the problems that used to arise sometimes due to global scoping…
Also enables us towards implementing pure function which are less prone to bugs and easy to test!
Problem that used to arise with var
Hence I would like to conclude by encouraging you all to embrace this new construct let and const for declaring variables and write better JS code!