Different methods of concatenating JavaScript strings

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.
- 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.