Akercode.com

JavaScript String Concatenation

To combine, or join text strings together.

concat()

TheĀ concat() method concatenates, or appends string(s) to the calling string and returns the result as a new string.

const str = 'Fire'.concat('trucks');

console.log(str); // 'Firetrucks'

You can concatenate multiple parameters:

const originalStr = 'Fire';

const str1 = 'trucks';
const str2 = ' ';
const str3 = 'are the best!';

const str = originalStr.concat(str1, str2, str3);

console.log(str); // 'Firetrucks are the best!'

The same can be done with an array of arguments and the rest parameter, if you don't know how many parameters there will be:

let coolVehicles = ['Firetrucks', ' & ', 'Ambulances', '!'];

let str = ''.concat(...coolVehicles);

console.log(str); // 'Firetrucks & Ambulances!'

It's strongly recommended that the assignment operators (+, +=) are used instead of the concat() method because of performance.

+ operator

The + operator returns a new string:

const str1 = 'Now I know how to';
const str2 = 'concatenate!';

const str = str1 + ' ' + str2;

console.log(str); // 'Now I know how to concatenate!'

+= operator

The += operator modifies the original string:

let str = 'Now I know how to';
str += ' ';
str += 'concatenate!';

console.log(str); // 'Now I know how to concatenate!'

Template Literals

Recognized by the backticksĀ ` allowing embedded expressions called substitutions.

const str1 = 'Now I know how to';
const str2 = 'concatenate';

const str = `${str1} correctly ${str2} like a pro!`;

console.log(str); // 'Now I know how to correctly concatenate like a pro!'