Sobes.tech
Junior — Middle

What is the difference between variable declarations using var and let in JavaScript?

sobes.tech AI

Answer from AI

In JavaScript, the keywords var and let are used for declaring variables, but there are important differences between them:

  1. Scope:

    • var has function scope. If declared inside a function, the variable is visible throughout the entire function.
    • let has block scope. The variable is only visible within the nearest enclosing {}.
  2. Hoisting:

    • Variables declared with var are hoisted and initialized with undefined at the beginning of the function.
    • Variables with let are also hoisted but not initialized, accessing them before declaration results in a ReferenceError (Temporal Dead Zone).
  3. Re-declaration:

    • var allows re-declaring the same variable within the same scope.
    • let does not allow re-declaration within the same scope.

Example:

function test() {
  if (true) {
    var x = 1;
    let y = 2;
  }
  console.log(x); // 1
  console.log(y); // Error: y is not defined
}

test();

In modern JavaScript standards, it is recommended to use let (or const for constants) due to more predictable behavior and scope limitation.