arrow_left_alt Back to Blog

2Minutes: Lexical Environment In JavaScript

calendar_today July 19, 2026 | timer 2 min read |

What is Lexical Environment ?


Let’s look at the following:

function sayHello() {
  const name = "Mouhammad";
  console.log("Hello!");
}

console.log(name); // ReferenceError: name is not defined

We get a ReferenceError: name is not defined because the name variable is only accessible within the sayHello() function’s scope (its lexical scope).

Have a look at the following:

if (true) {
  const name = "Mouhammad";
}

console.log(name); // ReferenceError: name is not defined

We get a ReferenceError: name is not defined because the name variable is only accessible within the if block’s scope (its lexical scope).

Have a look at the following:

const name = "Mouhammad";

function sayHi() {
  console.log(`Hello ${name} !`);
}

sayHi(); // Output: Hello Mouhammad

Here we get the correct output because the name variable is in the global scope (the file’s lexical scope).

So, from all the examples above, we can come up with the following definition:

The lexical environment of any piece of code is the context in which it was created.

We have 3 main scopes:

  • Function scope, as in the first example
  • Block scope, as in the second example
  • Global scope, as in the third example

One important rule: inner scopes have access to variables declared in their outer (ancestor) scopes. That’s why when we create a variable in the global scope, it is accessible throughout the entire file unless another variable with the same name shadows it.

That’s 2Minutes Concept, see you in the next one !

Sources

https://www.geeksforgeeks.org/javascript/lexical-scope-in-javascript

https://dev.to/catherineisonline/what-is-lexical-scope-in-javascript-4gi8

https://www.w3schools.com/js/js_scope.asp

index.php