Duplicating arrays in JavaScript

Many of those who write JavaScript do not come from programming backgrounds (while I've written plenty of PHP, Python, and JavaScript, I don't have much experience with "real" programming languages*). As a result, a significant portion of JavaScript coders do not think of variables as pointers to memory addresses. This leads to confusion in cases such as this:

var fruits = ['orange', 'lime'];
var colours = fruits; // naïve attempt to duplicate array
colours.append('yellow');

One might be surprised to learn that fruits now contains not just "orange" and "lime" but also "yellow". Oops! Here's how it went wrong:

var fruits = ['orange', 'lime']; // fruits points to array containing "orange" and "lime"
var colours = fruits; // colours now points to that same array!

How, then, does one create a copy of the original array? Slice!

var colours = fruits.slice();

Leave a reply…

accepted tags
  • <a href="" title=""></a>
  • <abbr title=""></abbr>
  • <acronym title=""></acronym>
  • <blockquote cite=""></blockquote>
  • <cite></cite>
  • <code></code>
  • <del datetime=""></del>
  • <em></em>
  • <q cite=""></q>
  • <strike></strike>
  • <strong></strong>