Hone

Lessons · TypeScript · joining two strings

Joining text

+ between strings joins them, and a non-string on either side is turned into text first. A template literal, `Total: ${x}`, does the same more readably.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Messages, labels, URLs, HTML: most of what a web page shows is text built from pieces, and the template literal is the tool that keeps it readable.

How to think about it

Reach for a template literal whenever you mix text and values; the ${} does any maths inside it before joining. Keep + for two plain strings.

Worked example

console.log("a" + "b");
ab.
console.log("Total: " + 12);
Total: 12: the number becomes text.
console.log(`Total: ${12 + 3}`);
Total: 15: a template literal does the maths inside ${}.
console.log("Total: " + 12 + 3);
Total: 123: + runs left to right and turns to text at the first string.

Your turn

Greet by name with a template.

const msg = `Hello, ${}`;

The trap

'Total: ' + 12 + 3 is 'Total: 123'. Parenthesise the sum or use a template literal when text and maths mix.

Practise joining two strings on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.