DEV Community

Cover image for Summarizing Namaste 🙏 JavaScript EP04 (How functions work in Js and Variable environment )
Abhinav Singh Jamwal
Abhinav Singh Jamwal

Posted on

Summarizing Namaste 🙏 JavaScript EP04 (How functions work in Js and Variable environment )

Thank you Akshay Saini for this beautiful series. Just summarizing your lessons for whenever I need a quick recap. Same for others. Hope it helps.

image

On right side is Js code and on left side is the output.
Now, we will discuss line by line how this Js code is executed.

image

As we know, execution context goes through two phases.
During memory allocation phase,
x: undefined
a: {...function body...}
b: {...function body...}

During code execution phase, Global execution context is pushed into the Js Call stack.
When line 1 is executed,
x: 1
Since we know that whenever a function is invoked, a new execution context is created.
When line 2 is executed,

image

We can see in the left bottom that in call stack section, execution context named a is pushed into call stack above anonymous (Global execution context)
It goes through same phases and logs the value of x as 10.

After completion, a is popped out of call stack and line 3 is executed.

image

We can see in the left bottom that in call stack section, execution context named b is pushed into call stack above anonymous (Global execution context)
It goes through same phases and logs the value of x as 100.

After completion, b is popped out of call stack and line 4 is executed.

Since at start, the value of x is assigned 1 in the local scope of Global execution context, it logs the value of x as 1.

This is the reason why it logs result 10, 100 and 1.

Top comments (0)