Skip to content

Instantly share code, notes, and snippets.

@dillonforrest
Last active December 21, 2015 07:09
Show Gist options
  • Save dillonforrest/6269204 to your computer and use it in GitHub Desktop.
Save dillonforrest/6269204 to your computer and use it in GitHub Desktop.

Quoted from David Walsh on tech.pro

Source

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.

Dillon's take

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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment