EN
JavaScript - difference between Array.length = 0 and Array = []?
1
answers
0
points
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
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