js

JavaScript Concatenate Strings es6| String concat() Method


The concat() method is used to join two or more strings to form a new string. This is done by joining one or more strings to the calling string. This method returns a new string containing the text of the joined strings without changing the existing strings. It was introduced in ECMAScript 1.

Syntax

string.concat(string1, string2, ... string_n);

Parameters 

string1, string2, ... string_nThese are the values to join to the end of the calling string.

Returns

The concat() method returns a new string that results from concatenating the original string with the string values that were passed in as parameters.

Examples

const firstName = 'John';
const middleName = 'Emmanuel';
const surname = 'Paul';
console.log(firstName.concat(' ', middleName));
// expected output: "John Emmanuel"

console.log(surname.concat(', ', firstName, middleName));
// expected output: "Paul, John Emmanuel"
let greetList = ['Paul', ' ', 'how are ', 'you doing!']
"Hello".concat(...greetList) 
// expected output: "Hello Paul how are you doing!"

String.concat() and numbers

"".concat(20, 20)  // "2020"

Note

Other ways to concatenate string values in JavaScript include:

  • Using the + operator.
  • Using the ES6 template literal.

According to the performance test between the assignment operators and the string concat() method, it is strongly recommended that the assignment operators (+, +=) are used instead of the concat() method.

Conclusion

The concat() method join multiple string strings together and returns a new string. Performance-wise, the concat() method is slower in modern JavaScript engines compared to the + which is faster on modern JavaScript engines.


Share on social media

//