You can also use the += operator, which is the same as the + operator except it will append the new string to the existing string.
JAVASCRIPT
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.
JAVASCRIPT
let sentence = "Apples";
sentence += undefined; // Type coercionconsole.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.
JAVASCRIPT
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.
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.
JAVASCRIPT
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: