How JavaScript executes: 3 phases of JavaScript code execution
This is the next part of how JavaScript executes. In the previous post, we proceeded with Execution Context. In this post we look into what execution phases JavaScript has.
The first phase — Static Semantics
Static Semantics is a phase of JavaScript code execution that occurs at the moment when this very code is passed as input to our agent (runtime).
This phase will be applied to all code constructs written in text form, regardless of whether the code is executed or not.
(
() => {
something;
let foo = 'foo';
let foo = 'bar';
}
)()The second phase — Runtime Semantics: EvaluateBody
The next phase, which causes our code to start executing, is called the syntax-directed operation EvaluateBody.
This operation describes what the agent or runtime should do and what operations it should perform before any code (after the Static Semantics phase 1) starts executing.
EvaluateBody is a process of evaluation and preparation; the beginning of what is a body (a set of JS commands) starts executing.
A more detailed algorithm is here.
console.log('Init',
(() => {
'use strict'
return initVar;
var initVar = 'KS';
}
)()
)The reader will have observed that the call to initVar did not result in any error but returned undefined, although the variable denoting initVar is associated with the value and is outside our return.
Get Andrei Smolka’s stories in your inbox
Join Medium for free to get updates from this writer.
If we comment out our var, we will get such an error, precisely in the second phase, when the code will be executing.
The third phase — Runtime Semantics: Evaluation
The algorithms that define the semantics that should be called at runtime are called runtime semantics. Runtime Semantics are defined by abstract operations or syntactically oriented operations.
This phase is directly related to the interpretation of our code. In this phase, the remaining effects of our code’s behavior manifest themselves.
Summary
Static Semantics is the phase in which we can get code interrupts, even those that will never be executed.
The phases EvaluateBody and Evaluation are tightly connected.
EvaluateBody — performs manipulations with statements in a loop, inside its code, and directly affects the code that will then be executed.
The Evaluation phase is the stage of interpreting our code.
References
Static Semantics — https://tc39.es/ecma262/#sec-static-semantic-rules
Runtime Semantics: EvaluateBody — https://tc39.es/ecma262/#sec-runtime-semantics-evaluatebody
Runtime Semantics: Evaluation — https://tc39.es/ecma262/#sec-evaluation








