Javascript: Var vs Let vs Const

Javascript: Var vs Let vs Const

Here are some of the differences between var, let and const keywords in JavaScript.

ยท

2 min read

Table of contents

Var is the first keyword introduced to Javascript for declaring variables. This keyword is different from others and has unique properties and use cases. So before ES6 was introduced most people used the var keyword, but nowadays people stopped using this keyword because of these new keywords

ES6 Introduced 2 new keywords for declaring variables in Javascript.

  1. Let: Accessible only Block level and can be reassigned.

  2. Const: Accessible only Block level and can't be reassigned.

Introducing new keywords made var obsolete.

Differences

VarLetConst
ScopeAnywhereBlockBlock
ReassignCan be ReassignedCan be ReassignedCannot be Reassigned
RedeclarationSupportedNot SupportedNot Supported
HoistingSupportedNot SupportedNot Supported
Initialize on DeclarationNot requiredNot requiredRequired

Code Examples

  • Var Keyword
var name = "Prajwal Aradhya";
var counter = 3;
console.log(name); // Prajwal Aradhya
if (counter > 2) {
    var name = "Aradhya, Prajwal";
}
console.log(name); // Aradhya, Prajwal
  • Let Keyword
let name = "Prajwal Aradhya";
let age = 10;

if (age % 5 === 0) {
    console.log("๐Ÿ˜");
} else {
    console.log("๐Ÿ˜Ÿ");
}
  • Const Keyword
const title = "A good movie";
const rating = 5;
// Movie "A good movie" has 5 ๐ŸŒŸ rating.
console.log(`Movie "${title}" has ${rating} ๐ŸŒŸ rating.`);
ย