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.

ACI image

ACI.dev: The Only MCP Server Your AI Agents Need

ACI.dev’s open-source tool-use platform and Unified MCP Server turns 600+ functions into two simple MCP tools on one serverβ€”search and execute. Comes with multi-tenant auth and natural-language permission scopes. 100% open-source under Apache 2.0.

Star our GitHub!

Top comments (0)

Join the Runner H "AI Agent Prompting" Challenge: $10,000 in Prizes for 20 Winners!

Runner H is the AI agent you can delegate all your boring and repetitive tasks to - an autonomous agent that can use any tools you give it and complete full tasks from a single prompt.

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. ❀️