DZone
Web Dev Zone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Web Dev Zone > A Simple Guide to Heaps, Stacks, References, and Values in JavaScript

A Simple Guide to Heaps, Stacks, References, and Values in JavaScript

Let's look at how memory allocation works in JavaScript - including heaps, stacks, references, and values.

Johnny Simpson user avatar by
Johnny Simpson
CORE ·
May. 11, 22 · Web Dev Zone · Tutorial
Like (2)
Save
Tweet
3.57K Views

Join the DZone community and get the full member experience.

Join For Free

A common concept in software engineering, in general, is the idea of reference versus value. JavaScript has an interesting way of storing variables, objects, and functions, and misunderstanding this can lead to confusion further down the road. Developers need to know how these concepts work since it is fundamental to JavaScript. This article will cover how JavaScript manages values and references, which will pay dividends when working on complicated applications and websites.

Memory Storage in JavaScript

To understand what we mean when we say JavaScript stores values and references, we need to understand where JavaScript stores them. There are two places JavaScript stores this data:

  • The stack is scratch space for the current Javascript thread. Since JavaScript is usually only single-threaded, there is usually one stack. The stack is also limited in size, which is why numbers in JavaScript can only be so big.
  • The heap is a dynamic memory store at an application level. Accessing and retrieving data from the heap is a little more complicated, but the datastore is dynamic - meaning it will expand if it needs to and is not limited.

When something is stored in the stack, it is stored by value. When something is stored in the heap, it is stored by reference.

Stack Storage

JavaScript stores regular primitive types, like number, string, boolean, null, undefined and bigint in the stack. As you define variables in your code, they are added to the top of the stack:

 
let myVar = 15;
let myName = 'Johnny';
let someOtherVar = false;
let check = null;


Stack:
An example of the stack in Javascript

This means if we redefine a variable in JavaScript, it becomes an entirely new value. For example:

 
let myNumber = 5;
let newNumber = myNumber;

++newNumber;

// Returns 5, 6
console.log(myNumber, newNumber);


Stack:
An example of the Stack in Javascript

Since JavaScript creates a new value for anything stored in the stack, even though we referred to newNumber being the same as myNumber, they do not refer to the same thing. These two variables become independent of each other, and altering one will not alter the other.

Heap Storage

If you are defining something which is not a primitive type and is instead an object, it is stored in the heap. For example, in JavaScript, functions, and arrays also fall into the "object" category.

Instead of being easily accessible in the stack, heap definitions need to be defined with a little bit more thought. Everything stored in the heap is instead given a reference.

Example

Let's say we define both an object and a function in JavaScript:

 
let myObject = { name: "Hello" };
let myFunction = function() {
    return "Hello World";
}


As shown below, a new reference is made for each myObject and myFunction, with references #000 and #001, respectively. That reference is the place in memory where they are stored.

Heap Storage
An example of heap storage in Javascript

The main difference with heap storage, when compared to the stack, is that if we reference an object again, the reference remains the same. That means if we try to create a new version of myObject, it will instead keep the same reference:

let myObject = { name: "Hello" };
let newObject = myObject;
newObject.name = "Goodbye";

// Returns { name: "Goodbye" }, { name: "Goodbye" }
console.log(myObject, newObject);


When we change one, both change - which is the opposite of when we stored data in the stack.

Heap Storage
An example of heap storage in Javascript

Equivalence in Value and References

Since JavaScript stores the definition of objects as a reference, it can be a little confusing. For values, we can easily compare if two things are equal:

 
let a = 5;
let b = 5;

// Returns true
console.log(a === b);


We can easily compare these two because they are both values. For references, though, it's a different story. Comparing two objects compares them by reference. Even if their value is the same, they are not equal as their references are different:

 
let a = { name: "Hello" };
let b = { name: "Hello" };

// Returns false
console.log(a === b);


Conclusion

References and values have real implications for your code - especially when making comparisons, understanding the difference is critical. Not only that, but the stack is much less expensive performance-wise than the heap, and it's very easy to make too many stack entries if you aren't aware of how it works.

If you know how JavaScript handles heap and stack storage, you can start to optimize your application's performance to work best within these rules. I hope you've enjoyed this quick guide on how references and values work in JavaScript. If you want more JavaScript content, it can be found here.

JavaScript

Published at DZone with permission of Johnny Simpson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How to Hash, Salt, and Verify Passwords in NodeJS, Python, Golang, and Java
  • Data Visualization of Healthcare Expenses by Country Using Web Scraping in Python
  • Modernizing Testing With Data Pipelines
  • Servlets Listeners Introduction and Examples

Comments

Web Dev Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo