JavaScript provides three different ways to perform String concatenation:
Template literals are the most preferred way of concatenating strings in JavaScript because they enable string interpolation. Instead of using single or double quotes in template literals, you use backticks (`) to create the string. Within the backticks, you use placeholders to replace variables with their respective values. Placeholders are created using the ${}
.
The following example will show you how easy it is to concatenate strings using template literals.
let a = 5; let b = 10; let sum = `The value of ${a} + ${b} is ${a+b}.`; console.log(sum); //The value of 5 + 10 is 15.
+
operator performs two functions based on the operands present on both sides of it. For example, if both operands are numbers, then the + operator performs addition. On the other hand, if any of the operands is a string, then the + operator does string concatenation.
Let's understand the string concatenation using the + operator.
let firstName = 'Mohit'; let lastName = 'Natani'; let msg = "Hello " + firstName + " " + lastName + ", How are you?"; console.log(msg); //Hello Mohit Natani, How are you?
+=
is an assignment using which you can also perform string concatenation. For example:
let firstName = 'Mohit'; let lastName = 'Natani'; let msg = "Hello "; msg += firstName; msg += " "; msg += lastName; console.log(msg); //Hello Mohit Natani
If you want to concatenate two or more strings then use the String.prototype.concat()
method.
The concat() method does not modify the original string. The syntax for the concat() method is:
let concatenatedString = string.concat(str1, str2, ..., strn);
The resultant string will be of the form:
"stringstr1str2,...,strn"
The following example will explain to you the process of concatenating string using the concat() method.
let firstName = "Mohit "; let lastName = "Natani"; let fullName = firstName.concat(lastName); console.log(fullName); //Mohit Natani console.log(firstName); //Mohit
Using the spread operator, you can also pass the entire array to the concat() method and get the string concatenated form of all the array elements.
let arr = ["Performing", " ", "String", " ", "Concatenation"]; let resultant = "".concat(...arr); console.log(resultant); //Performing String Concatenation