Emmanuel Akinfulubi

JavaScriptString

Template literals vs string concatenation in JavaScript

Beginner · 3 min read

Almost every program builds sentences out of pieces: a greeting with the user's name, a cart summary with a count, an error message with a file name. There are two ways to do it in JavaScript. The older way joins strings with +. The newer way, a template literal, writes the sentence with gaps that JavaScript fills in.

In this tutorial you will build 'Ada has 3 items' both ways, handle "1 item" versus "3 items", write text over two lines, and find the case where + gives a different answer depending on the order. You should know what variables, strings and numbers are.

Joining with +

When at least one side of + is a string, + joins the two into one string. A number on the other side is turned into text first:

JavaScript

console.log('Ada has ' + 3); // 'Ada has 3'

Template literals

A template literal is a string written between backtick characters instead of quotes. Inside it, ${ } marks a hole. Whatever expression you put in the hole is worked out, turned into text and dropped into the string:

JavaScript

const name = 'Ada';
console.log(`Hello, ${name}!`); // 'Hello, Ada!'

The backtick key is usually at the top left of the keyboard, next to the 1.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

31 Template literals against concatenation

easy

Build the sentence 'Ada has 3 items' twice: once with + and once with a template literal. Then find the case where + gives a different answer depending on the order.

Stuck? Three hints, smallest first
  1. 1. A hole in a template literal can hold any expression, including a conditional.
  2. 2. A template literal keeps a newline exactly as typed; a quoted string needs \n.
  3. 3. + adds when both sides are numbers and joins as soon as one side is a string.

Step 1: build the sentence with +

Step 1

const name = 'Ada';
const items = 3;
console.log(name + ' has ' + items + ' items'); // 'Ada has 3 items'

It works, but you have to watch the spaces inside each quoted piece. Forgetting one gives 'Ada has3 items'.

Step 2: build it with a template literal

Step 2

const name = 'Ada';
const items = 3;
console.log(`${name} has ${items} items`); // 'Ada has 3 items'

The sentence reads the way it will print. The spaces are where you see them.

Step 3: one item or many

"1 items" looks wrong. A hole can hold any expression, including a conditional, written condition ? a : b. It gives a when the condition is true and b otherwise:

Step 3

const name = 'Ada';
const items = 3;
const byTemplate = `${name} has ${items} item${items === 1 ? '' : 's'}`;
const byConcat = name + ' has ' + items + ' item' + (items === 1 ? '' : 's');
console.log(byTemplate);             // 'Ada has 3 items'
console.log(byTemplate === byConcat); // true

When items is 1 the hole is empty, so you get "1 item". The + version needs extra brackets around the conditional, or + would grab parts of it first. Both give the same text.

Step 4: text over two lines

A template literal keeps a line break exactly as you type it:

Step 4

const address = `12 Marina Road
Lagos`;
console.log(address.split('\n').length); // 2

'\n' is the newline character, so splitting on it counts the lines. With quotes you would have to write '12 Marina Road\nLagos'. One catch: any spaces at the start of the second line also become part of the string, so don't indent it to match your code.

Step 5: values in holes

Step 5

console.log(`n=${42}`);                    // 'n=42'
console.log(`v=${null}`);                  // 'v=null'
console.log(`${[1, 2, 3].join('-')}`);     // '1-2-3'

Numbers become their digits. null becomes the word 'null', so check for missing values before you print them. Any expression works, including method calls.

Step 6: the order trap with +

Here is where the two ways really differ:

Step 6

console.log(1 + 2 + 'x'); // '3x'
console.log('x' + 1 + 2); // 'x12'

JavaScript works through + from left to right. In the first line, 1 + 2 are both numbers, so they are added to make 3, and then 3 + 'x' joins to make '3x'. In the second line, 'x' + 1 is a string plus a number, so it joins to make 'x1', and then 'x1' + 2 joins again. The same three values give two different answers.

A hole in a template literal is worked out on its own, so this can't happen. If you want a sum in the middle of text, put it in a hole: `x${1 + 2}` is 'x3'.

The full solution

Here is the complete answer: the sentence built both ways, the plural, the two-line address and the order trap, each with a check. Press Run and compare the last line's two results.

The answer

const name = 'Ada';
const items = 3;

const byTemplate = `${name} has ${items} item${items === 1 ? '' : 's'}`;
const byConcat = name + ' has ' + items + ' item' + (items === 1 ? '' : 's');

// A template literal spans lines as typed, and the newline is part of the value.
const address = `12 Marina Road
Lagos`;

console.log('template   :', byTemplate);
console.log('concat     :', byConcat);
console.log('address has', address.split('\n').length, 'lines');
console.log("1 + 2 + 'x' :", 1 + 2 + 'x', "   'x' + 1 + 2 :", 'x' + 1 + 2);

Output


      
10 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 10 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

10 checks

test('the two forms produce the same text', byTemplate, byConcat);
test('and it reads properly', byTemplate, 'Ada has 3 items');
test('one item drops the s', `1 item${1 === 1 ? '' : 's'}`, '1 item');
test('a template literal keeps the newline you typed', address.split('\n').length, 2);
test('a quoted string needs the escape instead', 'a\nb'.split('\n').length, 2);
test('a number is converted inside a hole', `n=${42}`, 'n=42');
test('and so is null, as the word', `v=${null}`, 'v=null');
test('+ adds two numbers before it meets the string', 1 + 2 + 'x', '3x');
test('but joins from the start in the other order', 'x' + 1 + 2, 'x12');
test('a hole can hold any expression at all', `${[1, 2, 3].join('-')}`, '1-2-3');

'x' + 1 + 2 being 'x12' while 1 + 2 + 'x' is '3x' is not a quirk, it is left-to-right evaluation meeting one overloaded operator. It is also the strongest practical argument for template literals: a hole is evaluated on its own, so no amount of reordering changes what a number does.

The multi-line form has one catch worth knowing: the indentation of the continuation line is part of the string. A template literal indented to match the surrounding code carries those leading spaces into the value.

Common mistakes

  • Using quotes instead of backticks. '${name}' in single quotes prints the characters ${name} as they are. Holes only work between backticks.
  • Adding numbers next to text with +. 'Total: ' + 2 + 3 gives 'Total: 23'. Put the sum in brackets or in a hole.
  • Indenting the second line of a multi-line template. The spaces become part of the value.

Try it yourself

  1. Build 'Ada has 1 item' by changing only the value of items.
  2. Write price(n) that returns 'Total: 2500 naira' for price(2500) using a template literal.
  3. Predict '1' + 2 + 3 and 1 + 2 + '3', then run them to check.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.