There's not a developer out there that hasn't been bitten by JavaScript's pass-objects-by-reference nature. Oftentimes developers will attempt to empty an array but mistakenly create a new one instead:
var myArray = yourArray = [1, 2, 3];
// :(
myArray = []; // "yourArray" is still [1, 2, 3]
// The right way, keeping reference
myArray.length = 0; // "yourArray" and "myArray" both []
What these developers probably realize is that objects are passed by reference, so while setting myArray to [] does create a new array, other references stay the same! Big mistake! Use array truncation instead.
I was amazed that array.length = 0;
would turn our array into an empty array. My intuition told me that length
would just not reflect the correct length of the array anymore. Try it out in your favorite js repl. Awesome!
To make this more practical in a production codebase, I'd suggest wrapping it all in a function:
function empty(array) {
return array.length = 0;
}