concat()
ES3+Concatenates the string arguments to the calling string.
Syntax
string.concat(str1, str2, ...)Parameters
strings string Strings to concatenate
Return Value
A new string containing the combined text
Examples
const str = 'Hello';
console.log(str.concat(' ', 'World')); 📌 When to Use
Use concat() when you need to join multiple strings programmatically from an array or when compatibility with older code patterns is required. For most cases, template literals or the + operator are preferred for their readability.
⚠️ Common Mistakes
Using concat() for simple string joining when template literals are more readable: use `${a}${b}` instead of a.concat(b).
Forgetting that concat() converts non-string arguments to strings, which might cause unexpected results with objects.
Using concat() in a loop for building strings when array.join() or template literals would be more efficient.
✅ Best Practices
Prefer template literals for string interpolation and simple concatenation: `Hello, ${name}!` is clearer than "Hello, ".concat(name, "!").
Use array.join() for joining multiple strings with a separator, which is often clearer than multiple concat calls.
concat() can be useful with spread operator for dynamic arguments: "".concat(...stringArray).
⚡ Performance Notes
concat() has similar performance to the + operator in modern engines. However, for building strings in loops, using an array and join() is typically faster as it avoids creating many intermediate strings. Template literals are optimized by engines and often perform best for known concatenations.
🌍 Real World Example
Dynamic String Building
While template literals are preferred for most cases, concat() can be useful when building strings dynamically from arrays or when working with older codebases.
// Modern approach: Template literals (preferred)
const name = 'World';
const greeting = `Hello, ${name}!`;
console.log(greeting); // 'Hello, World!'
// Using concat for dynamic parts from array
const parts = ['Hello', ' ', 'World', '!'];
const message = ''.concat(...parts);
console.log(message); // 'Hello World!'
// Comparison of approaches for building strings
function buildQueryString(params) {
// Using concat (less preferred)
// let query = '';
// Object.entries(params).forEach(([key, value]) => {
// query = query.concat(query ? '&' : '?', key, '=', value);
// });
// Better: Using array and join
const pairs = Object.entries(params)
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`);
return pairs.length > 0 ? '?' + pairs.join('&') : '';
}
console.log(buildQueryString({ name: 'John', age: 30 }));
// '?name=John&age=30'
// When concat is appropriate: programmatic string assembly
function buildPath(...segments) {
return segments
.filter(s => s && s.length > 0)
.map(s => s.replace(/^\/+|\/+$/g, ''))
.reduce((path, segment) => path.concat('/', segment), '');
}
console.log(buildPath('api', 'v1', 'users')); // '/api/v1/users'