What’s the difference between var, let, and const keywords?

JavaScript has three ways to declare variables.

var width = 100;
let height = 200;
const key = "Tech Talks";

var

{
var a = 10;
console.log(a);
} //block 1
{
a++;
console.log(a);
} //block 2
function fun1() {
var a = 10;
console.log(a);
} //function scope of fun1
function fun2() {
a++;
console.log(a);
} //function scope of fun2

let:

{
let a = 10;
console.log(a);
} //block 1
{
a++;
console.log(a);
} //block 2
function fun1() {
let a = 10;
console.log(a);
} //function scope of fun1
function fun2() {
a++;
console.log(a);
} //function scope of fun2

const:

{
const a = 10;
console.log(a);
} //block 1
{
a++;
console.log(a);
} //block 2
{
const a = [1, 2, 3];
const b = { name: "hello" };
a.push(4, 5); //mutating the value of constant "a"
b.name = "World"; //mutating the value of constant "b"
console.log(a); //this will show [1,2,3,4,5]
console.log(b); //this will show {name: "World"}
}
{
const name = "Tech Talks";
const PI = 3.14;
const a = [1, 2, 3];
const b = { name: "Hello" };
name = "Ankit Kumar"; //Throws an error, since we are attempting to re-assign "name” to a different value.
PI = PI + 1; //Throws an error, since we are attempting to re-assign PI to a different value.
a = [1, 2, 3, 4, 5]; //Throws an error, since we are attempting to re-assign "a" to a different value.
b = { name: "Hello Ankit" }; //Throws an error, since we are attempting to re-assign "b" to a different value.
}

Summary

var:

let:

const:

Polyglot Fullstack Developer