Combining and Copying Arrays

Grade 7, page 10 of 14. A one-minute read.

To combine arrays, you can use concat, or the modern spread syntax ..., which "spreads out" all the items of an array:

JavaScript
const fruits = ["mango", "pawpaw"];
const veggies = ["okra", "garden egg"];

const shopping1 = fruits.concat(veggies);
const shopping2 = [...fruits, ...veggies];
const shopping3 = ["bread", ...fruits, "eggs"];

console.log(shopping1);
console.log(shopping2);
console.log(shopping3);

It prints

[ 'mango', 'pawpaw', 'okra', 'garden egg' ]
[ 'mango', 'pawpaw', 'okra', 'garden egg' ]
[ 'bread', 'mango', 'pawpaw', 'eggs' ]

Think of ...fruits as tipping the fruits out of their bag and onto the table. The three dots are a powerful little tool, and we'll see more of them in Grade 13.

Arrays are shared, not copied

Here's something that surprises everyone. Look at this:

JavaScript
const original = [1, 2, 3];
const copy = original;

copy.push(4);

console.log(original);
console.log(copy);

It prints

[ 1, 2, 3, 4 ]
[ 1, 2, 3, 4 ]

We only pushed to copy... but original changed too! What?!

When you write const copy = original, you're not making a new array. You're making a second label that points to the same array. It's like giving your friend a second key to your house. They're not getting a new house. If they paint the kitchen pink, it's your kitchen that's pink.

To make a real, separate copy, use spread:

JavaScript
const original = [1, 2, 3];
const realCopy = [...original];

realCopy.push(4);

console.log(original);
console.log(realCopy);

It prints

[ 1, 2, 3 ]
[ 1, 2, 3, 4 ]

Now they're two separate arrays. This idea (that arrays and objects are shared when you assign them) is called reference behavior, and it's important enough that we'll draw a picture of it in Grade 8.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning