How to Merge Strings or Arrays in JavaScript Using the concat() Method

JavaScript has a built-in method for merging strings or arrays together called concat(). It allows you to take an array, combine it with one or many different arrays and make a new array containing the elements from all the arrays – the same principle applies to strings.

 

In this tutorial, we will learn how to merge strings or arrays in JavaScript with examples.

 

Merge Strings in JavaScript

Let's begin by merging strings together. Put the concat() method after the string variable as a “dot function”. Then pass a comma-separated list of strings to add inside the () (parenthesis) of the concat() method.

 

var string_1 = 'hello ';
var string_2 = ' good afternoon ';
var string_3 = 'goodbye';

var merged = string_1.concat(string_2, string_3);

console.log(merged);
hello  good afternoon goodbye

 

As you can see in the example above, concat() appends strings to the first string.

 

note - you can merge numbers to the string; they will automatically be converted into strings.

 

Merge Two or More Arrays in JavaScript

To merge arrays, put the first array before the concat() method with a . (dot) separating them. Then pass a comma-separated list of arrays inside the () (parenthesis) of the concat() method in the order you wish them to be appended.

 

var array_1 = [1, 2, 3];
var array_2 = [4, 5, 6];
var array_3 = [7, 8, 9];

var merged = array_1.concat(array_2, array_3);

console.log(merged);
[1, 2, 3, 4, 5, 6, 7, 8, 9]

 

note - arrays can be merged into strings, though the new string will contain a comma-separated list of elements from the array(s). Strings can also be merged into a new array using concat().

 

Merge Arrays Using the Spread Syntax

The spread syntax was introduced in ES2015 and allows us to merge arrays with a very clean syntax. To use it create a new array using [] (square brackets) and pass in a comma-separated list of arrays, each of which starting with (three dots).

 

var array_1 = [1, 2, 3];
var array_2 = [4, 5, 6];
var array_3 = [7, 8, 9];

var merged = [...array_1, ...array_2, ...array_3];

console.log(merged);
[1, 2, 3, 4, 5, 6, 7, 8, 9]

 

Conclusion

You now know how to merge arrays and strings in JavaScript using the concat() method. If you are working with strings the + operator is a cleaner way to achieve the same result.

array string merge combine concatenate