Skip to content

Add array to array JavaScript | Example code

Use the concat() method to Add array to array JavaScript. But this method creates a new array instead of simply extending the first one.

a.concat(b)

Another method is the push() method, which can take multiple arguments. You can use the spread operator to pass all the elements of the second array as arguments to .push.

a.push(...b)

Example Add array to array JavaScript

A simple example code merges two arrays using The concat() method.

<!DOCTYPE html>
<html>
<body>

  <script>

    var a = [1, 2];
    var b = [3, 4, 5];

    var res = a.concat(b);

    console.log(res)

  </script>

</body>
</html>

Output:

Add array to array JavaScript

How to extend an existing JavaScript array with another array, without creating a new array?

Answer: push is often used to push an array to the end of an existing array.

  <script>

    var a = [1, 2];
    var b = [3, 4, 5];

    a.push(...b)

    console.log(a)

  </script>

Output: Array(5) [ 1, 2, 3, 4, 5 ]

Do comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

1 thought on “Add array to array JavaScript | Example code”

Leave a Reply

Your email address will not be published. Required fields are marked *