What is a difference between var and let in JavaScript?

Experience Level: Junior
Tags: JavaScript

Answer

In JavaScript, var and let are both used for declaring variables, but they have some differences:

  • Scope: Variables declared with var are function-scoped, whereas variables declared with let are block-scoped.
  • Hoisting: Variables declared with var are hoisted to the top of their scope and initialized with a value of undefined.
  • Reassignment: Both var and let variables can be reassigned a new value.

Here's an example to illustrate the difference between var and let:

function myFunction() {
  var x = 1;
  if (true) {
    var x = 2; // same variable as above
    console.log(x); // Output: 2
  }
  console.log(x); // Output: 2
}

function myOtherFunction() {
  let y = 1;
  if (true) {
    let y = 2; // different variable than above
    console.log(y); // Output: 2
  }
  console.log(y); // Output: 1
}