I have been curious of how js code is executed from beginning to the end.
I have read about the event loop and seen this great video, how stack frames look like here,and also read about how the V8 engine compiles js code here.
Question :
When does V8 starts compiling and executing the code in relation to the event loop stack ?
is it when the function is about to get popped out of the stack?
or do all functions get compiled, right before they are placed on the stack ?
therefore the proccess of putting other function on top is acctually only dealing with machine code, if so does the execution of that machine code occurs when popping the function from the stack ?
In case my question is not understood, i believe via this example it would be better understood
Example :
function foo() {
var name=`foo`;
var obj = {
number: 6
}
console.log(obj.number);
}
function baz() {
var name = `baz`;
console.log(a);
foo();
}
baz();
- the first process that occurs is lazy parsing, where all the file is being parsed for syntax errors, but not fully parsed so it takes less time.
going through the function declerations
- does the v8 engine now compiles the function declaration code to machine code ? or its not his turn yet..
baz is called , baz is placed on bottom of the stack ,and in its stack frame the name variable value is stored (since its a primitive).
- when exactly does buz gets parsed and converted to machine code ? before its placed on the stack ? or when it pops off ?
console.log placed on top of baz and is executed, - console shows
baz
- is this is the place where the console.log js code is compiled to machine code and executed ?
console.logs pops of the stack.
foo is placed on top of baz, obj is placed in heap (since its a reference type), and
name=foo
is placed in foo`s stack frame.console.log goes on top of foo, and is executed , console shows 6.
- console.log pops off.
- foo pops off, along with its local variable value.
- baz pops off along with its
name=baz
local variable