What is the difference between let, var and const in javascript
I'm a beginner in javascript and when i go through the existing code, someplaces i'm seeing var and some places it's let or const. What is the difference between them?
1 Answer
6 years ago by Anusha
Var is the old way of declaring variables. ES6 introduced let and const to overcome issues with var. Below information gives you better idea about them.
| var | let | const | |
|---|---|---|---|
| Meaning | Var is used to declare variables(old way of declaring variables) | let is the new way of declaring variables | const is used to declare const values. Once the value is assigned it can not be modified |
| Scope | Function or global scope | Global or block Scope | Global or block Scope |
| Usage | var age = 20; | let name ="foo"; | const id =1; |
check the below program to understand issues with var. In the below example, age is a var variable whose value is not getting reflected back to 20 even after coming out of if block but with let, name will again becomes foo. Hence, let is recommended to use.
let name ="foo";
console.log('name:', name); //global scope, here name = foo
const id =1;
console.log('id:', id); //global scope, here id=1
var age = 20;
console.log('age:', age); //global scope, here age = 20
if(id) {
let name ="bar"; //block scope
console.log('inside block name:', name); //here name = bar
//const id =1;
// if you uncomment the above line, program will throw an error as const can't be assigned twice
console.log('id:', id); //id =1
var age = 25;
console.log('age:', age); // here age=25
}
console.log('outside block name:', name); //here name will be foo again
console.log('id:', id); //id =1
console.log('age:', age); // age will not become 20 and it remains 25 even after the block is ended
6 years ago by Divya