3 Ways to concatenate strings in JavaScript

3 Ways to concatenate strings in JavaScript

concatenation in JavaScript

There are 3 main ways to concatenate strings in JavaScript:

  1. The + operator
const str1 = 'Hello' 
const str2 = 'World'
const result = str1 + ' ' + str2
// result is 'Hello World'

The + operator can be used to concatenate both strings and other types by implicitly converting them to strings.

  1. The Array.prototype.join() method
const parts = ['Hello', ' ', 'World']
const result = parts.join('')
// result is 'Hello World'

The join() method joins all elements of an array into a string, using an optional separator. This is useful when concatenating multiple strings.

  1. The String.prototype.concat() method
const str1 = 'Hello'
const result = str1.concat(' ', 'World')
// result is 'Hello World'

The concat() method concatenates one or more strings to the calling string and returns a new string.

The + operator is the most flexible and commonly used method for string concatenation. Array.join() is useful when concatenating an array of strings, and concat() is rarely used due to its more restrictive error cases.

Conclusion-

In summary, the + operator is recommended for most string concatenation needs in JavaScript due to its flexibility, simplicity and performance.

Hope this helps! Let me know if you have any other questions.