var vs let vs const in JavaScript

In this tutorial, you will learn about var, let, and const. You can declare a variable in JavaScript through var, let, and const.

They are used to store the data.

var is a Function Scope, not a Block Scope.

You can redeclare the variable.

var in JavaScript

This is an old way to declare a variable in JavaScript

Example of redclare the variable


var name = "John";
var name = "Tom";   // ✅ Allowed
name = "Alan";      // ✅ Allowed

Example of Function Scope


if (true) {
  var x = 20;
}
console.log(x);  // 20 ✅

let in JavaScript

let was introduced into ES6.

You can not re-declare the variable.

let is a Block scoped.

Example of re-declare the variable


let age = 35;
age = 40;   // Allowed ✅
let age = 50;  // ❌ Not allowed

Example of Block Scope


if (true) {
  let x = 20;
}
console.log(x);  // ❌ Error

const in JavaScript

const was introduced into ES6.

You can not re-declare the variable.

You can not reassign the value of the variable.

Example:


const num = 20;
num = 30;  // ❌ Error

Note: You can change the value to an object or an array.


const user = { name: "John" };
user.name = "Tom";   // ✅ Allowed

Var vs Let vs Const (Comparison Table)

Feature var let const
Scope Function Block Block
Re-declare Yes No No
Reassign Yes Yes No
Hoisting Yes (undefined) Yes (TDZ) Yes (TDZ)
Modern Usage ❌ Avoid ✅ Yes ✅ Yes