The flaw of deep copy with #jquery and an empty array

Reading Time: 1 minutes

When you’re working with #javascript and arrays of objects you’ll probably want to copy an array by value instead of byref sooner or later.

You can clone an array of objects with Jquery (including objects containing objects themselves, called nested objects) using the following syntax:

var clonedArrayOfObjects = jQuery.extend(true, {}, originalArrayWithObjects);

The true parameter indicates that you want to deep copy the original array’s objects.

I was concatenating locally stored objects (yes, in the localstorage) and objects retrieved from an API’s JSON result into a viewObjects array that I’d show to the user. After implementing the .extend functionality my setup didn’t work. I was like:


Spending quite some time debugging, i started noticing my issue was only occurring when the originalArrayWithObjects was an empty array.

Then it finally hit me: Using jQuery.extend on an empty array object will return an empty object, not – as I expected – an empty array. Concatenating its result into the view array therefore led to the viewObjects array becoming an object instead of an array and my view logic crumbled and burned like Pompeij on its last day.

One more mystery on this planet was solved and I lived to see another day.