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

Answer:

1. Scope:

2. Redeclaration:

3. Reassignment:

4. Hoisting:

Examples

var example

function exampleVar() {
  var x = 10;
  if (true) {
    var x = 20; // Same variable, re-declared
    console.log(x); // 20
  }
  console.log(x); // 20
}
exampleVar();

let example

function exampleLet() {
  let x = 10;
  if (true) {
    let x = 20; // Different variable due to block scope
    console.log(x); // 20
  }
  console.log(x); // 10
}
exampleLet();

const example

function exampleConst() {
  const x = 10;
  // x = 20; // Error: Assignment to constant variable
  console.log(x); // 10
}
exampleConst();

Key Points

Read more about var

Read more about const

Read more about let