Where are JavaScript variables stored?

Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.

JavaScript variables are stored in different memory locations depending on their type and scope. Understanding where variables are stored helps optimize performance and avoid memory leaks.

Stack vs Heap Memory

JavaScript uses two main memory areas for storing variables:

  • Stack Memory: Stores primitive values (numbers, strings, booleans) and function call information
  • Heap Memory: Stores objects, arrays, and functions

Example: Primitive vs Reference Types

// Primitives stored in stack
let num = 42;
let str = "Hello";
let bool = true;

console.log("Primitive values:", num, str, bool);

// Objects stored in heap (variable holds reference)
let obj = {name: "John", age: 30};
let arr = [1, 2, 3];

console.log("Reference types:", obj, arr);
Primitive values: 42 Hello true
Reference types: { name: 'John', age: 30 } [ 1, 2, 3 ]

Variable Storage by Scope

// Global variables - stored in global memory space
var globalVar = "I'm global";

function exampleFunction() {
    // Local variables - stored in function's execution context
    let localVar = "I'm local";
    
    console.log("Global:", globalVar);
    console.log("Local:", localVar);
}

exampleFunction();
Global: I'm global
Local: I'm local

Memory Storage Comparison

Variable Type Storage Location Access Speed
Primitives (number, string, boolean) Stack Memory Fast
Objects, Arrays, Functions Heap Memory Slower
Global Variables Global Memory Space Always accessible

Browser Storage Options

Beyond memory, JavaScript can store data persistently:

  • localStorage: Permanent storage until manually cleared
  • sessionStorage: Temporary storage for the session
  • Cookies: Small data pieces sent with HTTP requests
<html>
<body>
<script>
// Browser storage examples
localStorage.setItem('username', 'John');
sessionStorage.setItem('sessionId', '12345');

console.log('localStorage:', localStorage.getItem('username'));
console.log('sessionStorage:', sessionStorage.getItem('sessionId'));
</script>
</body>
</html>

Conclusion

JavaScript variables are stored in stack memory for primitives and heap memory for objects. Understanding these storage mechanisms helps write more efficient code and manage memory properly.

Updated on: 2026-03-15T21:35:13+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements