Memory Management in JS

ShubhradeepShubhradeep
2 min read

When you call a function in JS like this:

function greet(name) {

let message = "Hello, " + name;

return message;

}

greet("Shubhradeep");

✅ name and message are stored in the call stack (temporary memory).

The reference to the heap string ("Hello, Shubhradeep") is returned to the caller.

✅ The full string "Hello, Shubhradeep" is created and stored in the heap (longer-term memory).

Return Statement: return message;

Depending on what you do with the return value, memory management changes.

🔄 Two Possible Scenarios After Return:

✅ Scenario A: Return value is USED

const result = greet("Shubhradeep");

result now holds a reference to the heap string.

So the string is still reachable → not cleaned up.

greet()’s stack frame is removed, but the heap string stays alive because result points to it.

❌ Scenario B: Return value is IGNORED

greet("Shubhradeep"); // no variable holds the return value

Once greet() returns:

Its execution context is popped off the call stack

name and message disappear (stack is gone)

The heap string "Hello, Shubhradeep" is now unreachable

Garbage Collection Happens

JS has a built-in Garbage Collector (GC) - it automatically frees memory that is no longer referenced.

Behind the scenes:

JS engine keeps track of what’s still reachable (i.e. has a variable pointing to it).

If no reference points to the heap string ("Hello, Shubhradeep"), it is marked as garbage.

On the next GC cycle, it’s deleted from memory to free space.

Summary -

Stack stores local variables + references.

Heap stores longer-lived objects/strings.

After function returns:

If result is used → heap string survives

If not used → heap string is garbage-collected

You don’t manage memory manually in JS - the engine does it for you.

0
Subscribe to my newsletter

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

Written by

Shubhradeep
Shubhradeep

Full-Stack Developer with 1.5 years of experience building scalable, secure web applications using React, Node.js, and PostgreSQL. Skilled in REST APIs, backend architecture, authentication (JWT/JWE), and modern frontend tools. Proven ability to enhance system efficiency, SEO, and user experience.