String concatenation in vanilla JS

ECMAScript 2015 (also known as ES2015 or ES6) gave us template literals. They’re a really convenient way to create multi-line strings and/or strings that contain data. But they have no IE support and they can’t be polyfilled. The old-school way is to use string concatenation.

Multi-line strings

You can use string concatenation to create multi-line strings:

var html = (
  "<div>" +
    "<p>Hello, World!</p>" +

Notice that I’m using the + operator to concatenate the strings.

The parentheses are optional, but I think they make it nice and readable.

Expressions, variables, and function calls

You can also concatenate expressions, variables, and function calls.


var fact = "Fifteen is the same as " + (5 + 10);

The parentheses are necessary here. Otherwise, the result would be "Fifteen is the same as 510". This is due to type coercion.


var name = "Katie";

var greeting = "Hello, " + name + "!";

Function calls

var greeting;

var user = {
  firstName: "Jocko",
  lastName: "Willink"

function getFullName (person) {
  return person.firstName + " " + person.lastName;

greeting = "Hello, " + getFullName(user) + "!";

Wrapping up

Hopefully these examples are enough to get your feet wet with string concatenation. It’s just a fancy term for “joining strings together”.

For more information, check out Concatenating strings in the MDN Web Docs.

If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!