Javascript Variable Declaration

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 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";

Now, change the name from John to Rom.


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];
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){

Output:- John