Bisexual Pride

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>" +
"</div>"
);

Note: The string won’t truly span multiple lines. This is just a way of laying out HTML strings nicely in your editor. To make them truly span multiple lines, you would need to insert some newline characters (\n).

Expressions, variables, and function calls

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

Expressions

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.

Variables

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.