How to Concatenate Strings in JavaScript

Updated onbyAlan Morel
How to Concatenate Strings in JavaScript

In this post, we'll learn four different ways to concatenate strings in JavaScript.

The Plus Operator

You can use the + operator to concatenate strings.

const firstName = "John";
const lastName = "Doe";
const fullName = firstName + " " + lastName;

console.log(fullName); // John Doe

You can also use the += operator, which is the same as the + operator except it will append the new string to the existing string.

let sentence = "Apples";
sentence += " are red";

console.log(sentence); // Apples are red

It is safe to use the += operator on a variable that is not a string, like undefined, null, and objects, because JavaScript will convert the variable to a string if the left-hand side is already a string. This is called type coercion.

let sentence = "Apples";
sentence += undefined; // Type coercion

console.log(sentence); // Applesundefined

Template Strings

You can use template strings for string interpolation. Template strings allow you to add expressions inside of a string in a cleaner way.

const firstName = "John";

const greeting = `Hi my name is ${firstName}`;

console.log(greeting); // Hi my name is John

Template strings are generally the recommended way to do string concatenation because they're easier to read and write.

Join() function

You can use the join() function to create a new string using an existing array by concatenating all of its elements.

const fruits = ["Banana", "Orange", "Apple", "Mango"];
const fruitList = fruits.join(", ");

console.log(fruitList); // Banana, Orange, Apple, Mango

The join() function takes an optional parameter that specifies the separator to use between each element. The default separator is a comma (,).

Here's another example using a slash as a separator:

const url = ["", "blog", "javascript-concat-strings"];
const path = url.join("/");

console.log(path); //

In general, using join() is the preferred way to concatenate strings because it is more efficient than using the + operator inside a loop.

Concat() function

You can use the concat() function to create a new string by concatenating two or more existing strings. Because strings are immutable, the concat() function returns a new string instead of modifying the existing one.

const a = "Hi";
const b = "there";

const c = a.concat(b);

console.log(c); // Hithere

Keep in mind that the concat() function only works with strings since it is a function on the String object. There's no good reason to use the concat() unless you have to, but if you do, the common practice is to use it on an empty string to avoid any issues:

"".concat("Hi", "there"); // Hithere


To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 All rights reserved. Made with ❤ in NY.