Execute Program

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 do array1 + array2 is 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'Pass Icon
  • 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]Pass Icon
  • .concat takes multiple arguments, so we can combine many arrays if needed:

  • >
    [1, 2].concat([3, 4], [5, 6]);
    Result:
    [1, 2, 3, 4, 5, 6]Pass Icon
  • 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]Pass Icon
  • At first, using .concat on a single element looks like using .push. But there's a crucial difference: .push mutates the array we're pushing to.

  • >
    const oldNumbers = [1, 2];
    oldNumbers.push(3);
    oldNumbers;
    Result:
    [1, 2, 3]Pass Icon
  • .concat builds 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]Pass Icon
  • >
    const oldNumbers = [1, 2];
    const newNumbers = oldNumbers.concat(3);
    oldNumbers;
    Result:
    [1, 2]Pass Icon