Javascript var-let-const
Initially, the only keyword that was used to create variables was var, but later in 2015 after the release of ES6/ES(2015) let and const came into existence which solved some of the problems that developers used to face while developing an application. In this blog, I will be explaining all the 3 ways of declaring variables and majorly focusing on the difference between var and let.
Starting with const
As the name suggests the const keyword is used to create variables whose values will remain constant throughout the course of the program. Once the const variable is initialized its value cannot be changed.
Let's check out one example:
const constantVariable = "Hello World";
constantVariable = "Hello John" //error: Assignment to a constant variable
let and var Now let's talk about the "let" keyword. Most people know how to use the "let" keyword but upon asking them, what's the difference between var and let or what are the advantages of using let over var, they fail to answer and they start searching this on the internet.
Like any other programming language, if any variable is created using the let keyword, the scope of that variable is limited only to the block in which it's declared. But this is not the case with the var keyword. So, let us understand what is the problem with using the var keyword while declaring variables.
Let's check out one example:
function demo() {
for (var i = 0; i < 3; i++) {
console.log(i); //0, 1, 2 is logged in the console
}
console.log(i); // 3 is logged in the console
}
Here the variable i is created inside the for loop but the scope of variable i is not limited to the block of for, instead it's limited to the function block which means we can access it anywhere in the function demo.
This concludes that the variables created with the var keyword have a scope limited to the function in which the variable is declared and the inner block. This was the first reason why the let keyword was introduced.
Secondly while creating a global variable, if the var keyword is used then the variable gets attached to the window object of the browser. It's not a good practice to attach variables and functions to the window object. Let's suppose you are using any third-party library which contains the variables with the same name as the global variable, then it will end up overwriting the global variable. Therefore we should avoid adding stuff to the window object.

