Skip to main content

JavaScript Strings

JavaScript String Concatenation

Written by Published

Concatenation joins strings together into a longer one.

The plus operator is the usual way.

Template literals are usually clearer once more than two pieces are involved.

Example

Example

javascript

const first = "Ada";
const last = "Lovelace";

console.log(first + " " + last);

The space has to be added deliberately.

Ways to Join

+ joins two strings.

+= adds to the end of an existing one.

concat and template literals do the same job.

Syntax

Syntax

javascript

a + b;
`${a} ${b}`;

A number joined to a string becomes a string.

Building Up in a Loop

+= is the usual way to build a string piece by piece.

Example

Example

javascript

const names = ["Ada", "Grace", "Alan"];
let text = "";

for (const name of names) {
  text += name + " ";
}

console.log(text.trim());

join would be simpler here, and faster.

Numbers Become Text

This is the coercion rule, and it catches everyone once.

Example

Example

javascript

console.log("Total: " + 5 + 3);
console.log("Total: " + (5 + 3));

Brackets make the addition happen first.

The concat Method

It works but is rarely used, because + is shorter.

Example

Example

javascript

const a = "Hello";

console.log(a.concat(" ", "world"));

It accepts as many arguments as you like.

Repeating

repeat saves writing a loop.

Example

Example

javascript

console.log("ab".repeat(3));
console.log("-".repeat(10));

Useful for simple separators in console output.

Prefer Template Literals

Once there are several pieces, backticks read much better.

Example

Example

javascript

const name = "Ada";
const age = 36;

console.log("Name: " + name + ", age: " + age);
console.log(`Name: ${name}, age: ${age}`);

Both produce the same string; the second is harder to get wrong.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript String Concatenation</title>
</head>
<body>

  <h1>String Concatenation</h1>

  <p id="out"></p>

  <script>
    const first = "Ada";
    const last = "Lovelace";
    const names = ["Ada", "Grace", "Alan"];

    document.getElementById("out").innerHTML =
      "Joined: " + first + " " + last +
      "<br>Template: " + `${first} ${last}` +
      "<br>From array: " + names.join(", ") +
      "<br>Repeated: " + "-".repeat(20);
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try the number trap:

Add "Total: " + 5 + 3 and see what you get.

Important Points

  • + joins strings together.
  • += adds to an existing string.
  • A number joined to a string becomes a string.
  • repeat repeats a string.
  • Template literals are clearer for several pieces.

Conclusion

Joining strings is simple, but the number coercion trap is real.

join is better than a loop when you already have an array.

Template literals are the modern default.