Let and Const
In javaSctipt earlier we were using var which is a functional or global scope. Now in Es6 We have new way to assign variable which are let and const which are block scop or local scope.
- Let Variable: Let is a block scope varibale whose value can be changed.
- Const Variable:Const is a block scoper variable whose value can not changed
What is function/global scope and block scope?
Function scope work on the entire code whereas block level code works inside only a perticular block in which the variable is written. Because of this the error will be less as we can use the same variable multiple times and assign new value without disturbing the earlier ones.
For Expample
in this function scope code we will see the how var works
var name = "shivam";
if(name.typeof= string){
var name = "Neha";
console.log("i am"+ name);
}
console.log("i am"+ name);
Output:
i amNeha
i amNeha
note: As we can see that we have change the assigned value inside the block but the output is same as it updated the local as well as globla scope at the same time.
In this example we will see how const and let works
let name = "shivam";
if(name.typeof= string){
let name = "Neha";
console.log("i am"+ name);
}
console.log("i am"+ name);
Output:
i amNeha
i amShivam
note: As we can see that we have change the assigned value inside the block but the output is different as the let in inside block did not updated the globla scope.
In this example we will see how const and let works
const name = "shivam";
if(name.typeof= string){
const name = "Neha";
console.log("i am"+ name);
}
console.log("i am"+ name);
Output:
i amNeha
i amShivam
note: As we can see that we have change the assigned value inside the block but the output is different as the const in inside block did not updated the globla scope.
Also in const we can not update the data for the same variable but here we have done that. As they both have different scope level in the code.

Comments
Post a Comment