🧠 JavaScript Memory Management: Understanding the Basics with Code Examples

Zia Ur RehmanZia Ur Rehman
3 min read

JavaScript, as a high-level programming language, manages memory automatically. However, understanding how memory is allocated, how garbage collection works, and how reference types behave is key to writing efficient and bug-free code.


🔍 Primitive vs Reference Types

🔸 Primitive Types

Primitive types are basic, immutable data types:

  • Number

  • String

  • Boolean

  • Undefined

  • Null

  • Symbol

  • BigInt

🧪 Example:

javascriptCopyEditlet a = 10;
let b = a;
b = 20;
console.log(a); // 10

Here, b gets a copy of a, so changing b doesn’t affect a.

🔸 Reference Types

These include:

  • Object

  • Array

  • Function

They are stored by reference, not by value.

🧪 Example:

javascriptCopyEditlet obj1 = { name: "Alice" };
let obj2 = obj1;
obj2.name = "Bob";

console.log(obj1.name); // "Bob"

Both variables refer to the same object in memory.


🧰 JavaScript Memory Allocation

JavaScript handles memory in two main areas:

  • Stack: for storing primitive values (simple and fast).

  • Heap: for storing reference types like objects (more complex).

🔧 How it works:

javascriptCopyEditlet age = 30; // Stored in stack
let person = { name: "John" }; // Object in heap, reference in stack

🧹 Garbage Collection

JavaScript uses automatic garbage collection to free memory.

✨ Two Main Strategies:

  1. Mark-and-Sweep
    Marks all objects still in use; removes the rest.

  2. Reference Counting
    Frees objects with zero references.

🧠 Analogy: Like a janitor cleaning unused desks in a classroom.


📋 Shallow vs Deep Copy

Shallow Copy

Only the top-level properties are copied.

javascriptCopyEditlet original = { name: "Anna", meta: { age: 25 } };
let shallow = { ...original };
shallow.meta.age = 30;

console.log(original.meta.age); // 30

Deep Copy

All levels of the object are copied.

javascriptCopyEditlet deep = JSON.parse(JSON.stringify(original));
deep.meta.age = 40;

console.log(original.meta.age); // 30

❗️Caution: JSON.stringify doesn’t work with functions or special values.


⚠️ Common Mistakes Leading to Memory Leaks

  1. Uncleared Timers/Intervals
javascriptCopyEditlet timer = setInterval(() => console.log("Still running..."), 1000);
// Not cleared
  1. Undisposed Event Listeners
javascriptCopyEditfunction setup() {
  window.addEventListener('resize', () => console.log("resized"));
}
// No removal with removeEventListener
  1. Lingering References
javascriptCopyEditlet cache = {};
function loadData() {
  let data = { largeData: new Array(10000).fill("data") };
  cache["data"] = data;
}
// 'data' is never released

🧠 Tips for Writing Memory-Efficient JavaScript

✅ Use local variables where possible
✅ Release references you don’t need
✅ Avoid large global variables
✅ Use WeakMap or WeakSet when you don’t want strong references

🧪 Example: Using WeakMap

javascriptCopyEditlet wm = new WeakMap();
let obj = {};

wm.set(obj, "some data");

obj = null; // Automatically removed from WeakMap if no other references

🙌 Conclusion

Understanding how JavaScript manages memory can greatly improve performance and reduce bugs. By being mindful of how you handle references, use memory, and write clean-up logic, you can avoid memory leaks and write faster, smarter code.

0
Subscribe to my newsletter

Read articles from Zia Ur Rehman directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Zia Ur Rehman
Zia Ur Rehman

🧐 Are you facing challenges like slow website performance, poor user experience, cross-browser issues, and difficulty integrating with back-end systems, all while trying to manage business growth without a streamlined digital solution? 🤔 Are you struggling to reach a wider audience, improve customer engagement, and stay competitive without a web app, while dealing with inefficient operations, limited scalability, and missed revenue opportunities? 🚀 Build a web app to expand reach, improve engagement, and streamline operations for growth. ⚙️ Optimize performance, enhance user experience, and integrate systems with a smooth, scalable solution. 👨‍💻 I am Zia-Ur-Rehman a MERN Developer with experience in building scalable and high-performing web applications that solve buisness Problems. I worked with the startup to Help their clients by developing highly scalable webApps to make their global buisness mangable with one click across globe. ✅ Frontend Development to create responsive, user-friendly interfaces that solve the problems of your audience. ✅ Figma to Next.js Functional App transforming your designs into interactive, high-performance Web apps. ✅ Web App Development to expand your reach and improve customer engagement.✅ Performance Optimization for faster load times and seamless user experience.✅ Cross-Browser Compatibility ensuring your app works perfectly everywhere.✅ Backend Integration to streamline operations and boost business efficiency.If you have an idea that will capture market share, why are you waiting? 🚀 DM me today or email me (emailtozia0@gmail.com) and get started!