Lexical Environment
Hello all, I hope you read the first article of JS Essentials i.e. Syntax Parser. Now let’s proceed further and talk about our next under the hood concept which is ‘Lexical Environment’.
Let’s first understand what is the meaning of the word ‘lexical’ ? Lexical is nothing but related to words or vocabulary of a language or grammar. A lexical environment is where something sits physically in the code we write. And that environment is created behind the scene. This is the logistic concept & we can’t actually access it from our JS code. Then why do we need to understand it ? Because whenever we are creating any function in JS, we have been creating a lexical environment along with it but we didn’t know it.
A Lexical environment is where something sits physically in the code we write.
Let’s take an example to understand it better. Suppose there is a function having one variable inside it.
function greet() {
var msg = “Hello World”;
}
We can say that variable ‘msg’ sits lexically inside the function. Just imagine physically where we are writing the code, there it sits. But if you read our last blog post about Syntax Parser, we said that our code is not actually given directly to the computer, but it translated into something the computer can understand.
But in programming language, ‘lexical environment’ is important, that means where we see things written gives us an idea of where it will actually sit in the computer’s memory. And how it will interact with other variables, functions and elements of the program. And that’s because the program, the compiler that is converting our code to those instructions cares about where we put things. It makes decisions that syntax parser going through everything makes decisions.
So when we talk about the lexical environment of something in the code we’re talking about where it’s written & what surrounds it. I hope this post helps to understand one of the the basic terms of JS. I will talk about ‘‘Execution Context’ in upcoming articles. Let me know if you have any queries in the comments section below or on my personal email address. Till that stay tuned ! Thank you for reading.