Everything in JavaScript happens inside an "Execution Context”. Whenever a JavaScript program is run an execution context is created.
when we run the above code, a global execution context (GEC) is created. It is created in two phases:
1)Creation Phase or Memory Creation
In this phase, javascript allocates the memory to all the variables and functions present in the program. The variables are stored with the value undefined and the function is stored with all the code present in that particular function. For the above code, the variable number is stored with the value undefined and the function add is stored with value b/w the {...} curly braces. The result1 is also a variable so it is stored with the value undefined.
2)Code Execution Phase
In this phase the main execution takes place and the javascript runs through the code line by line. Now the number value is changed from undefined to 10. Then it moves to the next line as there is nothing to execute it moves to line 5. In line 5 function invocation takes place. When a new function is invoked a new execution context is created within the GEC.
Now the again above process is repeated with the two phases but for only the add function. After the function is executed completely, the execution context created for that particular function will get deleted automatically.
Now, when the whole javascript program is executed completely the GEC will also get deleted.
A Call stack is also maintained by javascript. Call stack maintains the "Order of execution of execution contexts". It works similarly as a stack whenever a new function is invoked its execution context is pushed into the call stack.
The GEC is at the bottom of the call stack as it is created at the starting of the program and all the new execution context is pushed on top of it. So when a function's execution gets finished its execution context is also removed from the call stack.
I hope you would have found this article beneficial. Thank you for reading through this article.
Keep Striving for the progress instead of perfection