What is lexical scope in JavaScript?

In JavaScript, lexical scope refers to the scoping rules used to determine where variables and functions are accessible within the code. It’s a way of defining the visibility of variables and functions in the code.

The basic principle of lexical scope is that a variable or function defined within a particular block of code (such as a function or a loop) is only accessible within that block and not from outside of it. This is in contrast to dynamic scope, where the scope of a variable is determined at runtime based on the call stack.

In JavaScript, lexical scope is determined by the physical location of variables and functions within the code, as well as the nesting of scopes. For example, variables declared within a function are only accessible within that function, while variables declared in the global scope are accessible from anywhere in the code.

Here’s an example of lexical scope in JavaScript:

function outerFunction() {
  let outerVariable = 'I am outerVariable';

  function innerFunction() {
    let innerVariable = 'I am innerVariable';
    console.log(outerVariable); // outputs: "I am outerVariable"
  }

  innerFunction();
  console.log(innerVariable); // ReferenceError: innerVariable is not defined
}

outerFunction();

In this example, the innerFunction has access to the outerVariable because it is defined within the scope of the outerFunction. However, trying to access innerVariable from outside its scope (in this case, from within the outerFunction) results in a ReferenceError.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *