#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
•Question 1 of 50easy

What is the difference between let, const, and var?

Understanding variable declarations in JavaScript.

What You'll Learn

  • Differences between var, let, const
  • Scoping rules
  • Best practices

Comparison

Featurevarletconst
ScopeFunctionBlockBlock
RedeclareYesNoNo
ReassignYesYesNo
HoistingYes (undefined)TDZTDZ

Examples

code.jsJavaScript
// var - function scoped
function test() {
  var x = 1;
  if (true) {
    var x = 2; // same variable
  }
  console.log(x); // 2
}

// let - block scoped
function test2() {
  let y = 1;
  if (true) {
    let y = 2; // different variable
  }
  console.log(y); // 1
}

// const - cannot reassign
const z = 1;
z = 2; // Error!

Best Practice

Prefer const by default, use let when reassignment needed, avoid var.