Hone

Lessons · TypeScript · template literals

Putting values into text

A template literal `...${value}...` drops a value into a string where the braces are.

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

Every label, message, log line and filename is text with values in it.

How to think about it

Where do the values go, and how should each look? Write the sentence, replace each value with ${name}, and format numbers first with toFixed or toLocaleString.

Worked example

const name = "Ada", total = 1234.5;
Two values.
`${name}: ${total.toFixed(2)}`;
Ada: 1234.50.
`${name}: ${total.toLocaleString()}`;
Ada: 1,234.5 in an English locale.

Your turn

Show a percentage with one decimal.

const line = `${(share * 100).(1)}%`;

The trap

Using plain quotes: 'Hello ${name}' prints the braces literally. Template literals need backticks.

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