Skip to content

JavaScript string concatenation | Example code

  • by

Use + Operator or String concat() method to string concatenation in JavaScript. The concat() method joins two or more strings.

string.concat(string1, string2, ..., stringX)

The same + operator you use for adding two numbers can be used to concatenate two strings.

const str = 'Hello' + ' ' + 'World';

You can also use +=, where a += b is a shorthand for a = a + b.

let str = 'Hello';
str += ' ';
str += 'World';
str; // 'Hello World'

JavaScript string concatenation

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    // + Operator
    const str = 'Hello' + ' ' + 'World';
    console.log(str);

    // String concat()
    const str1 = 'str1';
    const str2 = str1.concat(' ', 'str2');

    console.log(str2)

  </script>
</body>
</html>

Output:

JavaScript string concatenation

Use the Array join() function to create a new string from concatenating all elements in an array.

['Hello', ' ', 'World'].join(''); // 'Hello World'

Using string interpolation (ES6 and later):

let firstName = "John";
let lastName = "Doe";
let fullName = `${firstName} ${lastName}`;

JS strings “+” vs concat method

MDN has the following to say about string.concat():

It is strongly recommended to use the string concatenation operators (+, +=) instead of this method for performance reasons

Also, see the link by @Bergi.

TestOps/sec
concat'Coucou '.concat('c\'est ', 'nous !');27,370,690 ±0.72%fastest
+'Coucou ' + 'c\'est ' + 'nous !';Infinity ±0.00%
join['Coucou ', 'c\'est ', 'nous !'].join();11,480,928 ±1.59%58% slower

Using the concat() method:

let str1 = "Hello";
let str2 = "world";
let result = str1.concat(" ", str2); // Concatenating two strings with a space in between
console.log(result); // Output: "Hello world"

You can also use template literals (introduced in ES6) for string concatenation. Template literals allow embedding expressions inside ${} within backticks (`).

let str1 = "Hello";
let str2 = "world";
let result = `${str1} ${str2}`; // Using template literals for string concatenation
console.log(result); // Output: "Hello world"

This syntax makes it easier to concatenate strings and embed variables or expressions within them.

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

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

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading