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 to allocate memory to an object whose length is set to 0 - JavaScript?
In JavaScript, you can manipulate array length to clear memory and allocate new slots. When you set an array's length to 0, it clears all elements. Setting length to a larger value allocates empty slots.
Understanding Array Length Property
The length property controls how many elements an array can hold. Setting it to 0 removes all elements, while setting it to a larger number creates empty slots filled with undefined.
var arrayObject = [
"John",
"David",
"Mike"
];
console.log("Original array:", arrayObject);
console.log("Original length:", arrayObject.length);
Original array: [ 'John', 'David', 'Mike' ] Original length: 3
Clearing Memory by Setting Length to 0
Setting length = 0 removes all elements and frees the memory used by the array:
var arrayObject = ["John", "David", "Mike"];
// Clear all elements
arrayObject.length = 0;
console.log("After clearing:", arrayObject);
console.log("New length:", arrayObject.length);
After clearing: [] New length: 0
Allocating Memory by Increasing Length
Setting length to a larger value allocates new slots filled with undefined:
var arrayObject = [];
arrayObject.length = 5;
console.log("Array after allocation:", arrayObject);
console.log("Length:", arrayObject.length);
// Check each element
for (var i = 0; i
Array after allocation: [ ]
Length: 5
Index 0: undefined
Index 1: undefined
Index 2: undefined
Index 3: undefined
Index 4: undefined
Complete Example
Here's a complete demonstration of clearing and reallocating memory:
var arrayObject = ["John", "David", "Mike"];
console.log("Step 1 - Original:", arrayObject);
// Clear memory
arrayObject.length = 0;
console.log("Step 2 - After clearing:", arrayObject);
// Allocate new memory
arrayObject.length = 4;
console.log("Step 3 - After allocation:", arrayObject);
// Fill with new data
arrayObject[0] = "Alice";
arrayObject[1] = "Bob";
console.log("Step 4 - After adding data:", arrayObject);
Step 1 - Original: [ 'John', 'David', 'Mike' ]
Step 2 - After clearing: []
Step 3 - After allocation: [ ]
Step 4 - After adding data: [ 'Alice', 'Bob', ]
Key Points
- Setting
array.length = 0removes all elements and clears memory - Setting
array.length = n(where n > current length) creates empty slots - Empty slots contain
undefinedvalues - This approach modifies the original array rather than creating a new one
Conclusion
Manipulating the length property provides direct control over array memory allocation. Use length = 0 to clear arrays and length = n to pre-allocate slots for better performance when you know the expected size.
