Understanding the JS memory heap and call stack

Hi, One important thing that we need to learn about Javascript code is how Javascript code is executed.

Every browser implement a Javascript engine and this engine read the Javascript code that we write and change that code into machine executable instructions for the browser. 

This image show the engines that this 3 common browsers use:

Let’s see the the Chrome browser engine that’s called V8, this engine have 2 important components, the memory heap and call stack:

The memory heap 

Were the memory allocation happens 

Let’s see basic example code:

// Assigning memory
const a = 1; // At this point we are using the memory heap

Sometimes we will come across the term “Memory leak” in Javascript programming, the memory heap have limited capacity, one example of memory leak is when we are declared a unlimited variables and we are not using that variables (unused memory) this will fill up the memory and finally the browser will be blocked (not be able to work).

So check the next example:

// Assigning memory
const a = 1; // At this point we are using the Memory heap
const b = 2;
const c = 3;
const d = 4;
const e = 5;
const f = 6;
const g = 7;
...
const x = 2000;

The call stack 

This is where our code is read and executed, this tell us where we are in the program.

console.log('1'); // Insert this line in the call stack and executed the line
console.log('2'); // Insert this line in the call stack and executed the line
console.log('3'); // Insert this line in the call stack and executed the line

Result:

This next example is a little more complex, take a look:

const myFunctionOne = () => {
  const myFunctionTwo = () => {
    console.log('Hi');
  }

  myFunctionTwo();
}

myFunctionOne();

Result:

So as we know the code will be loading from top to bottom of the JS file, so the call stack is filled in order of how the code is read:


console.log('Hi'); // 3 Inside myFunctionTwo find console.log
myFunctionTwo() // 2 Inside myFunctionOne find myFunctionTwo
myFunctionOne() // 1 Find myFunctionOne first
// CALL STACK

Then if we don’t have more code the code will be executed until the call stack will be empty.

// --- empty ---
// CALL STACK

 Javascript is single thread because by nature have one call stack, so you can do one thing at the time. So the call stack is First In Last Out, so goes executed whatever it’s in the top to down until the call stack is empty. 

By Criss.