2Minutes: Lexical Environment In JavaScript
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 definedWe 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 definedWe 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 MouhammadHere 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