Different methods of concatenating JavaScript strings

Mohammad Anisul Islam
2 min readApr 23, 2021

--

String concatenation

First let's know what is “concatenating”. It means to add two or more strings/parts of strings.

There are various methods of concatenating two or more strings. In this article, we are going to show three different ways of concatenating Strings.

  1. Using assignment operator (+, +=)

There are two assignment operators used to concate.

a. +

b. +=

let str1 = "JavaScript";
let str2 = "String";
console.log(str1 + " " + str2);//You can get Output after executiong last line : JavaScript Stringstr1 + " "; str1 += str2; console.log(str1);//You can get Output after executiong last line : JavaScript String

2. Using array join

Here, elements of array join with each other by join() function.

const strArray = ["JavaScript", " ", "String"];const concatenatedString = strArray.join(""); //Join all string elements of strArray array;console.log(concatenatedString);
//You can get Output after executiong last line : JavaScript String

3. Using string concat() method

Another method of the concatenation of string apply concat() method.

const str1 = "JavaScript";
const str2 = "String";
const concatenatedString = str1.concat(" ", str2);console.log(concatenatedString);
//You can get Output after executiong last line : JavaScript String

Though there have many methods to apply concatenation, it is encouraged to use the assignment operator rather than concat() method. The reason is, concat() has shown more error cases than the + operator.

For example, you would get unwanted behavior if you call concat() on a value that happens to be an array. You should use + instead of concat().

That's short for today about concatenating strings in JavaScript.

Happy coding.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Mohammad Anisul Islam
Mohammad Anisul Islam

Written by Mohammad Anisul Islam

Software Engineer || Full Stack Developer || Technical Writer || Speaker

No responses yet

Write a response