Merge arrays with concat, spread or push in JavaScript
Beginner · 3 min read
Joining two lists into one is everyday work: this page of results plus the next, the items in a cart plus a new order, morning stops plus evening stops. JavaScript gives you three common ways to do it: concat, the spread syntax, and push. They don't all behave the same, and one small difference, push(b) against push(...b), catches a lot of beginners.
In this tutorial you will combine two arrays all three ways, see which ones change their inputs, and find out exactly what push gives back. You should know what an array is.
New array, or the same one?
Some methods build a new array and leave their inputs alone. Others change the array you call them on, which is called mutating it. concat and spread build new arrays. push mutates. Keep that split in mind as you read each step.
Spread in a function call
You may have seen three dots inside square brackets. They also work inside a function call, where they turn an array into separate arguments:
const nums = [3, 9, 4];
console.log(Math.max(...nums)); // 9: the same as Math.max(3, 9, 4)
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
17 Joining arrays: concat, spread and push
easyCombine two arrays three ways. Then find the difference between push(other) and push(...other).
Stuck? Three hints, smallest first
- 1.
concatand spread both return a new array;pushchanges one in place. - 2.
pushreturns the new length, not the array, so it does not chain. - 3.
concatunwraps array arguments one level deep, but not two.
Step 1: concat
a.concat(b) returns a new array: the items of a, then the items of b.
const a = [1, 2];
const b = [3, 4];
const joined = a.concat(b);
console.log(joined); // [ 1, 2, 3, 4 ]
console.log(a, b); // [ 1, 2 ] [ 3, 4 ]
Both inputs are unchanged.
Step 2: spread
Spread each array inside a new pair of square brackets.
const a = [1, 2];
const b = [3, 4];
const spread = [...a, ...b];
console.log(spread); // [ 1, 2, 3, 4 ]
Same result, and again nothing is changed. Spread is handy when you want to add loose values too, like [0, ...a, ...b, 5].
Step 3: push(...b)
push adds items to the end of an existing array. Spreading b into the call adds each of its items.
const b = [3, 4];
const pushedSpread = [1];
pushedSpread.push(...b);
console.log(pushedSpread); // [ 1, 3, 4 ]
This is the one to use when you really do want to grow the array you already have.
Step 4: the wrong turn, push(b)
Forget the three dots and something different happens:
const b = [3, 4];
const pushedWhole = [1];
const newLength = pushedWhole.push(b);
console.log(pushedWhole); // [ 1, [ 3, 4 ] ]
console.log(newLength); // 2
push(b) adds one item, and that item is the whole array b. You now have an array with an array inside it, and a length of 2, not 3.
Look at newLength too. push returns the new length of the array, not the array. So const xs = [1].push(2) gives you the number 2, not [1, 2]. That is why you can't chain push like other methods. Use concat or spread when you want a value you can pass along, and push as a statement on its own line.
Step 5: concat with loose values
concat also accepts single values, and it unwraps any array you hand it, but only one level deep.
const a = [1, 2];
console.log(a.concat(3, [4, 5])); // [ 1, 2, 3, 4, 5 ]
console.log([1].concat([[2]])); // [ 1, [ 2 ] ]
[[2]] is an array holding an array. concat opens the outer one and keeps the inner [2] as an item.
Step 6: a quick copy
concat() with nothing in the brackets copies an array.
const a = [1, 2];
const copy = a.concat();
console.log(copy); // [ 1, 2 ]
console.log(copy === a); // false
Same items, different array. [...a] and a.slice() do the same.
A limit to know about
push(...other) turns every item into a separate argument. Engines have a limit on how many arguments one call can take. With a very large array, hundreds of thousands of items, push(...other) can throw an error. concat doesn't have that limit, so prefer it, or a loop, for very large arrays.
The full solution
The panel joins a and b with concat and spread, then shows push(...b) next to push(b) and prints what push returned. Press Run to see the output.
const a = [1, 2];
const b = [3, 4];
const joined = a.concat(b);
const spread = [...a, ...b];
const pushedSpread = [1];
pushedSpread.push(...b); // appends 3 and 4
const pushedWhole = [1];
const newLength = pushedWhole.push(b); // appends ONE element: the array
console.log('concat :', joined);
console.log('spread :', spread);
console.log('inputs after:', a, b, '<- both untouched');
console.log('push(...b) :', pushedSpread);
console.log('push(b) :', pushedWhole, '<- one nested element');
console.log('push returned', newLength, 'which is a length, not an array');
console.log('concat with loose values:', a.concat(3, [4, 5]));
console.log('one level only :', [1].concat([[2]]));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('concat joins into a new array', joined, [1, 2, 3, 4]);
test('spread gives the same result', spread, [1, 2, 3, 4]);
test('neither input is modified', [a, b], [[1, 2], [3, 4]]);
test('concat takes loose values as well as arrays', a.concat(3, [4, 5]), [1, 2, 3, 4, 5]);
test('but it unwraps only one level', [1].concat([[2]]), [1, [2]]);
test('push(...b) appends the elements', pushedSpread, [1, 3, 4]);
test('push(b) appends the array as a single element', pushedWhole, [1, [3, 4]]);
test('push returns the new length', newLength, 2);
test('concat() with no arguments is a shallow copy', a.concat().length === a.length && a.concat() !== a, true);
push returning a length is the detail that trips chaining: const xs = [1].push(2) gives you 2, not [1, 2]. Use concat or spread when you want an expression, push when you want a statement.
push(...other) reads well and has a real limit: the spread becomes one argument per element, and a few hundred thousand of them will exceed the engine's argument limit and throw. For very large arrays, concat or a loop is the safe form.
Common mistakes
- Writing
push(b)to add the items ofb. You get one nested array. Writepush(...b). - Using the return value of
push. It is a number, the new length. Useconcator spread when you need the array. - Expecting
concatto flatten everything. It unwraps one level only. Useflatfor deeper nesting.
Try it yourself
- Combine three arrays,
[1],[2, 3]and[4], with oneconcatcall and then with one spread. - Add
'tea'to the start and'bread'to the end of['milk', 'sugar']in one line, without changing it. - Predict what
[1].concat(2, [3, [4]])gives, then check it.