Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How are variables allocated memory in JavaScript?
JavaScript handling of the variable is different from other programming languages C, C++., Java, etc. Variables in JavaScript 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.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows.
<script> var rank; var points; </script>
Storing a value in a variable is called variable initialization. You can do variable initialization at the time of variable creation or at a later point in time when you need that variable.
<script>
var rank = 1;
var points;
points = 100;
console.log("Rank:", rank);
console.log("Points:", points);
</script>
Rank: 1 Points: 100
Memory Allocation in JavaScript
JavaScript automatically handles memory allocation for variables. Unlike languages like C or C++, you don't need to explicitly allocate or deallocate memory.
Primitive vs Reference Types
JavaScript allocates memory differently based on the data type:
<script>
// Primitive types - stored in stack memory
var num = 42;
var str = "Hello";
var bool = true;
// Reference types - stored in heap memory
var arr = [1, 2, 3];
var obj = {name: "John", age: 25};
console.log("Primitive:", num, str, bool);
console.log("Reference:", arr, obj);
</script>
Primitive: 42 Hello true
Reference: [1, 2, 3] {name: "John", age: 25}
Variable Hoisting
JavaScript moves variable declarations to the top of their scope during compilation:
<script>
console.log("Value before declaration:", x);
var x = 5;
console.log("Value after declaration:", x);
</script>
Value before declaration: undefined Value after declaration: 5
Modern Variable Declarations
ES6 introduced let and const which have different memory behavior:
<script>
let mutableVar = "Can change";
const immutableVar = "Cannot change";
mutableVar = "Changed!";
console.log("Let variable:", mutableVar);
console.log("Const variable:", immutableVar);
</script>
Let variable: Changed! Const variable: Cannot change
Conclusion
JavaScript automatically manages memory allocation for variables. Primitive types are stored in stack memory, while objects and arrays are stored in heap memory with references in the stack.
