JavaScript is an easy-to-learn programming language compared to many of its counterparts. However, a few basic concepts need a bit more attention if you want to understand, debug, and write better code.
In this article, we will learn about two such concepts,
As a beginner to JavaScript, understanding these concepts will help you understand the this
keyword, scope
, and closure
much more comfortably. So enjoy, and keep reading.
In general, a JavaScript source file will have multiple lines of code. As developers, we organize the code into variables, functions, data structures like objects and arrays, and more.
A Lexical Environment
determines how and where we write our code physically. Take a look at the code below:
function doSomething() {
var age= 7;
// Some more code
}
In the above code, the variable age
is lexically inside the function doSomething
.
Please note that our code does not run as-is. It has to be translated by the compiler into computer understandable byte-code. So the compiler needs to map what is lexically placed where in the meaningful and valid way.
Usually, there will be more than one Lexical Environment
in your code. However, not all the environments get executed at once.
The environment that helps the code get executed is called the Execution Context
. It is the code that’s currently running, and everything surrounding that helps to run it.
There can be lots of Lexical Environment
s available, but the one currently running code is managed by the Execution Context
.
Check out the image below to understand the difference between a Lexical Environment and Execution Context:
Lexical Environment vs Execution Context
So what exactly happens in the Execution Context? The code gets parsed line-by-line, generates executable byte-code, allocates memory, and executes.
Let’s take the same function we have seen above. What do you think may happen when the following line gets executed?
var age = 7;
There are many things happening behind the scenes. That piece of source code goes through the following phases before it is finally gets executed:
Tokens
. For example, the code var age = 7;
tokenizes into var, age, =, 7 and, ;.AST
(Abstract Syntax Tree).The animated picture below shows the transition of the source code to executable byte-code.
Source Code to Executable Byte-Code
All these things happen in an Execution Context
. So the execution context is the environment where a specific portion of the code executes.
There are two types of execution contexts:
And each of the execution contexts has two phases:
Let’s take a detailed look at each of them and understand them a bit better.
#javascript