What is the difference between “let” and “var”?

In JavaScript, let and var are both used to declare variables, but they have some important differences in terms of scope and behavior.

  • The var keyword was used to declare variables before the introduction of let and const in ECMAScript 6 (ES6). Variables declared with var are function-scoped, which means they are only accessible within the function in which they were declared, or if they were declared outside any function, they are accessible throughout the global scope. If a variable is declared with var keyword inside a function, it is still accessible throughout the function, even if it’s declared inside an if-statement or for loop, for example.
function varFunction() {
  if (true) {
    var x = 5;
  }
  console.log(x); // Output: 5
}
varFunction();
console.log(x); // Output: 5
  • The let keyword was introduced in ECMAScript 6 (ES6) as an alternative to var, and it is block-scoped. Variables declared with let are only accessible within the block in which they were declared.
function letFunction() {
  if (true) {
    let x = 5;
  }
  console.log(x); // ReferenceError: x is not defined
}
letFunction();

Leave a Reply