How to Concatenate Strings in JavaScript [4 Ways]

Here are the four ways to concatenate a strings in JavaScript.

  1. Using the + operator
  2. Using template literals
  3. Using the concat() method
  4. Use the join() method

Method 1: Using the + operator

The + or concate operator is used to concatenate two strings. If the left-hand side of the + operator is a string, JavaScript will coerce the right-hand side into a string. In JavaScript, the “+” concatenation creates a new String object.

Visualization of Using the + operator

let str = "Maeve: ";
str += "Wiley";

console.log(str);

Output

Maeve: Wiley

Method 2: Using template literals

Template literals are string literals producing enclosed expressions. You can use multi-line strings and string interpolation features with them. For example, this is the output of the following string before template strings.

let fn = "Krunal"
let country = "India"

console.log("Hi, I'm " + fn + " and I'm from " + country);

Output

Hi, I'm Krunal and I'm from India

You can see that the code is not easily readable, and you can make mistakes if you are not careful. It is a mess and cumbersome.

To fix this issue, you can use the “template literals”, which makes things super easy.

Visualization of Using template literals

let fn = "Krunal"
let country = "India"

console.log(`Hi, I'm ${fn} and I'm from ${country}`);

Output

Hi, I'm Krunal and I'm from India

Method 3: Using the concat() method

Pictorial representation of concat() method

The string concat() is a built-in JavaScript method that takes one or more parameters and returns the modified string. You can use the concat() method to append or join the strings.

const dt1 = "Otis";
const dt2 = dt1.concat(" ", "Milburne");

console.log(dt1);
console.log(dt2);

Output

Otis
Otis Milburne

Method 4: Using the join() method

The array join() is a built-in method that combines the array items and returns a string. A specified separator will separate the elements. The default separator is a comma (,). If you are working with an array, adding additional strings is beneficial.

const spain = "Hola";
const belgium = "Hello";
const switzerland = ['Other winners are ', spain, belgium];

const italy = "kem chho";

switzerland.push(italy);

console.log(switzerland.join(' '));

Output

Other winners are Hola Hello kem chho

That’s it.

Related posts

How to Check If Variable is String in JavaScript

How to Get Last Character from String in JavaScript