JavaScript String Concatenation Guide: +, concat(), Template Literals, and join()

1. Introduction

JavaScript is one of the most widely used programming languages in web development. Among its many features, string concatenation is a fundamental operation that is used extremely often—such as combining data or generating content to display on the screen.

For example, when you display data received from a form or generate sentences dynamically, string concatenation becomes essential. In this article, we will explain several different ways to concatenate strings in JavaScript in detail, and introduce appropriate examples depending on your use case and situation.

By the end, you will understand everything from the basics to more advanced techniques and gain practical skills you can apply in real-world development.

2. Basic Methods of String Concatenation

The simplest way to concatenate strings in JavaScript is to use the plus operator (+). This method is highly readable and easy to write, so even beginners can quickly start using it.

Example Using the Plus Operator (+)

let greeting = "Hello";
let name = "World";
let message = greeting + " " + name + "!";
console.log(message); // Output: Hello World!

This example shows how easily you can concatenate string literals and variables.

Be Careful with Type Conversion

One important thing to watch out for when using the plus operator is concatenating numbers and strings. In JavaScript, when different types are combined, the value is automatically converted into a string.

let number = 10;
let text = " apples";
console.log(number + text); // Output: 10 apples

This behavior is convenient, but it can also produce unexpected results. If you want arithmetic operations to be performed first, you need to use parentheses to control the evaluation order.

console.log("The total is " + (5 + 10)); // Output: The total is 15
console.log("The total is " + 5 + 10);   // Output: The total is 510

Summary

The plus operator is simple and intuitive, making it an ideal choice for short string concatenations. However, be careful when working with numbers, and use parentheses when necessary to avoid unexpected results.

3. Other Methods of String Concatenation

In JavaScript, there are several ways to concatenate strings besides the plus operator (+). In this section, we will explain how to use the concat() method and template literals, along with their key features.

concat() Method

The concat() method is a built-in function used to combine multiple strings. Since it uses a function-based syntax, it can be convenient when you need to chain multiple concatenation operations.

Example

let str1 = "JavaScript";
let str2 = "string";
let str3 = "concatenation";
let result = str1.concat(" ", str2, " ", str3);
console.log(result); // Output: JavaScript string concatenation

In this code, multiple strings are concatenated with spaces inserted between them.

Advantages

  • Easy to read and useful when concatenating multiple strings in order.
  • Safe because it returns a new string without modifying the original string.

Disadvantages

  • Readable, but it tends to increase the amount of code and is less concise than using the plus operator.

Template Literals

Template literals are a newer syntax introduced in ES6 (ECMAScript 2015). They allow you to embed variables and write multi-line strings more cleanly. Strings are wrapped in backticks (`), and you can embed variables or expressions using ${}.

Example

let name = "Taro";
let age = 25;
let message = `Hello, ${name}! You are ${age} years old.`;
console.log(message);
// Output: Hello, Taro! You are 25 years old.

Advantages

  • Simple and easy to read when embedding variables or expressions.
  • Makes multi-line strings easy to write.
let address = `Address:
Tokyo
Shibuya
1-1-1`;
console.log(address);
/* Output:
Address:
Tokyo
Shibuya
1-1-1
*/

Disadvantages

  • May not be supported in older browsers, so transpiling may be required in legacy environments.

Conclusion

It is important to choose the right method depending on your use case and the readability of your code.

  • Plus operator (+): Best for simple cases.
  • concat() method: Useful when you want to concatenate multiple strings safely.
  • Template literals: Ideal for embedding variables/expressions and handling multi-line strings.

4. Concatenating Array Elements

In JavaScript, the join() method is provided to efficiently combine array elements. This method concatenates each element into a single string and allows you to specify any separator you want.

Basic Usage of the join() Method

Syntax

array.join(separator)
  • array: The array containing the elements you want to concatenate.
  • separator: The separator used between elements (defaults to a comma , if omitted).

Example

let words = ["JavaScript", "string", "concatenation"];
let result = words.join(" ");
console.log(result); // Output: JavaScript string concatenation

In this example, each element is joined into one string using a space.

Specifying Separators

Comma-separated (default)

let fruits = ["apple", "orange", "grape"];
console.log(fruits.join()); // Output: apple,orange,grape

Hyphen-separated

let phoneNumber = ["080", "1234", "5678"];
console.log(phoneNumber.join("-")); // Output: 080-1234-5678

No separator

let letters = ["H", "e", "l", "l", "o"];
console.log(letters.join("")); // Output: Hello

Practical Examples

  1. Generating HTML Tags
let listItems = ["<li>apple</li>", "<li>orange</li>", "<li>grape</li>"];
let htmlList = "<ul>" + listItems.join("") + "</ul>";
console.log(htmlList);
/*
Output:
<ul><li>apple</li><li>orange</li><li>grape</li></ul>
*/
  1. Generating a CSV-formatted String
let data = ["Tanaka", "Taro", "30", "Tokyo"];
console.log(data.join(",")); // Output: Tanaka,Taro,30,Tokyo
  1. Formatting Output When Processing JSON Data
let keys = ["name", "age", "location"];
let values = ["Suzuki", 28, "Osaka"];
let result = keys.map((key, index) => `${key}: ${values[index]}`).join(", ");
console.log(result);
// Output: name: Suzuki, age: 28, location: Osaka

Benefits of the join() Method

  • Simple and efficient: You can concatenate multiple elements at once without writing loops.
  • Flexible separators: Easily customize formatting based on your data structure.
  • Performance optimization: Works fast even when handling large amounts of string concatenation.

Conclusion

When concatenating array elements, the join() method is a powerful tool—especially in the following situations:

  • Creating list-style or table-style output
  • Formatting CSV or JSON-like data
  • Generating HTML or structured text

5. Performance and Optimization

When concatenating strings in JavaScript, performance becomes an important factor when working with large amounts of data or complex processing. In this section, we will explain efficient string concatenation techniques and key optimization tips.

Performance Issues with Large-Scale Data Processing

The most intuitive way to concatenate strings is using the plus operator (+), but performance can degrade when used inside large loops.

Example: Concatenating Strings Inside a Loop

let result = "";
for (let i = 0; i < 100000; i++) {
  result += "data";
}

In this code, result is recreated as a new string object on every iteration, which can significantly slow down processing.

Efficient Concatenation Methods

  1. Using an Array with the join() Method

By storing data in an array and using the join() method at the end, you can reduce memory overhead.

Example: Efficient Loop Processing

let data = [];
for (let i = 0; i < 100000; i++) {
  data.push("data");
}
let result = data.join("");

In this approach, each string is stored in an array and then concatenated all at once, which improves memory efficiency and performance.

  1. Simplifying with Template Literals

Template literals provide a good balance of readability and convenience for small-scale string operations.

Example: Loop Using Template Literals

let result = "";
for (let i = 0; i < 100000; i++) {
  result = `${result}data`;
}

This method is convenient, but it may be slightly slower than using join(), so you should be careful when working with large datasets.

Benchmark Comparison

The following table shows the differences in execution time when performing large-scale string concatenation.

MethodExecution Time (100,000 iterations)
Plus operator (+)120ms
Array + join()25ms
Template literals (${})135ms

These results show that combining an array with join() is the most efficient approach.

Key Notes and Best Practices

  1. Keep it simple for short strings
    For small concatenations, using the plus operator or template literals is perfectly fine.
  2. Use join() for large-scale data processing
    For large datasets, array-based concatenation is recommended for better performance and memory efficiency.
  3. Use optimization tools
    When performance matters, use tools like Chrome DevTools or Node.js performance measurement utilities to evaluate execution time and memory usage.

Conclusion

String concatenation should be optimized based on the size and purpose of your code.

  • Small-scale processing: Use the plus operator or template literals.
  • Large-scale processing: Use arrays and the join() method for efficient concatenation.

By choosing the right approach for each scenario, you can achieve both speed and readability.

6. Key Considerations and Best Practices

When concatenating strings in JavaScript, unexpected errors or performance issues may occur. In this section, we will cover important points to watch out for and best practices for writing efficient, maintainable code.

Type Conversion When Combining Numbers and Strings

In JavaScript, when you concatenate a number and a string, the number is automatically converted into a string. This behavior is useful, but it can sometimes produce unintended results.

Example: Unintended Result

let total = 5 + 10 + " yen";
console.log(total); // Output: "15 yen"

Here, 5 + 10 is evaluated first, resulting in 15. Then it is concatenated with the string, so 15 is converted into a string.

Solution
If you want to control the evaluation order, use parentheses.

let total = 5 + (10 + " yen");
console.log(total); // Output: "510 yen"

Handling undefined or null Values

If a variable is undefined or null, concatenating it directly may produce unexpected output.

Example: Handling null or undefined

let name = null;
let greeting = "Hello, " + name + "!";
console.log(greeting); // Output: "Hello, null!"

Solution
You can safely handle this by providing a default value.

let name = null;
let greeting = `Hello, ${name || "Guest"}!`;
console.log(greeting); // Output: "Hello, Guest!"

Optimizing Large-Scale String Concatenation

When working with large amounts of text, using the join() method is recommended to improve performance.

Efficient Example

let data = [];
for (let i = 0; i < 100000; i++) {
  data.push("data");
}
let result = data.join("");

Using += inside a loop can slow things down, so storing values in an array and joining them at the end is typically faster.

Improving Readability and Maintainability

Since code may be maintained by someone other than the original author, keep the following points in mind:

  1. Use template literals
    When concatenating strings with variables or line breaks, template literals help keep your code clean and readable.

Example: Better Readability with Template Literals

let name = "Tanaka";
let age = 30;
let message = `${name} is ${age} years old.`;
console.log(message); // Output: Tanaka is 30 years old.
  1. Add comments when needed
    For more complex logic, add appropriate comments to clarify your intent and improve maintainability.

Summary of Best Practices

  1. For small concatenations, use the plus operator or template literals.
  2. For large concatenations, use arrays and join() for better performance.
  3. Be careful with type conversion and undefined/null values, and set safe defaults.
  4. Prioritize readability and maintainability by using template literals and adding comments when appropriate.

7. Summary

In this article, we explored various ways to perform string concatenation in JavaScript—from basic techniques to more advanced approaches. Let’s review the key points so you can apply them in real-world development.

1. Basic String Concatenation Methods

  • The plus operator (+) is simple and intuitive, making it ideal for small-scale concatenation.
  • Be mindful of type conversion, and use parentheses to prevent unexpected results.

2. Other String Concatenation Methods

  • The concat() method is a function-based approach that safely concatenates multiple strings.
  • Template literals allow you to embed variables and expressions, and they also support multi-line strings. This makes them both flexible and highly readable.

3. Concatenating Array Elements

  • Using the join() method, you can efficiently convert array elements into a single string.
  • Because separators can be customized, it is especially useful for generating lists or CSV-formatted strings.

4. Performance and Optimization

  • For small-scale operations, using the plus operator or template literals is usually fine.
  • For large-scale string concatenation, using the join() method significantly improves performance.
  • When processing large amounts of data, avoid repeated string operations inside loops and use arrays instead for better efficiency.

5. Key Considerations and Best Practices

  • When handling numbers or undefined values, pay attention to type conversion and use safe default values to avoid errors.
  • Use template literals and comments to improve readability and maintainability.
  • Select the best approach for your specific scenario, and measure performance using optimization tools when needed.

Your Next Step

Now that you’ve learned the fundamentals, advanced techniques, and important precautions related to string concatenation in JavaScript, try practicing with the following exercises.

Practice Tasks

  1. Create a program that dynamically generates an HTML list (<ul><li>) using array data.
  2. Build a program that takes a user’s name and age as input, then generates a self-introduction message using template literals.
  3. Run a 100,000-iteration test and compare the performance of the plus operator and the join() method.

Final Thoughts

String concatenation is an essential operation in everyday JavaScript programming. Use the techniques in this article to improve both your development workflow and your learning.

Keep exploring more advanced string handling and performance tuning to take your JavaScript skills even further!

広告