how JS exactly works

let's run a simple code

let a = 10;
let b = 20;
function sum(a, b) {
  let sum = a + b;
  console.log (sum);
}
sum(a, b);

we all know the output. sum function will console 30.

but how this above code get executed in background.

Now inside JavaScript whenever a code is executed an execution context is created along with a call stack.

Screenshot (108) (1).png

Screenshot (105) (1).png

  • First, the Memory part also called Variable Environment. In this component variable or function are stored in a key value pair.

  • Second, the code component also called Thread of Execution. In this component code is executed line by line.

JavaScript codes get parsed two times . First time when it goes through every line of code it takes all the variable and provides it with a special keyword called undefined. And function are stored not with the keyword undefined rather stored with the the complete actual code that’s written.

Screenshot (104).png

Second time when it parses it executes code line by line and provide the desire value to the variable. Function do not get executed by this component until and unless the function are invoked explicitly.

Screenshot (103).png

Function works differently in JavaScript than any other programming language.

In case of Function whenever function is called a new local execution context is created which follows the exact same procedure as the global execution context. Inside this execution context parameters also gets memory. Once the function code get executed this local execution context get deleted. And when the whole JavaScript code gets executed the global execution context gets deleted.

Screenshot (107) (1).png

After executing all the code

JavaScript memory management runs a process called garbage collection that reclaim memory that is no longer needed or referenced by the program.

JavaScript developers generally don't need to explicitly manage memory allocation and de allocation, thanks to automatic garbage collection.

Mark-and-sweep algorithm is one the famous algorithm used for garbage collection.