1. Tokenizing / Lexing
2. Parsing
3. Code-Generation
Abstract Syntax Tree
JS is compiled as compilation happens just before (microseconds) the code is executed.
a well-defined set of rules for storing and finding variables (identifiers) in some location.
engine
compiler
scope
LHS
Left-hand Side look-up. Process of looking for a variable (target) to assign it a value.
RHS
Right-hand Side look-up. Process of retrieving the value of a variable (source).
function square(number) {
return number * number;
}
function cube(number) {
return number * square(number);
}
const result = cube(3);
total
LHS
look-ups: 3
assignment to
result = ...
implicit param assignment
number = 3
in fuctioncube(number)
implicit param assignment
number = 3
in fuctionsquare(number)
total
RHS
look-ups: 6
cube(3)
function executioninside
cube
function > retrieve the value fornumber
innumber *
inside
cube
function > execution ofsquare(...)
inside
cube
function > retrieve the value of argumentnumber
insquare(number)
inside
square
function > retrieve value fornumber
innumber *
inside
square
function > retrieve value fornumber
in* number
engine starts at the currently executing Scope, then looks for a variable there, if not found, keeps going up one level an so on util it reaches the outermost global scope and stops whether it finds the variable or not.
g = 10;
function foo(a) {
function bar(a, b) {
var c = 5;
function baz(d) {
return d + c + b + a + g;
}
return baz(5);
}
return bar(10, a + 5);
}
var g;
console.log(foo(15));
50
(function foo(x) {
function bar(y) {
function baz(z) {
w = x * y * z;
return x + y + z;
}
return baz(4);
}
return bar(4);
})(4);
console.log(w);
64
when a variable couldn't be found in any of the Scopes.
when a variable is found but an illegal/impossible action is attempted against its result.
function bar(n) {
return n * m;
var m = 2;
}
console.log(bar(3));
NaN
function bar(n) {
return n * m;
m = 2;
}
console.log(bar(3));
ReferenceError: m is not defined
function bar(n) {
m = 2;
return n * m;
}
console.log(bar(3));
6
'use strict';
function bar(n) {
m = 2;
return n * m;
}
console.log(bar(3));
ReferenceError: m is not defined
function bar(n) {
var m = 2;
return n * m;
}
bar = 5;
console.log(bar(3));
TypeError: bar is not a function
var bar;
function bar(n) {
var m = 2;
return n * m;
}
console.log(bar(3));
6
var bar = 3;
function bar(n) {
var m = 2;
return n * m;
}
console.log(bar(3));
TypeError: bar is not a function
function bar(n) {
var m = 2;
return n * m;
}
console.log(bar(3));
var bar = 3;
6
var bar = 2;
var bar = 'a';
console.log(bar);
"a"