Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to concatenate several strings in JavaScript?
JavaScript provides multiple methods to concatenate several strings. The most common approaches include using the + operator, template literals, Array.join(), and the concat() method.
Method 1: Using the + Operator
The simplest way to concatenate strings is using the + operator:
<html>
<body>
<script>
let str1 = "John";
let str2 = "Amit";
let str3 = "Sachin";
let result = str1 + ", " + str2 + ", " + str3;
document.write(result);
</script>
</body>
</html>
John, Amit, Sachin
Method 2: Using Template Literals (ES6)
Template literals provide a cleaner syntax using backticks and ${} placeholders:
<html>
<body>
<script>
let str1 = "John";
let str2 = "Amit";
let str3 = "Sachin";
let result = `${str1}, ${str2}, ${str3}`;
document.write(result);
</script>
</body>
</html>
John, Amit, Sachin
Method 3: Using Array.join()
When concatenating multiple strings with the same separator, Array.join() is very efficient:
<html>
<body>
<script>
let arr = ['John', 'Amit', 'Sachin'];
let result = arr.join(', ');
document.write(result);
</script>
</body>
</html>
John, Amit, Sachin
Method 4: Using concat() Method
The concat() method joins strings without modifying the original strings:
<html>
<body>
<script>
let str1 = "John";
let str2 = "Amit";
let str3 = "Sachin";
let result = str1.concat(", ", str2, ", ", str3);
document.write(result);
</script>
</body>
</html>
John, Amit, Sachin
Comparison
| Method | Best For | Performance |
|---|---|---|
+ operator |
Simple concatenation | Good |
| Template literals | Complex strings with variables | Good |
Array.join() |
Many strings with same separator | Best for large arrays |
concat() |
Method chaining | Good |
Conclusion
Choose the concatenation method based on your needs: use + for simple cases, template literals for complex formatting, and Array.join() for multiple strings with consistent separators.
Advertisements
