DEV Community

Nitika Poudel
Nitika Poudel

Posted on

Let's JAVASCRIPT !!

You can't change the world if you don't know the basics. Similarly, you can't be a better programmer unless you've set your foundation strong. It's so important to know how a technology works under the hood in order to be able to solve problems efficiently as an engineer. So, without further ado let's dive right into getting our basics right.

Let's Javascript!!

Today we will look into how a piece of JS code runs.

Points to remember

  1. JavaScript executes the code line by line i.e. one line at time, known as the thread of execution.
  2. It stores the data like Strings, Arrays and even the code (function definitions) in its memory.
  3. The Execution context is comprised of the thread of execution and the memory.
  4. Whenever a function is invoked or called, a new execution context is created and that function call is pushed to the call stack.
  5. Javascript keeps track of what function is currently running with the help of the call stack.
  6. After the function is finished running, it is popped off the stack.
  7. Whatever is on top of the call stack is the function currently running.
  8. On the bottom of call stack is always the global execution context.

Now, Let's visualise

const a = 10;
function multiplyBy3(num){
  let result = num * 3;
  return result;
}
const multiplied = multiplyBy3(a); 
Enter fullscreen mode Exit fullscreen mode

Here is how the snippet of code gets executed as we go along with the thread of execution:
initial call stack
Initially the call stack consists of only the global execution context.
global execution context

  1. The value "10" gets stored in the global memory with an identifier "a".
  2. All the code of the function is bundled up and stored in the global memory with an identifier "multiplyBy3.
  3. The identifier "multiplied", which is supposed to store the result of the execution of function: multipliedBy3 , remains uninitialized for a moment. Call stack with function Now, a new execution context is created for the function multiplyBy3 inside the global execution context and it is added to the call stack. Function execution context
  4. The value of passed-in argument and the result of multiplication are saved with the label "num" and "result" respectively in the local memory of the function's execution context. Final execution context
  5. When the function execution is completed, everything (the whole execution context) is deleted besides what is returned out of the function.
  6. The function is then popped off the call stack and the returned value is stored with an identifier "multiplied". initial call stack
  7. Now the control flows back to the global execution context.

Top comments (0)