Let, Var, Const in javascript
Modern javascript (ES6) introduces a new keyword for the declaration of variables let and const which is an addition to the var keyword in javascript. In this article, i will introduce you to the basic difference between the let, var, and const keywords.
Firstly all three different types of variable declaration differ in the scope of the variable.
var - The scope of the var keyword within a function. let's see this in code
function say(){ for(var i=0;i<5;i++){ console.log(i); } console.log(i); } say();
In the above code when we call say() function it will print 5. but we have declared var in for loop and we print the value of i outside the scope of i that is for loop. This is how var works.
Let - Now let's try the above code with the let keyword
function say(){ for(let i=0;i<5;i++){ console.log(i); } console.log(i); } say();
If we run the above code we will get some error (shown below) which means we are using i now out of scope. Hence we can say that when we have to preserve the scope of the variable up to a specific block we can use 'var'.
console.log(i); ^ ReferenceError: i is not defined
Const - As the name suggests this keyword is used to declare constant value. The scope of a constant variable is the same as let within the scope of block.
const a=1; //declaration
// a=3
We can't modify the const variable if we try to run the second line of the above code and modify the value of const we will get an error (shown below).
a=3;
^
TypeError: Assignment to constant variable.
We can this is the basic difference between this 3 keywords.