Skip to main content

How does JavaScript Work?

Updated 2 min readMarkdown
How does JavaScript Work?

Everything in JavaScript Happens Inside an Execution Context.

Execution Context is divided into two components:

  • Memory Component

  • Code Component

Variable and functions exist as key-value pairs in the Memory Component.
Memory Component is also known as Component Variable Environment.

Code Component is a place where code is executed one line at a time.

Do you know that JavaScript is a Synchronous single-threaded language?
That means it executes one command at a time in a specific order.

How does JavaScript code get executed?

When you run a JS code, An Execution Context is created, in two phases:

  1. Creation Phase (or) Memory Creation Phase

  2. Code execution Phase

    Consider the code:

     var n=3;
     function square(num){
             var ans= num*num;
             return ans;
     }
     var square2 = square(n);
     var square4 = square(4);
    
    1. Creation Phase:

JavaScript first gives a placeholder called "undefined" to all the variables and puts them in the memory component.

Whereas, it copies the whole code, in the case of function.

2. Code execution phase:

When it starts executing and goes through the first line it encounters "var n=3;", then it replaces undefined with "3" in the memory component of the execution context.

After encountering a function in the second line, it again creates an execution context of the function in the code component of the execution phase and assigns "undefined" to the variables in it.

After encountering these lines below, it goes back to the function and replaces the "undefined" value with the argument given.

After the execution of the whole code, the Execution Context gets deleted automatically.

How does JavaScript Handle all of this?

JavaScript has its own CallStack.

When you run a JS Script code, a Global Execution Context gets created and pushed onto the stack.

Suppose, during the execution, if it encounters a function "a()",
a() is pushed onto the stack.

After the execution of a(), it gets popped and the control goes back to the Global Execution Context.

Whenever an Execution Context is created, it is pushed onto the stack.
Whenever an Execution Context is deleted, it is popped off the stack
After the whole execution, the Call stack gets empty.
This is how the Call stack maintains the order of execution of the Execution Context.

So, the next time you're debugging or optimizing your JavaScript applications, remember the role of the Call Stack in maintaining the order of Execution Context, as it is a key concept in mastering the language.

Thanks for reading,
Cheers!

Follow me on
Twitter: https://twitter.com/AnandMunjuluri
LinkedIn: https://www.linkedin.com/in/anand-munjuluri-6885aa221/

No comments yet. Be the first to comment.