How to Join/Concatenate Strings in JavaScript

How to Join/Concatenate Strings in JavaScript

Introduction

Strings are one of the most common data type used in software - they represent strings of characters that we parse as words.

String concatenation is a pretty standard task, especially since we don't always deal with static strings. We oftentimes create strings dynamically, such as with ES6 Templates, or simply concatenate strings to form new ones.

If you'd like to read more about creating dynamic formatted strings - read our Guide to ES6 Templates/String Literals in Node.js!

In this tutorial, we'll take a look at how to join/append/concatenate strings in JavaScript.

Note: Strings are immutable, meaning they can't really be changed. Whenever you call a changing operation on a string, a copy is constructed with the changes applied and it's returned instead of the original one.

Concatenate With the + Operator

The easiest, and probably most intuitive appraoch to string concatenation is using the + operator:

console.log("hello " + "world");

Running this short piece of code results in:

hello world

It is possible to assign a string in memory to a reference variable, and reference the object instead of concatenating it directly:

let firstWord = "hello ";
let secondWord = "world";
let newWord = firstWord + secondWord;

This also results in:

hello world

Note: In most cases, you can reasonably replace a = and + with the shorthand +=, which lets you omit the reference to the first operand, which will be replaced with the variable you're assigning the result to.

Instead, you could be writing the short-hand version:

let word = "hello ";
word += "world";
console.log(word);

It's worth noting that other data types can be thrown into the mix as well, and whenever implicit conversion is possible - JavaScript will "match" the data types into strings.

For instance, integers are easily converted to strings so if you try concatenating an integer onto a string - the integer is converted before being appended. A string may not be converted into an integer at all times - such as when it doesn't represent a number or has odd formatting, so generally, it's easier to convert to a string, than from a string:

var str = "hello";
var int = 21;
var boolean = true;

console.log(str+int);
console.log(str+boolean)

This results in both the boolean and integer being converted into string representations and then appended to the "hello" string:

hello21
hellotrue

String.prototype.concat()

The concat() method was created specifically for this task - to concatenate strings. It can be invoked over any string, and accepts another string to be concatenated to the calling one.

In a sense, it's similar to using the short-hand += operator:

let string1 = "Java";
let string2 = "Script";

console.log(string1.concat(string2));

This results in:

JavaScript

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Additionally, you can specify a delimiter as the first argument, which is then added in-between all of the concatenated strings:

let string1 = "Java";
let string2 = "Script";

console.log(string1.concat(", ", string2));

This results in:

Java, Script

Array.prototype.join()

The join() method of the Array class is used to join the elements of an array into a string, with a default delimiter of a comma (,).

This allows us to deal with a larger number of strings in a much more concise way, and it's not unheard of to read a file into an array, or to work with an array of strings you'd like to join together.

If you don't pass in any arguments into the method - the default value will be used to delimit the newly joined strings. Let's pass in an empty string to skip that and just join them similar to what we've seen before:

let elements = ["JavaScript", "HTML", "CSS"];
console.log(elements.join(""));

This results in:

JavaScriptHTMLCSS

Which Approach to Use?

It's advised to prefer the concat() function instead of the + operator, due to performance benefits. However, this doesn't actually always hold and takes in several assumptions into mind.

First of all - the number of strings you're concatenating plays a role in this, as well as other factors you might not even be aware of. Let's benchmark the concat() method as well as the + operator:

console.time('Concatenating with Operator');
concatWithOperator();
console.timeEnd('Concatenating with Operator');

console.time('Concatenating with Function');
concatWithFunction();
console.timeEnd('Concatenating with Function');

function concatWithOperator() {
    let result = "";
    for (let i = 0; i < 10000; i++) {
      result += i;
    }
}

function concatWithFunction() {
    let result = "";
    for (let i = 0; i < 10000; i++) {
      result = result.concat(i);
    }
}

This results in:

Concatenating with Operator: 3.232ms
Concatenating with Function: 1.509ms

But wait, let's switch the environment and run this on a different machine:

Concatenating with Operator: 1.985ms
Concatenating with Function: 1.990ms

And let's run that on the same machine again:

Concatenating with Operator: 2.030ms
Concatenating with Function: 0.934ms

The execution times vary wildly (although, all of them are acceptable in speed). It's also worth noting the official statement from MDN, regarding the performance benefits:

It is strongly recommended that the assignment operators (+, +=) are used instead of the concat() method.

Which might seem odd, given the fact that concat() outperforms the operators in the tests or at worst is the same speed. What gives? Well, benchmarking code like this isn't as easy as simply running it and observing the results.

Your browser, its version, as well as the optimizer it uses may vary from machine to machine, and properties like those really impact the performance. For instance, we've used different strings in the concatenation, the ones generated from iteration. If we were to use the same string, an optimizer such as Google's V8 would further optimize the usage of the string.

Test and verify your own code instead of taking advice at face value. Not all machines and environments are the same, and what works great on one, might not work great on another. Take this into consideration when creating applications as well.

Conclusion

We've taken a look at how to concatenate strings in JavaScript using the + operator, the join() method of the Arrays class as well as the concat() method of the String class.

We've taken a look at the official stance and ran our own tests to see which approach is the most performant - and as usual, it depends on various factors.

Last Updated: November 23rd, 2021
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Want a remote job?

    Prepping for an interview?

    • Improve your skills by solving one coding problem every day
    • Get the solutions the next morning via email
    • Practice on actual problems asked by top companies, like:
     
     
     

    Getting Started with AWS in Node.js

    Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

    © 2013-2021 Stack Abuse. All rights reserved.