When a JavaScript engine executes a script, it creates execution contexts. Each execution context has two phases: the
creation
phase and theexecution
phase.(We will cover this concept in future)
Here is an exmaple: Creation and Execution phase
Tokenizing
:var x = 1;
<KEYWORD, var> <ID, x> <EQUALS> <INTEGER, 1> <SEMICOLON>
Parsing
:- It'll generate
AST
and check syntax againstlanguage rules
. e.g.assignment = ID followed-by EQUALS followed-by INTEGER
- It'll generate
function square(x) {
var result = x * x;
return result;
}
The AST representation will look like:
So If a code has a syntax error, it will throw an error:
var validCode = function() {
alert('valid code ran!');
};
validCode();
// on purpose syntax error after valid code that could run
syntax(Error()
/*Output:
Uncaught SyntaxError: missing ) after argument list
*/
Code Generation
: When a script executes for the first time, the JavaScript engine creates aGlobal Execution Context
. During this creation phase, it performs the following tasks:
- Create a global object i.e.,
window
in the webbrowser
orglobal
inNode.js
. - Create a
this
object binding which points to the global object above. - Setup a memory heap for storing variables and function references.
- Store the function declarations in the memory heap and variables within the global execution context with the initial values as
undefined
. ... ReadMore