Real Ultimate Programming

The Home for People Who Like to Flip Out and Write Code

JavaScript Idioms - Copying an Array

Ever see a block of JavaScript that looks like this?

var myArray = [];
for (var i = 0; i < source.length; i++) {
    myArray[i] = source[i];
}

That’s the popular way to copy the elements of one array (note the lack of capitalization) into a new Array (note the capitalization - we’ll get to this in a minute). I wasn’t really a fan, at first, but it’s almost as pervasive as

while(*dst++ = *src++);

in C, so eventually I decided to stop worrying and love the bomb. Basically, JavaScript will automatically grow your Array for you, so you can dispense with all the sizing you might expect when using something called an Array.

Now for the notes you took on capitalization. Not everything that acts like an array in JavaScript is actually an Array. One example is the arguments property available to Functions. If you happen to need the stuff in arguments as an actual Array (because you want to use it as a key for a map/dictionary/hash, let’s say), you will find yourself writing some code like that above. Just remember that sometimes stuff is “Array-like” without actually being an Array, because it can really bite you if you’re not careful.

Back to flipping out…