What happens when length of object is set to 0 - JavaScript?


Let’s say the following is our array object −

var arrayObject =
   [
      "John",
      "David",
      "Mike"
   ]

You can use length property to set the length to 0 and clear memory

The syntax is as follows to clear memory −

yourArrayObjectName.length=0; // To clear memory
yourArrayObjectName.length=4; // To allocate memory

Output

This will produce the following output on console −

var arrayObject =
   [
      "John",
      "David",
      "Mike"
   ]
arrayObject.length = 0;
console.log(arrayObject);
arrayObject.length = 5;
for (var i = 0; i < arrayObject.length; i++)
   console.log(arrayObject[i]);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo277.js.

Output

This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo277.js
[]
undefined
undefined
undefined
undefined
undefined

Updated on: 09-Nov-2020

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements