Sobes.tech
Middle+

What is scope and lexical environment in JavaScript? How does var differ from let/const?

sobes.tech AI

Answer from AI

Scope in JavaScript is the context in which variables and functions are accessible. Lexical environment is the structure that holds variables and functions available at a particular place in the code, and it is determined during the writing of the code, not during execution.

Difference between var and let/const:

  • var has function scope, meaning the variable is accessible throughout the entire function where it is declared.
  • let and const have block scope, meaning they are only accessible within the block (e.g., inside curly braces).
  • var allows re-declaration of the same variable within the same scope, whereas let and const do not.
  • const declares a constant, which cannot be reassigned after initialization.

Example:

function example() {
  if (true) {
    var x = 1;
    let y = 2;
    const z = 3;
  }
  console.log(x); // 1
  console.log(y); // ReferenceError
  console.log(z); // ReferenceError
}
example();
What is scope and lexical environment in JavaScript… - sobes.tech