How Javascript Works (Overview)!!!

How Javascript Works (Overview)!!!

·

3 min read

"Javascript is synchronous single-threaded language". JS is single-threaded which means only one statement is executed at a time. Synchronous execution usually refers to code executing in sequence. In sync programming, the program is executed line by line, one line at a time.

Whenever we create a javascript program, a global execution context is created. Everything in JavaScript happens inside an "Execution Context”. Execution Context can be assumed as a container or a body where JavaScript code is executed.

Execution Context has two components:

a) Variable Environment (a.k.a Memory)

All the variables and functions are stored in Variable environment in the form of key-value pairs. For example,

var firstVariable = 100;          //line 1
function test() {                     //line 2
var secondVariable = 200;   //line 3
console.log(firstVariable + " " + secondVariable);     //line 4
}
test();          //line5

In the above code snippet, the variables firstVariable and secondVariable will be stored with their values (i.e. 100 and 200) and the function test will be stored with all its code as it is(i.e line3 and line 4).

b) Thread of Execution (a.k.a Code)

In the Thread of execution, the JavaScript code is executed line by line.

var firstVariable = 100; //line 1
function test() { //line 2
var secondVariable = 200; //line 3
console.log(firstVariable + " " + secondVariable); //line 4
}
test();     //line5

On every function call in Javascript, a new execution context is created and added to the execution stack. As in line5 when the function test is invoked, a new execution context is created and the program execution moves forward. After program execution is finished, the execution context is popped from the execution stack.

This was just an overview of how javascript works. I hope you would have found this article beneficial. Thank you for reading through this article.