Go deep in NodeJS - Part 4
This post inspired by javascripttutorial
An execution context is like a box where your JavaScript code runs. It keeps track of variables, functions, and this keyword at any time. There are different types of boxes depending on where the code is running: globally, inside a function, or inside an eval function.
Types of Execution Contexts:
The default context is where your code starts running.
Create a global object like window in the browser or global in Node.js. (It contains global variables and functions that do not exist in any function.)
Every time a function is called, there is the creation of the execution context for the function.
It covers the list of parameters passed to the function, the variables declared within this function and inner functions, and the value of this.
Nested functions generate their own execution contexts.
Code executed inside an eval function has its execution context. (See the `What is Eval?` section at the end of this article.)
领英推荐
Execution Contexts Phases
Each execution context has two phases: the creation phase and the execution phase.
Creation Phase:
The Creation phase in JavaScript is the preparation phase that prepares the environment that is required for running the code. It can be defined as a state of doing all the work before actually doing the work.
Execution Phase:
Executes the code line by line, sets variable values, and Executes functions based on the code. For each function call, the JavaScript engine creates a new?function execution context.
What is Eval?
The?eval()?function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script.
console.log(eval('3 + 2'));
// output: 5
console.log(eval(new String('3 + 2')));
// output: 3 + 2
console.log(eval('3 + 3') === eval('6'));
// output: true
console.log(eval('3 + 3') === eval(new String('3 + 3')));
// output: false
Conclusion
In this part we learned about Execution Context, this issue becomes tangible and understandable when we know about other JavaScript runtime subjects in future parts.