JavaScript String Concatenation: 5 Best Methods (+ Performance Tips & Common Errors)

目次

1. JavaScript String Concatenation Basics and Why It Matters

What string concatenation means in JavaScript

In JavaScript, string concatenation is an essential technique for dynamically combining text within your program. For example, you might merge user input into a single sentence, or generate HTML dynamically—both are common use cases.

String concatenation is not just about “joining text.” It can also affect code readability and performance, so choosing the right approach for the situation is important.

Common use cases for string concatenation

Below are typical scenarios where string concatenation is used.

1. Combining a user name and a greeting

let userName = 'Sato';
let greeting = 'Hello, ' + userName + '!';
console.log(greeting);
// Output: Hello, Sato!

2. Dynamically generating an HTML element

let name = 'Tanaka';
let age = 25;
let profile = '<p>' + name + '\'s age is ' + age + '.</p>';
console.log(profile);
// Output: <p>Tanaka's age is 25.</p>

Benefits of learning string concatenation

  1. Efficient data handling: By building text dynamically, you can simplify code for complex UIs and data processing.
  2. Better maintainability: Using template literals or built-in methods can improve readability and maintainability.
  3. Performance optimization: When handling large amounts of data, choosing the right method can significantly improve execution speed.

2. 5 Ways to Concatenate Strings in JavaScript (with Code Examples)

2.1. Plus operator (+) and addition assignment (+=)

Basic usage

The plus operator (+) is the simplest and most intuitive way to concatenate strings. It’s beginner-friendly and widely used because it keeps code easy to read.
The addition assignment operator (+=) is convenient when you want to append text to an existing string.

Code examples

Using the plus operator:

let greeting = 'Hello';
let name = 'Tanaka';
let message = greeting + ', ' + name + '!';
console.log(message);
// Output: Hello, Tanaka!

Using addition assignment (+=):

let message = 'Hello';
message += ', Sato!';
console.log(message);
// Output: Hello, Sato!

Things to watch out for

  1. Type coercion pitfalls: When you concatenate numbers and strings, JavaScript performs implicit type coercion, which may lead to unexpected results. Example:
   let result = 10 + '20';
   console.log(result); // Output: "1020" (string)

Workaround: If you need numeric addition, use explicit type conversion.

Example:

   let result = 10 + Number('20');
   console.log(result); // Output: 30
  1. Performance limitations: If you repeatedly concatenate strings in a large loop, the plus operator can become slow. For large datasets, consider methods like join(), explained below.

2.2. concat() method

Basic usage

The concat() method is used to combine multiple strings. Compared with the plus operator, it’s a more “object-oriented” approach. You can pass multiple arguments and concatenate them all at once.

Code example

let str1 = 'Hello';
let str2 = 'World';
let result = str1.concat(', ', str2, '!');
console.log(result);
// Output: Hello, World!

Things to watch out for

  1. Not for arrays: concat() here refers to the string method (not array concatenation). For joining array elements into a string, use join() below.
  2. Performance: It works fine for small data, but for large-scale processing, join() is usually faster.

2.3. Template literals (using backticks)

Basic usage

Template literals are a modern approach where you wrap the string in backticks (`). Because you can embed variables and expressions using ${}, they’re ideal for complex string building and multiline text.

Code example

let name = 'Yamada';
let age = 30;
let greeting = `Hello, ${name}. You are ${age} years old.`;
console.log(greeting);
// Output: Hello, Yamada. You are 30 years old.

Advantages

  1. Improved readability: Clean and easy to read, even with complex structures.
  2. Easier handling of newlines and special characters:
   let multiline = `This is
   a multi-line
   text.`;
   console.log(multiline);
   // Output:
   // This is
   // a multi-line
   // text.

Things to watch out for

  • Compatibility with older browsers: Internet Explorer does not support template literals, so they can’t be used in legacy environments.

2.4. join() method (joining array elements)

Basic usage

If you want to convert array elements into a single string, join() is the best option. You can specify any delimiter, which makes it great for list-style data processing.

Code example

let words = ['Red', 'Blue', 'Green'];
let sentence = words.join(', ');
console.log(sentence);
// Output: Red, Blue, Green

Advanced: To generate multi-line CSV data, you can write:

let rows = [
  ['Name', 'Age', 'City'],
  ['Sato', 25, 'Tokyo'],
  ['Suzuki', 30, 'Osaka']
];

let csvData = rows.map(row => row.join(',')).join('\n');
console.log(csvData);
/* Output:
Name,Age,City
Sato,25,Tokyo
Suzuki,30,Osaka
*/

Advantages

  1. Best for large datasets: Using arrays helps make large-scale processing more efficient.
  2. Custom delimiters: You can freely use commas, spaces, newline characters, and more.

2.5. Advanced techniques

reduce() for custom concatenation

If you want to perform more complex, dynamic concatenation, reduce() is useful.

Example: Join array elements with formatting

let data = ['JavaScript', 'Strings', 'Concatenation'];
let result = data.reduce((acc, curr) => acc + ' - ' + curr);
console.log(result);
// Output: JavaScript - Strings - Concatenation

Summary

In this section, we introduced five ways to concatenate strings in JavaScript with practical examples. We covered everything from the simple plus operator to template literals, the efficient join() method, and the more advanced reduce() approach.

3. Performance Comparison and How to Choose the Best Method

Why performance comparison matters

There are multiple ways to concatenate strings, and performance can vary significantly depending on the situation. In particular, if you repeatedly concatenate a large number of strings, choosing the wrong approach can slow down your code.

In this section, we compare the performance of common methods and provide selection criteria based on your use case.

Methods compared

  1. Plus operator (+)
  2. concat() method
  3. Template literals
  4. join() method (using arrays)

Performance comparison results

The following test compares execution time when concatenating strings in a 100,000-iteration loop.

MethodExecution Time (ms)Best Use Case
Plus operator (+)120Small datasets
concat() method150Small datasets
Template literals110Small to medium datasets
join() method85Large datasets (recommended)

Characteristics and usage

Plus operator (+)

Characteristics:

  • Simple and beginner-friendly.
  • Good for small datasets.
  • May slow down when used repeatedly in large loops.

Use case:
Short string concatenation and temporary processing.

concat() method

Characteristics:

  • A more object-oriented approach.
  • Convenient, but not ideal for large-scale processing.

Use case:
Concatenating a small number of strings efficiently.

Template literals

Characteristics:

  • Highly readable and flexible.
  • Ideal for complex strings that include variables and numeric values.

Use case:
Medium-scale processing, HTML generation, and dynamic content creation.

join() method

Characteristics:

  • An efficient approach that uses arrays.
  • High performance and well-suited to large datasets.

Use case:
Generating CSV data and consolidating large log datasets.

How to choose the best method

1. For small datasets:

Recommended:

  • Plus operator (+)
  • Template literals

2. For medium datasets:

Recommended:

  • Template literals
  • concat() method

3. For large datasets:

Recommended:

  • join() method
  • Also consider array-based reduce() depending on your formatting needs.

Practical example: Large-scale processing

Below is an example of using arrays to efficiently concatenate large datasets.

let words = [];
for (let i = 0; i < 100000; i++) {
  words.push('String' + i);
}
let result = words.join('');
console.log(result);
// Example output: "String0String1String2...String99999"

Summary

  • For small datasets, simple methods (+, template literals) are a good fit.
  • For large datasets, join() is generally the most efficient approach.

4. Common Errors and Debugging Tips

What kinds of errors commonly happen with string concatenation?

String concatenation in JavaScript may look simple, but it can produce unexpected results or errors. In this section, we’ll explain common issues, their causes, and practical fixes.

4.1. Type coercion issues

Example

In JavaScript, concatenating different data types triggers implicit type coercion, which can lead to unexpected results.

Code example:

let num = 10;
let str = '20';
let result = num + str;
console.log(result);
// Output: "1020" (concatenated as a string)

Cause

When the + operator handles both numbers and strings, it prioritizes string conversion. As a result, even if you expect numeric addition, you may end up with string concatenation.

Solution

Use explicit type conversion:

let num = 10;
let str = '20';
let result = num + Number(str);
console.log(result);
// Output: 30

4.2. Concatenating undefined or null

Example

Concatenating an uninitialized variable or null can produce surprising output.

Code example:

let name;
let message = 'Hello, ' + name + '!';
console.log(message);
// Output: "Hello, undefined!"

Cause

  • Uninitialized variables have the value undefined, so that value gets concatenated as-is.
  • The same type of issue can occur when values returned from a database or form are null.

Solution

Set a default value:

let name = name || 'Guest';
let message = 'Hello, ' + name + '!';
console.log(message);
// Output: "Hello, Guest!"

Use a template literal with a fallback:

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

4.3. Mixing numeric operations and string concatenation

Example

When numeric operations and string concatenation are mixed, the final result may not match what you intended.

Code example:

let a = 10;
let b = 20;
let result = a + b + ' yen';
console.log(result);
// Output: "30 yen" (correct)

let result2 = a + ' yen' + b;
console.log(result2);
// Output: "10 yen20" (unexpected)

Cause

Because of operator evaluation order, once string concatenation happens, the remaining parts are treated as strings as well.

Solution

Use parentheses to clarify evaluation order:

let result = (10 + 20) + ' yen';
console.log(result);
// Output: "30 yen"

4.4. Performance slowdown with large-scale processing

Example

If you repeatedly concatenate large amounts of text with + or +=, performance can degrade significantly.

Code example:

let str = '';
for (let i = 0; i < 100000; i++) {
  str += 'String';
}
console.log(str);

Execution time: It can take several seconds in some environments.

Solution

Use an array and join():

let arr = [];
for (let i = 0; i < 100000; i++) {
  arr.push('String');
}
let str = arr.join('');
console.log(str);

Result: Finishes much faster in most cases.

4.5. Incorrect use of escape characters

Example

When dealing with strings that include special characters (like quotes), incorrect escaping can cause errors.

Code example:

let message = 'This is a "JavaScript" example.';
console.log(message);
// Output: This is a "JavaScript" example.

let errorMessage = 'This is a "JavaScript example.';
console.log(errorMessage);
// Error: string is not properly closed

Solution

Use proper escaping (or choose the other quote type):

let message = "This is a \"JavaScript\" example.";
console.log(message);
// Output: This is a "JavaScript" example.

Use a template literal:

let message = `This is a "JavaScript" example.`;
console.log(message);
// Output: This is a "JavaScript" example.

Summary

In this section, we covered common string-concatenation issues and how to fix them, including type coercion, handling undefined/null, mixing numbers and strings, performance pitfalls, and escaping quotes correctly. By applying these patterns, you can write safer and more efficient JavaScript.

5. Practical Techniques and Best Practices

5.1. Dynamic string generation with template literals

Example 1: Displaying user information

You can build clean, readable sentences that include dynamic data.

let user = {
  name: 'Sato',
  age: 25,
  city: 'Tokyo'
};

let message = `${user.name} is ${user.age} years old and lives in ${user.city}.`;
console.log(message);
// Output: Sato is 25 years old and lives in Tokyo.

Example 2: Dynamically generating an HTML template

Template literals are especially useful when generating HTML strings.

let title = 'JavaScript Basics';
let description = 'This page explains JavaScript string concatenation.';

let html = `
  <div class="article">
    <h1>${title}</h1>
    <p>${description}</p>
  </div>
`;

console.log(html);

Tip:
Because template literals handle multiline strings and variable interpolation well, they improve readability and maintainability.

5.2. Efficient string concatenation using arrays

Example 1: Generating CSV data

Using arrays with join() makes it easy to produce comma-separated data efficiently.

let data = ['Name', 'Age', 'City'];
let csv = data.join(',');
console.log(csv);
// Output: Name,Age,City

Advanced: For multi-line CSV data:

let rows = [
  ['Name', 'Age', 'City'],
  ['Sato', 25, 'Tokyo'],
  ['Suzuki', 30, 'Osaka']
];

let csvData = rows.map(row => row.join(',')).join('\n');
console.log(csvData);
/* Output:
Name,Age,City
Sato,25,Tokyo
Suzuki,30,Osaka
*/

Example 2: Creating multi-line text

This approach is also useful when combining sentences into a multi-line block.

let sentences = [
  'JavaScript is a popular programming language.',
  'String manipulation is one of its core features.',
  'This article explains string concatenation in detail.'
];

let text = sentences.join('\n');
console.log(text);
/* Output:
JavaScript is a popular programming language.
String manipulation is one of its core features.
This article explains string concatenation in detail.
*/

5.3. Dynamic processing with conditionals and loops

Example 1: Message generation with a conditional

Show different messages depending on a user’s state.

let userName = 'Sato';
let isLoggedIn = true;

let message = isLoggedIn
  ? `Welcome, ${userName}!`
  : 'Please log in.';
console.log(message);
// Output: Welcome, Sato!

Example 2: Building an HTML list using a loop

Here’s an example of generating a list from multiple items.

let items = ['Apple', 'Banana', 'Orange'];

let list = '<ul>\n';
items.forEach(item => {
  list += `  <li>${item}</li>\n`;
});
list += '</ul>';

console.log(list);
/* Output:
<ul>
  <li>Apple</li>
  <li>Banana</li>
  <li>Orange</li>
</ul>
*/

5.4. Best practices

1. Prioritize readability

Even for complex logic, template literals can keep your code easier to read.

Example:

const orderSummary = `
  Order Summary:
  Product: ${product.name}
  Quantity: ${product.quantity}
  Total: ${product.price * product.quantity} yen
`;

2. Consider performance

For large datasets, prefer join() or array-based approaches to keep performance stable.

3. Use type checks and error handling

To avoid unexpected type errors, set defaults and convert types explicitly when needed.

Example:

let name = userName || 'Guest';
let message = `Hello, ${name}!`;

4. Verify compatibility with older browsers

If you use template literals, consider transpiling (e.g., Babel) or providing alternatives for older browsers.

Summary

In this section, we introduced practical examples using template literals and join(), plus patterns with conditionals and loops for flexible string generation. These techniques can improve both maintainability and performance in real projects.

6. FAQ | Common Questions About JavaScript String Concatenation

Q1. How can I concatenate strings with line breaks in JavaScript?

A:
To concatenate strings with line breaks, you can either use special characters (escape sequences) or use template literals.

Example 1: Using escape sequences

let text = 'JavaScript\nString Concatenation\nLine Break Example';
console.log(text);
/* Output:
JavaScript
String Concatenation
Line Break Example
*/

Example 2: Using template literals

let text = `JavaScript
String Concatenation
Line Break Example`;
console.log(text);
/* Output:
JavaScript
String Concatenation
Line Break Example
*/

Tip: Template literals allow you to write multi-line text directly, which is especially convenient for longer content.

Q2. What should I watch out for when concatenating numbers and strings?

A:
In JavaScript, concatenating numbers and strings triggers implicit type coercion, which may produce unexpected results.

Example:

let result = 10 + '20';
console.log(result);
// Output: "1020" (concatenated as a string)

Solution: Use explicit type conversion to ensure correct calculations.

Example:

let result = 10 + Number('20');
console.log(result);
// Output: 30

Q3. Which string concatenation method has the best performance?

A:
The best method depends on the size of your data.

  • Small datasets: + operator or template literals are simple and efficient.
  • Large datasets: join() method is typically the fastest.

Example: Large-scale processing

let words = [];
for (let i = 0; i < 100000; i++) {
  words.push('String' + i);
}
let result = words.join('');
console.log(result);

This approach improves performance when handling large amounts of data.

Q4. How can I use spaces or commas as delimiters?

A:
Using an array with join() allows you to specify any delimiter.

Example: Space-separated

let words = ['JavaScript', 'Strings', 'Concatenation'];
let sentence = words.join(' ');
console.log(sentence);
// Output: JavaScript Strings Concatenation

Example: Comma-separated

let csv = ['Name', 'Age', 'Address'].join(',');
console.log(csv);
// Output: Name,Age,Address

Tip: join() is especially useful for large datasets or list-style data processing.

Q5. How can I prevent errors when concatenating strings?

A:
Below are common errors and how to avoid them.

1. Concatenating an undefined variable:

let name;
let message = 'Hello, ' + name + '!';
console.log(message);
// Output: Hello, undefined!

Workaround:

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

2. Mixing numbers and strings:

let result = 10 + '20';
console.log(result);
// Output: "1020"

Workaround:

let result = 10 + Number('20');
console.log(result);
// Output: 30

Q6. Can template literals be used in Internet Explorer?

A:
No. Template literals were introduced in ES6 (ECMAScript 2015), and Internet Explorer does not support them.

Solution:
If you need to support older browsers, use the traditional + operator.

Example:

let name = 'Tanaka';
let greeting = 'Hello, ' + name + '!';

Recommendation: Consider using modern browsers or a transpiler like Babel.

Q7. How can I concatenate a string in reverse order?

A:
To reverse a string, use array methods.

Example:

let str = 'JavaScript';
let reversed = str.split('').reverse().join('');
console.log(reversed);
// Output: tpircSavaJ

Explanation:

  1. split(''): Split the string into an array of characters.
  2. reverse(): Reverse the array elements.
  3. join(''): Join the array back into a string.

Q8. Can I concatenate strings that include line breaks or special characters?

A:
Yes. You can use escape sequences for special characters.

Example:

let text = 'This is\na JavaScript\nstring concatenation example.';
console.log(text);
/* Output:
This is
a JavaScript
string concatenation example.
*/

With template literals, you can write it directly as multi-line text:

let text = `This is
a JavaScript
string concatenation example.`;
console.log(text);

7. Conclusion

Key takeaways from this article

We covered JavaScript string concatenation from the basics to advanced techniques. Below is a summary of the main points.

  1. String concatenation basics and importance:
  • Concatenating strings is essential in many JavaScript programs.
  1. 5 main ways to concatenate strings:
  • Plus operator (+): Simple and beginner-friendly.
  • concat() method: More object-oriented, but not ideal for large datasets.
  • Template literals: A modern approach with excellent readability and flexibility.
  • join() method: Efficient for large datasets using arrays.
  • reduce() method: An advanced technique for dynamic concatenation.
  1. Performance comparison and selection criteria:
  • For small datasets, + and template literals are usually best.
  • For large datasets, join() is the most efficient choice.
  1. Common errors and solutions:
  • Prevent issues by handling type coercion and undefined values properly.
  1. Practical techniques and best practices:
  • Use template literals and loops to build dynamic strings and HTML efficiently.
  • Generating CSV data and multi-line text is also straightforward.
  1. FAQ section:
  • We answered common questions to make this guide more useful in real development.

Final notes

1. Share this article to spread knowledge!

If you found this article helpful, please share it on social media. Sharing with coworkers and programming friends is a great way to learn together.

2. Start practicing with code!

Copy and run the sample code from this article, and try using it in your own projects. If you have questions, feel free to leave a comment or ask!

Support your future learning

To further improve your programming skills, consider using the following learning resources.

Wrapping up

Through this article, you should now have a stronger understanding of JavaScript string concatenation and practical techniques you can apply immediately. Keep improving your skills and aim to write code that is more efficient, maintainable, and easy to understand.

We’ll continue sharing useful content, so please bookmark this site and check back regularly!

広告