JavaScript Arrays: Concat
Welcome to the Concat lesson!
JavaScript's array `.concat` method joins ("concatenates") multiple arrays into a single new array.
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
In many languages,
+combines two arrays. That's not the case in JavaScript. Trying to doarray1 + array2is usually a mistake. JavaScript will convert the arrays into strings before adding them.>
[1, 2].toString();Result:
>
[1, 2] + [3];Result:
>
[1, 2] + [3, 4];Result:
'1,23,4'
However, we can combine arrays properly with
.concat. (It's short for "concatenate", which means "link together".) This creates a new array containing all of the elements from the original arrays.>
[1, 2].concat([3, 4]);Result:
[1, 2, 3, 4]
.concattakes multiple arguments, so we can combine many arrays if needed:>
[1, 2].concat([3, 4], [5, 6]);Result:
[1, 2, 3, 4, 5, 6]
If we pass a single element to
.concat, it'll add it to the end of an array.>
[1, 2].concat(3);Result:
[1, 2, 3]
At first, using
.concaton a single element looks like using.push. But there's a crucial difference:.pushmutates the array we're pushing to.>
const oldNumbers = [1, 2];oldNumbers.push(3);oldNumbers;Result:
[1, 2, 3]
.concatbuilds and returns a new array. The original arrays aren't changed.>
const numbers1 = [1, 2];const numbers2 = [3, 4];numbers1.concat(numbers2);numbers1;Result:
[1, 2]
>
const oldNumbers = [1, 2];const newNumbers = oldNumbers.concat(3);oldNumbers;Result:
[1, 2]