Difference between var/let/const in JavaScript

Namish Aggarwal
2 min readJul 13, 2021

Many of you must have seen use of var, let and const in JavaScript code. So, question arises that what is the actual difference between all of them. Let’s dive in and see the difference in their usage and their scope.

var

Usage : It is the most commonly used of all the above mentioned in JavaScript and is used to initialize variables. User can change the value of variables declared as var type.

var x=4;x=5;console.log(x);   // outputs 5 on console

Scope : If it’s defined inside any function then it’s scope is local to that function. But, if it’s defined outside any function or inside if/else, for, while, do-while then it becomes global and can be accessed from anywhere after the variable is defined.

if(true)
{
var x=3;
}
console.log(x); // outputs 3 on console

let

Usage : It is also used to declare the variables in JavaScript and user can change the value of variables declared as let type.

let x=4;x=5;console.log(x);  // outputs 5 on console

Scope : If any variable is initialized using let then it’s scope is local to the function inside which it is defined. If it’s defined outside any function then it is global and can be accessed from anywhere after the variable is defined.

if(true)
{
let x=3;
}
console.log(x); // error: x is not defined

const

Usage : It is used to declare those variables whose value is to be kept constant. Variable once defined using const cannot be redefined and their value is fixed.

const x=4;x=5;console.log(x);  // error: cannot modify const variable

Scope : It’s scope is similar to let i.e. If any variable is initialized using const then it’s scope is local to the function inside which it is defined. If it’s defined outside any function then it is global and can be accessed from anywhere after the variable is defined.

if(true)
{
const x=3;
}
console.log(x); // error: x is not defined

--

--