Javascript Fundamentals — Call Stack and Memory Heap

Javascript is a single-threaded language

Allan Sendagi
6 min readFeb 7, 2020

The Javascript Engine does a lot of work for us. But the biggest thing is reading our code and executing it. The two main important things in this step are:

  1. We need a place to store and write information — data for our app(variables, objects, etc..)
  2. We need to keep track of what's happening to our code line by line.

This is where a call stack and a Memory heap comes in. We need the memory heap as a place to store and write information because at the end of the day all programs just read and write operations — that is to allocate, use and release memory.

The call stack helps us keep track of where we are in the code so that we can run the code in order.

The above code is saying please allocate memory for the number variable and have it point in our memory heap to the value 402.

The above code is saying please allocate memory for the number variable and have it point to the value 402 in our memory heap.

Here we are telling our engine to allocate memory for the pets object and its values. So anytime I call the pets object, it's going to point to a region in our memory heap that has the first and second key pointing to cat and dog.

We can store any type of data here. Data is in an unordered fashion. We use variables to point to different locations and the engine takes care of putting the data away in boxes for us.

The function above is going to be allocated memory so that anytime we call calculate(), it just looks it up in memory and runs this piece of code.

Every time we run a function we use a call stack. We can think of a call stack as a region in memory that operates in a first in last out mode. So here, it will add the calculate() function on top of the stack. And after we finish running it, it's going to remove it.

How does the call stack run this function?

If we go to the Google developer console and we enter this code in sources ->snippets -> new snippet, we can see what's happening.

This is the way it works in most languages — we have call stacks and memory heaps. Now, since the Javascript engine implementations vary, where variables are allocated is not 100% the same all the time.

Simple variables can be stored on the stack and complex data structures arrays, objects are stored in memory heap.

Just know that whatever is on top is what’s running.

Stack Overflow

Stack overflow happens when we call functions nested inside each, other over and over again. If we just keep adding functions to the stack without popping them off, we will have a stack overflow.

We can create a stack overflow very easily with recursion

stack overflow — inception calls itself over and over again

Garbage Collection and Memory Leaks

Before talking about memory leaks we have to understand the concept of garbage collection.

Javascript is a garbage-collected language. This means that if Javascript allocates memory, let's say within a function we create an object and that object gets stored somewhere in our memory heap, automatically when we finish calling that object and if we don't need that object anymore, and there is no reference to it in our program, Javascript is going to clean it up for us.

So, automatically Javascript frees this memory or to put literally — it collects our garbage.

Only the data that's useful to us remains. This is how we make sure we don't use up all the memory we have because as we know our memory is limited. This is how the language prevents memory leeks — when the memory gets too big until we reach our maximum size. just like with stack overflow.

But it will be foolish to assume that since we have a garbage collector to clear the memory for us, we shouldn't worry about memory management because there is no perfect system.

And although the garbage collector is smart enough to figure out what we need and what we don't need, there are times it makes mistakes where it won't free up the memory.

In low-level languages like C, you control garbage collection. You tell the engine to remove parts of the memory. It’s dangerous but it’s the reason why C programs are extremely fast and memory-efficient because you control garbage collection.

Garbage collection in Javascript uses the Mark and sweep algorithm; when a reference to a variable is removed, its deleted

Creating a memory Leak

The above code will fill up our memory until there is nothing left to use and our browser will eventually crash. Nothing is being popped off the stack.

3 common memory Leaks

Global Variables

var a =1;
var b=1;
var c=1;

Here if I just keep adding these variables to my memory, all our memory is will eventually get used up because we are just using up memory. Imagine if these were deeply nested objects, we will be using up a lot of memory.

Event Listeners

var element = document.getElementById(‘button’)
element.addeventListener(‘click’, onClick)

This is a common way to leak memory because you can just keep adding event listeners and you don't remove them when you no longer need them. They will stay in the background and before you know, you have a memory leak.

setInterval()

If we put objects inside a setInterval(), they will never be garbage collected unless we remove the setInterval itself.

setInterval( () => { //referencing objects })

So something to keep in mind is that memory is limited. When it comes to a call stack and memory Heap, those are two places is where javascript runs and stores memory. So we have to be careful not to have memory leaks or stack overflow if we are to have efficient code.

Javascript is a single-threaded Programming language(synchronous)

This means that only one set of instructions is executed at any single time. It’s not doing multiple things. The best way to check if a language is single-threaded is if it has one call stack. We push and pop functions off the stack one by one. And so Javascript is synchronous — only one thing can happen at a time.

Javascript run time>>>

--

--

Allan Sendagi

Technology will save Homo Sapiens from extinction. I document my journey learning these technologies https://www.linkedin.com/in/allansendagi/