String concatenation using + operator vs. template literals in JS
Description
String concatenation can be done using several different methods. The + operator and template literals are a couple of these methods. Template literals make it easier to embed variables into a string.
String concatenation using the + operator
The + operator is usually the operator we use to add two numbers. + can also be used to concatenate strings in JavaScript.
Example
const name = "sachin";const age = "40";const country = "India";const output = "Hi, I am " + name + " and I am "+ age+" years old. I am from "+ country +".";console.log(output);// Hi, I am sachin and I am 40 years old. I am fromIndia.
String concatenation using template literals
Let’s take a look at a similar example using template literals.
Example
const name = "sachin";const age = "40";const country = "India";const output = `Hi, I am ${name} and I am ${age} years old. I am from ${country}.`;console.log(output);// Hi, I am sachin and I am 40 years old. I am from India.
Explanation
You can use template strings to write your string exactly how you want it to appear, without all the quotation marks and confusion. Template strings make it very easy to spot a missing space and make your string more readable.
Conclusion
Repeated concatenation using the + operator, with variables and more strings, can lead to a lot of very hard-to-read code. Don’t create a never-ending chain of concatenated strings using the + operator.
It is better to use template literals, as they were created specifically for this purpose.