This post will discuss how to concatenate two strings in JavaScript.

There are several ways to concatenate two strings in JavaScript. Here are some of the most common functions, along with some examples and explanations:

1. Using + operator

One of the simplest ways to concatenate two strings in JavaScript is to use the + operator, which performs string concatenation if one of the operands is a string. Here’s an example:

Download  Run Code

 
We can also use the += operator, where x += y is a shorthand for x = x + y. Here’s an example:

Download  Run Code

2. Using String.concat() function

Another way to concatenate two strings in JavaScript is to use the String.concat() function, which returns a new string that is the result of joining two or more strings. Here’s an example:

Download  Run Code

 
However, using the + operator is less error prone in case the first operand is not a string.

3. Using Array.join() function

We can also use the Array.join() function, which returns a new string that is the result of joining all the elements in an array with a specified separator. Here’s an example:

Download  Run Code

 
This function is useful when we have an array of strings or when we want to specify a different separator between the strings.

4. Using template literals

This is a new feature in ES6 that allows us to create strings with embedded expressions and variables using backticks and placeholders. Template literals can also span multiple lines and support interpolation of any JavaScript expression. For example:

Download  Run Code

That’s all about concatenating two strings in JavaScript.