How JavaScript Code is executed? in & Call Stack | Namaste JavaScript Ep. 2 notes by samjs
In the previous blog, we learnt about Execution context, let's see how's the creation of execution context happens
Creation of javascript execution context
creation of execution context can be separated into two phases:
memory allocation phase
here memory is allocated for each variable and function, the variables are assigned to a value of undefined,
the whole function is stored as a value in the function key
code execution phase
here the actual values are assigned to the variable.
then comes the interesting part, the function invocation. when a function call happens a brand new execution context is created inside the global execution context
and inside the functions execution context, the same memory allocation phase and the execution phase repeats,
when the function encounters the return statement the control will go back to the global context and the functions execution context will be deleted.
Call stack in JS
managing these execution contexts can be a headache especially when the code has many functions which are in a nested complex structure, but js engine elegantly handles this with a structure called CallStack
callstack maintains the order of execution in javascript
when a javascript function runs initially the global execution context is pushed into the stack then all the execution context are pushed on top of it
then finally after all the execution happened the even the global execution context also deleted from the call stack
Subscribe to my newsletter
Read articles from sam directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
sam
sam
im a developer who loves to code in javascript writes about javascript, frontend, React, Next.js