Languages

JavaScript - difference between Array.length = 0 and Array = []?

0 points
Asked by:
Maison-Humphries
821

When it comes to clearing arrays, could you explain to me the difference between array.length = 0 and array = []?

Example:

// ONLINE-RUNNER:browser;

var array = ['a', 'b', 'c'];

array.length = 0;

console.log(JSON.stringify(array)); // []

vs

// ONLINE-RUNNER:browser;

var array = ['a', 'b', 'c'];

array = [];

console.log(JSON.stringify(array)); // []
1 answer
0 points
Answered by:
Maison-Humphries
821

array.length = 0 modifies the existing array. When you try to access it using a different variable, you will still get the modified array.

array = [] creates a new array and assigns a new reference to the new array to a variable. All of the other references are unchanged and still point to the original array.

Practical examples

1. Using array.length = 0

// ONLINE-RUNNER:browser;

var array = ['a', 'b', 'c'];

var x = array;

array.length = 0;

console.log(JSON.stringify(array));  // []
console.log(JSON.stringify(x));      // []

2. Using array = []

// ONLINE-RUNNER:browser;

var array = ['a', 'b', 'c'];

var x = array;

array = []; // creates new array, doesn't destroy other references

console.log(JSON.stringify(array)); // []
console.log(JSON.stringify(x));     // [ 'a', 'b', 'c' ]

 

See also

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join