When you create a function they are compiled at run time. The function is invoked when you call them.
Let me explain a little bit:
You can have any number of function contexts, and each function call creates a new context.
//Global Context
var helloWorld = "hello world!";
function foo(){//execution context
function bar(){//execution context
console.log('bar');
}
}
foo();
So, in the above code function foo is being called, and creates the new context for function foo and the execution context for bar is only created after you call it but it is compiled already during the run time.
When a script is loaded first time by the browser, it enters the global execution context by default. If you call a function in global scope, the sequence flow of your program enters the function being called, creating a new execution context and pushing that context to the top of the execution stack.
Now let's have a detail about execution context:
So, everytime a function is called, a new execution context is created. Every call to an execution context has 2 stages:
1. creation stage:
When the function is called but before it executes any code inside are: create the scope chain, create variables, functions and arguments, and determine the value of "this".
2. activation stage:
Assign values, references to functions and executes the code.
Now, let's have a bit more knowledge of execution context:
function foo (a, b, c) {
function z(){alert(‘Z!’);}
var d = 3;
}
foo(‘foo’,’bar’);
ExecutionContext in the foo() call: Step 1: arguments is created
ExecutionContext: {
arguments: {
0: ‘foo’, 1: ‘bar’,
length: 2, callee: function() //Points to foo function
}
}
Step 3a: variable instantiation, arguments
ExecutionContext: {
arguments: {
0: ‘foo’, 1: ‘bar’,
length: 2, callee: function() //Points to foo function
},
a: ‘foo’, b: ‘bar’, c: undefined
}
Step 3b: variable instantiation, functions
ExecutionContext: {
arguments: {
0: ‘foo’, 1: ‘bar’,
length: 2, callee: function() //Points to foo function
},
a: ‘foo’, b: ‘bar’, c: undefined,
z: function() //Created z() function
}
Step 3c: variable instantiation, variables
ExecutionContext: {
arguments: {
0: ‘foo’, 1: ‘bar’,
length: 2, callee: function() //Points to foo function
},
a: ‘foo’, b: ‘bar’, c: undefined,
z: function(), //Created z() function,
d: undefined
}
Step 4: set this value
ExecutionContext: {
arguments: {
0: ‘foo’, 1: ‘bar’,
length: 2, callee: function() //Points to foo function
},
a: ‘foo’, b: ‘bar’, c: undefined,
z: function(), //Created z() function,
d: undefined,
this: window
}
After the creation of ExecutionContext, the function starts running its code from the first line until it finds a return or the function ends. Every time this code tries to access a variable, it is read from the ExecutionContext object.