Summary: in this tutorial, you’ll learn how to concatenate strings in JavaScript.
JavaScript provides various options that allow you to concatenate two or more strings:
- Use the
concat()method - Use the
+and+=operators - Use the template literals
1) Using the concat() method #
The String.prototype.concat() concatenates two or more string arguments and returns a new string:
let newString = string.concat(...str);The concat() accepts a varied number of string arguments and returns a new string containing the combined string arguments.
If you pass non-string arguments into the concat(), it will convert these arguments to a string before concatenating. For example:
let racing = 'Formula ' + 1;
console.log(racing);Output:
Formula 1This example concatenates strings into a new string:
let result = concat('JavaScript', ' ', 'String',' ', 'Concatenation');
console.log(result);Output:
JavaScript String ConcatenationThe following example concatenates all string elements in an array into a string:
let list = ['JavaScript',' ', 'String',' ', 'Concatenation'];
let result = ''.concat(...list);
console.log(result);Output:
JavaScript String Concatenation2) Using the + and += operators #
The operator + allows you to concatenate two strings. For example:
let lang = 'JavaScript';
let result = lang + ' String';
console.log(result);Output:
JavaScript StringTo compose a string piece by piece, you use the += operator:
let className = 'navbar';
className += ' primary-color';
className += ' sticky-bar';
console.log(className);Output:
According to a performance test on some modern web browsers, the + and += operators perform faster than the concat() method.
3) Using template literals #
ES6 introduces the template literals that allow you to perform string interpolation.
The following example shows how to concatenate three strings:
let navbarClass = 'navbar';
let primaryColor = 'primary-color';
let stickyClass = 'sticky-bar';
let className = `${navbarClass} ${primaryColor} ${stickyClass}`;
console.log(className);Output:
navbar primary-color stickyBarIn this tutorial, you have learned how to concatenate strings in JavaScript using the concat() method, + and += operator, and template literals.
Thank you for your feedback!