⏱ 0:01est. 3 min
Chapter 14- Function Invocation and the Execution Stack
Notes
- #BIGWORD Invocation : Calling a function , in js by using parentheses ()
What happens when you invoke a function in js?
Example 1
function b(){
}
function a(){
b();
}
a();
- First of all global execution context is created and code is executed.
- a() - New execution context is created and executed and placed on execution stack
- Whenever you execute a function in js. A new execution context is created and pushed on the execution stack. It will have it's own space for variables and functions and then it will execute line by line. However if i have another function call inside function it will stop that execution and create another execution context and run that code. This is how function execution happens in javascript.
- Once b() is executed it will be popped out of the stack then a() then back down to global. The order lexically doesn't matter nor does the rest of the code that happens to be surrounding those function calls. Explained in example 2
Example 2
function a(){
b();
var c;
}
function b(){
var d;
}
a();
var d;
This doesn't matter both functions are in memory during the create phase of the initial execution of the global context
Execution process of example 2
First of all a() at the bottom will be invoked and it's pushed on the execution stack then that becomes the currently running code. var d will not be executed yet because js is synchronous, one line at a time. Then a() will create its space and execute b(), now this will creates its new execution context and pushed on the top of stack and it will run it's single line of code only once it's finished we will go back to finishing a() when the function finishes the execution context is popped off the stack. Now current execution context is again a() now it will run another line of code which hasn't be executed yet in this execution context i.e var c and when a() is finished it's popped off the stack and the next line of code that hasn't been executed yet in the global execution context is run i.e var d