As I understand it, all code is executed in 2 stages: initial code scan (compilation) and code execution. However, it's still not entirely clear to me at what stage the declaration of variables occurs.
On the one hand, it specifies here that an execution context is created before executing the JavaScript code. And in the same article, below is an example of a schematic representation of an execution context:
let a = 20;
const b = 30;
var c;
function multiply(e, f) {
var g = 20;
return e * f * g;
}
c = multiply(20, 30);
console.log(c);
//Схематичное представление контекста выполнения для этого кода будет выглядеть так:
// GlobalExectionContext = {
// ThisBinding: <Global Object>,
// LexicalEnvironment: {
// EnvironmentRecord: {
// Type: "Object",
// // Данные о привязках для идентификаторов
// a: < uninitialized >,
// b: < uninitialized >,
// multiply: < func >
// }
// outer: <null>
// },
// VariableEnvironment: {
// EnvironmentRecord: {
// Type: "Object",
// // Данные о привязках для идентификаторов
// c: undefined,
// }
// outer: <null>
// }
// }
// FunctionExectionContext = {
// ThisBinding: <Global Object>,
// LexicalEnvironment: {
// EnvironmentRecord: {
// Type: "Declarative",
// // Данные о привязках для идентификаторов
// Arguments: {0: 20, 1: 30, length: 2},
// },
// outer: <GlobalLexicalEnvironment>
// },
// VariableEnvironment: {
// EnvironmentRecord: {
// Type: "Declarative",
// // Данные о привязках для идентификаторов
// g: undefined
// },
// outer: <GlobalLexicalEnvironment>
// }
// }
That is, as I understand it, during the initial scan of the code, variables are declared. For variables declared with let
and const
, it writes uninitialized
- that is, these variables are declared, but not yet initialized. Variables declared with var
are immediately initialized with undefined
.
On the other hand, there is TDZ (temporal dead zone). Here is the definition:
TDZ is a term to describe the state when variables are not available. They are in scope but not declared.
And here it seems to be that the declaration occurs during the execution of the code, not before execution when context execution is created. So when does it actually happen?