JavaScript variable declaration is the process of creating a variable and optionally assigning it an initial value. When you declare a variable, you inform the JavaScript interpreter to reserve memory space for that variable and optionally initialize it with a value.
var, let and const are used to variable declaration in JavaScript. let and const are introduced in ECMAScript (ES6). before introduced let and const only var is used to variable declaration.
var is used for function scope while let is used to block scoped.
Example:- function scoped
for(var i=1; i<5; i++){
console.log(i);
}
console.log("i value is ",i); //output:- i value is 5
Example:- block scoped
for(let i=1; i<5; i++){
console.log(i); //output:- 1 2 3 4 5
}
console.log("i value is ",i);
Output:- Uncaught ReferenceError: i is not defined
Note:- above example i is block scoped so it will show output in the for loop when you call i after the loop then it will show error.
const declaration:- You can not reassign the value in the const variable.
Example:- If you reassign the value in the premitive datatype then it will show error.
const name="John";
console.log(name);
Now, change the name from John to Rom.
name="Rom";
console.log(name);
Output:-Uncaught TypeError: Assignment to constant variable.
Example:- If you want to reassign the value into array element then value will be update.
const arr=[1,2];
arr[1]=3;
console.log(arr) //Output:- [1,3]
If we can not reassign in const then why use in for of and for in loop?
it seems that they create a new block scope with each iteration. That would mean that each new index is actually a new variable within a new scope & our constant is never reassigned.
var data=[{name:"John", age:35},{name:"Rom", age:30}]
for( const element of data){
console.log(element.name);
}
Output:- John
Rom