DEV Community

Ramya Sri M
Ramya Sri M

Posted on

Is JavaScript synchronous or asynchronous, and is it single-threaded or multi-threaded? How is JavaScript code executed?

JavaScript is a synchronous, single-threaded language that can execute only one command at a time. It will move to the next line only after the current line has finished its execution. However, JavaScript can perform asynchronous operations using an event loop, Promises, Async/Await and callback queue (JavaScript is synchronous by default).

How is JavaScript code executed?

Everything in JavaScript happens inside an execution context (think of it as a big box or container). The entire JavaScript code is executed within this execution context. It has two components: the memory component (the variable environment) and the code component (the thread of execution).

  • Memory Component: This is where all variables and functions are stored as key-value pairs.
  • Code Component: This is where the code is executed(one line at a time)."

First, a global execution context is created. Within this, each function creates its own execution context.

Before any line of code is executed, memory is allocated for all variables and functions.

How is the code executed after memory allocation?
The JavaScript engine runs through the entire program again(line by line) and executes the code.

Let's look at the following example:


function add(a,b){
   var ans = a+b;
   console.log(ans);
}
var addition = add(6,5);
Enter fullscreen mode Exit fullscreen mode

In this example, a global execution context is created first, which consists of two components: the Memory Component (MC) and the Code Component (CC).

Global Execution Context

For functions, the entire function code is stored in memory. For variables, a special value, undefined, is stored initially.

Execution Context(Function)

When the function is invoked, another execution context is created. In the Memory Component, the values for parameters (a = 6, b = 5) are stored, while variables like ans initially hold the value undefined. In the Code Component, the values from the Memory Component are used to perform the operation (a + b = 6 + 5 = 11). The result is then printed to the console.

I hope this explanation clarifies the concept. If you have any questions or corrections, feel free to ask in the comment section.

Credits to Akshay Saini (Refer:[(https://youtu.be/iLWTnMzWtj4?si=WWMxDHM-v532vY7F)])

Top comments (0)