DEV Community

himanshuc11
himanshuc11

Posted on

Working of JS Engine

JavaScript runs through the code it needs to execute, twice. This results in two phase execution of code

The two phases are popularly referred as
1) Creation Phase
2) Execution Phase

Creation Phase

In the creation phase, the JavaScript Engine goes through the code to

  • Create a special object called activation object. This object is used to hold all the variables and functions
  • Create a scope chain, which is an array of lexical environments.(Will be discussed in detail in later blogs)
  • Determine the value of 'this', which is a special keyword in JavaScript which refers to the object calling the function

Execution Phase

In this phase, the JavaScript Engine goes through the code line by line(in the order dictated by the thread of execution) and executes each line of code, and updates the values of variables as needed

Advantages of 2 Phase Execution Process

  1. As we can see, during the creation phase, JavaScript has access to all the variables and functions, we can get access to those functions. Hence we can now call a function before its definition.
// Function call before, definition is valid
dev()
function dev() {
// Some Code
}
Enter fullscreen mode Exit fullscreen mode

Hence call before definition is now possible in JavaScript Engine

  1. JavaScript now also knows all your variables and sets a initial value 'undefined' to it. This way if some identifier is not declared, the error message would give 'not defined' instead of 'undefined'
console.log(x)  // This gives undefined
let x = "dev"
console.log(x) // This gives "dev", as it is updated on the line above
Enter fullscreen mode Exit fullscreen mode
console.log(y) // This is not defined as 'y' is not a valid identifier that JavaScript knows about
let x = "dev"
Enter fullscreen mode Exit fullscreen mode

To get a video tutorial on the concept
https://www.youtube.com/watch?v=wtBbanu-kUY

References:
https://medium.com/@happymishra66/execution-context-in-javascript-319dd72e8e2c

https://medium.com/@sudhakarsp06/creation-phase-and-execution-phase-in-javascript-32fcdbef60f4

Top comments (0)