Introduction
In this short blog post, we'll understand the difference between the two ways of emptying an object in JavaScript i.e. by assigning an empty array and setting the length property of an array to zero.
- // set length property to zero.
- myArray.length = 0;
- // assign empty array
- myArray = [];
To know more about the length property, visit here.
Assigning an empty array points the existing variable to a new reference instead of modifying the existing reference.
- let myArray = [1, 2, 3, 4, 5];
- let myArray2 = myArray;
- myArray = [];
- console.log(myArray2);
- // Output: [1, 2, 3, 4, 5]
- let myArray = [1, 2, 3, 4, 5];
- let myArray2 = myArray;
- myArray.length = 0;
- console.log(myArray2);
- // Output: []

Join the conversation! Your thoughts help the community grow.