Home >Web Front-end >JS Tutorial >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).
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);
In this example, a global execution context is created first, which consists of two components: the Memory Component (MC) and the Code Component (CC).
For functions, the entire function code is stored in memory. For variables, a special value, undefined, is stored initially.
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)])
The above is the detailed content of Is JavaScript synchronous or asynchronous, and is it single-threaded or multi-threaded? How is JavaScript code executed?. For more information, please follow other related articles on the PHP Chinese website!