Skip to main content
Being Idea Innovations
What is lexical scope in JavaScript?
Back to Blog

What is lexical scope in JavaScript?

25 April 20231 min readJavascript
Share:

Lexical scope, also known as static scope, refers to the idea that the scope of a variable is determined at the time it is defined, based on its location within the source code, and does not change during runtime. In other words, a variable defined within a block of code (e.g., a function) is only accessible within that block and any nested blocks.

Here’s an example of lexical scope in JavaScript:

function outerFunction() {
  const outerVar = 'I am in outerFunction';

  function innerFunction() {
    const innerVar = 'I am in innerFunction';
    console.log(outerVar); // Output: 'I am in outerFunction'
  }

  console.log(innerVar); // Output: Uncaught ReferenceError: innerVar is not defined
  innerFunction();
}

outerFunction();

 

In this example, outerFunction defines a variable called outerVar within its block of code. innerFunction is also defined within outerFunction‘s block of code, so it has access to outerVar. However, innerVar is defined within innerFunction‘s block of code and is not accessible outside of that block. When we try to log innerVar outside of innerFunction, we get a ReferenceError because it is not defined in the outer scope.

This example demonstrates how lexical scope works in JavaScript. Variables defined within a block of code have access to variables defined in their parent blocks, but not vice versa. This allows for more control over the variable scope and can help prevent naming conflicts between different parts of a program.

Share:

Want to talk tech?

We ship software that scales. Let's work together.

No long-term contracts
Senior engineers only
US · AU · NZ timezone coverage
14-day trial on retainers