JavaScript Fundamentals: Memory Life cycle, Heap, Stack and Call Stack

JavaScript Fundamentals: Memory Life cycle, Heap, Stack and Call Stack

In this JavaScript fundamentals tutorial, you'll learn about memory life cycle, heap, stack and call stack in JavaScript. Learn a bit about how JavaScript works and become a better developer.

Learn about memory life cycle, heap, stack and call stack in JavaScript. Learn a bit about how JavaScript works and become a better developer.

Table of Contents

  • A quick introduction
  • Memory life cycle
  • The stack and memory heap
    • The stack
    • The memory heap
  • Stack, heap and references
    • Copying objects and primitives
  • The call stack
  • Conclusion

There are topics in JavaScript you as a developer may not know. Knowing about these topics can help you write better code. Memory life cycle, heap, stack and call stack are some of them. In this tutorial, you will learn about these topics and a bit about how JavaScript works.

A quick introduction

JavaScript is a very forgiving programming language. It allows you to do a lot, in many ways. It also does a lot of work for you. Memory management is one of these things. Ask yourself: how many times did you have to think about allocating memory for your variables or functions?

How many times did you have to think about releasing that memory when you no longer needed those variables or functions? Chances are not even once. The same applies to knowing how is heap, stack and call stack work, or what it even is. And yet, you can still work with JavaScript. You can still write code that works every day.

These things are not necessary for you to know. Nor are they required. However, knowing about them and how they work can help you understand how JavaScript works. This, in turn, can help you write better code and become a better JavaScript.

Memory life cycle

Let’s start with the easiest part. What is a memory life cycle, what it is about and how it works in JavaScript? Memory life cycle refers to how a programming language works with memory. Regardless of the language, memory life cycle is almost always the same. It is composed of three steps.

The first step is memory allocation. When you assign a variable or create a function or object some amount of memory has to be allocated for it. The second step is memory use. When you work with data in your code, read or write, you are using memory. Reading from variables or changing values is reading from, and write to, memory.

The third step is memory release. When you no longer use some function or object, that memory is can be released. Once it is released it can be used again. This is the memory life cycle in a nutshell. The nice thing on JavaScript is that it makes these three steps for you.

JavaScript allocates memory as you need and want. It makes it easier for you to work with that allocated memory. Lastly, it also does the heaving lifting and cleans up all the mess. It uses garbage collection to continuously check memory and release it when it is no longer in use. The result?

As a JavaScript developer, you don’t have to worry about allocating memory to your variables or functions. You also don’t have to worry about selecting correct memory address before reading from it. And, you don’t have to worry about releasing the memory you used somewhere in the past.

The stack and memory heap

Now you know about the steps of memory life cycle. You know about memory allocation, use and release. One question you may ask is where are those variables, functions and objects actually stored? The answer is: it depends. JavaScript doesn’t store all these things at the same place.

What JavaScript does instead is it uses two places. These places are stack and memory heap. Which of these places will be used depends on what you are currently working with.

The stack

The stack is a place that JavaScript uses to store only static data. This includes primitive data types values. For example, numbers, strings, booleans, undefined and null. These static data also include references. These references point to objects and functions you’ve created.

These data have one thing in common. The size of these data is fixed and JavaScript knows this size at compile time. This also means that JavaScript knows how much memory it should allocate, and allocates that amount. This type of memory allocation is called “static memory allocation”. It happens right before the code is executed.

There is one important thing about static data and memory. There is a limit to how large these primitive values can be. This is also true for the stack itself. That too has limits. How high these limits are depends on specific browser and engine.

// Declare and assign some variables
// and assign them primitive data types
// All these variables are stored in stack
const firstName = 'Jill'
const lastName = 'Stuart'
const age = 23
const selfEmployed = true
const dateOfMarriage = null

// The stack after declaring
// and assigning those variables:
///           Stack           ///
/////////////////////////////////
///   dateOfMarriage = null   ///
///   selfEmployed = true     ///
///   age = 23                ///
///   lastName = 'Stuart'     ///
///   firstName = 'Jill'      ///
/////////////////////////////////

The memory heap

The second place where JavaScript can store data is memory heap. This storage is more dynamic. When it comes to memory heap, JavaScript doesn’t allocate fixed amount of memory. Instead, it allocates memory as needed at the moment. This type of memory allocation is called “dynamic memory allocation”.

Which data are stored in memory heap? While the stack is a place where JavaScript stores static data, memory heap is a place where JavaScript stores objects and functions. So, remember, when you create with primitives, you are working with static data. JavaScript stores these static data in the stack.

These data has always fixed allocated memory. When, on the other hand, you create objects or functions JavaScript stores them in memory heap. Allocated memory for these is not fixed. It is allocated dynamically as necessary.

// Declare a variable and assign it an object
const terryP = {
  firstName: 'Terry',
  lastName: 'Pratchett',
  profession: 'author'
}

function introduceTerry() {
  return `Hi, my name is ${terryP.firstName}.`
}

const series = ['Discworld', 'Johnny Maxwell', 'Long Earth']

const isDone = true

///                  Stack                     ///
//////////////////////////////////////////////////
///   isDone = true                            ///
///   introduceTerry (reference to function)   ///
///   terryP (reference to "terryP" object)    ///
///   series (reference to "series" array)     ///
//////////////////////////////////////////////////

///                    Memory heap                  ///
///////////////////////////////////////////////////////
///  {                                              ///
///    firstName: 'Terry',                          ///
///    lastName: 'Pratchett',                       ///
///    profession: 'author'                         ///
///  }                                              ///
///  function introduceTerry() {                    ///
///    return `Hi, my name is ${terryP.firstName}.` ///
/// }                                               ///
///  ['Discworld', 'Johnny Maxwell', 'Long Earth']  ///
///////////////////////////////////////////////////////

// NOTE:
// the "terryP" in stack points
// to the "terryP" object in memory heap
// the "introduceTerry" in stack points
// to introduceTerry() function in memory heap
// the "series" in stack points
// to the "series" array in memory heap
// arrays are objects in JavaScript

Stack, heap and references

When you create a variable and assign it a primitive value, it will be stored in stack. Something different happens when you try the same, but with an object. If you declare a variable and assign it an object, two things will happen. First, JavaScript will allocate memory in stack for that variable.

When it comes to the object itself, JavaScript will store it in the memory heap. That variable that exists in the stack will only point to this object in memory heap. That variable will be a reference to this object. You can think of references as shortcuts, or aliases, for existing things.

These references are not those things themselves. They are only links to those “real” things. You can use those links to access those things they reference (they are linked to) and manipulate with them.

// Declare variable and assign it an object
// The "cat" variable will be stored in stack
// It will hold the reference to the "cat" object
const cat = {
  name: 'Kitty'
  breed: 'Abyssinian'
}

// The "cat" object itself will be stored in memory heap:
///       Memory heap         ///
/////////////////////////////////
///  {                        ///
///    name: 'Kitty',         ///
///    breed: 'Abyssinian'    ///
///  }                        ///
/////////////////////////////////

javascript programming web-development developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

What Garbage Collection in JavaScript Is and How It Works

JavaScript values are allocated when things are created (objects, Strings, etc.) and freed automatically when they are no longer used. This process is called Garbage collection.

What Javascript Spread Operator is, How It Works and How to Use It

JavaScript spread operator is one of the more popular features that were introduced in ES6. This tutorial will help you understand it. You will learn what spread operator is and how it works. You will also learn how to use it to copy and merge arrays and object literals, insert data and more.

Top 10 Web Development Trends in 2020 | Web Development Skills

Top 10 Web Development Trends in 2020 will provide you with a detailed list of the trends which are currently being noticed. Upskilling to these trends will help you in landing onto better jobs in 2020-2021.