Blog

ES6

JS

var vs let vs const

Discussion on different types of declaration

Ragav Kumar V

Ragav Kumar V

Aug 21, 2022 — Updated Sep 23, 2022 · 2 min read

  • Declaration means creating a variable
  • Redeclaration means re-creating a variable

_7
var x1 = 10;
_7
let x2 = 20;
_7
const x3 = 30;
_7
_7
var x1 = 80; // - ✅ Allowed
_7
let x2 = 70; // - ❌ Error
_7
const x3 = 90; // - ❌ Error

Changing the value of the variable


_7
var x1 = 10;
_7
let x2 = 20;
_7
const x3 = 30;
_7
_7
x1 = 180; // - ✅ Allowed
_7
x2 = 170; // - ✅ Allowed
_7
x3 = 190; // - ❌ Error

  • Our exceptation might be wrong about const since we must embrace how JS works
  • We object/array is declaraed with const inside value could be modified

_20
const player = {
_20
name: "Gukesh D",
_20
game: "chess",
_20
age: 16,
_20
rating: 2699,
_20
title: "Grandmaster",
_20
};
_20
_20
player.rating = 2710; // - ✅ Allowed
_20
console.log(player);
_20
// Output
_20
{
_20
name: "Gukesh D",
_20
game: "chess",
_20
age: 16,
_20
rating: 2710,
_20
title: "Grandmaster",
_20
};
_20
_20
player = 10; // - ❌ Error


_7
const movies = ["Vikram", "KGF", "RRR", "Valimai"];
_7
movies[1] = "Master"; // - ✅ Allowed
_7
_7
console.log(movies);
_7
// Output
_7
// ["Vikram", "Master", "RRR", "Valimai"]
_7
movies = "cool"; // - ❌ Error

@ragavkumarv
swipe to next ➡️