Building Strings With Template Literals
In this lesson, you ported the crew’s two f-string lines about Harbor Square to template literals, and found out what happens to a format spec on the way.
- Where Python writes an f-string, JavaScript writes a template literal: the string goes in
backticks, with no
fin front, and each value goes in a${...}placeholder. - A placeholder holds one expression, as an f-string’s braces do, such as
${name}or${fill.toFixed(0)}. Unlike an f-string, it takes nothing after the expression. - Template literals have no format spec. A spec carried over from Python, as in
${fill:.0f}, stops the whole file withSyntaxError: Missing } in template expression, and none of the file runs. - To round a number, call
.toFixed()with the number of decimals you want.fill.toFixed(0)gives the text93. It does only the rounding part of a spec, and a tie, a number exactly halfway between two whole numbers, can round the other way:(2.5).toFixed(0)gives3, where Python’sf"{2.5:.0f}"gives2, because Python rounds a tie to the even one of the two and.toFixed()rounds it up. Number formatting comes later. - In ordinary quotes,
${name}is plain text, as{name}is in a Python string without thef: the backticks play thef’s role.
Here’s the crew’s Python script:
name = "Harbor Square"
bikes = 14
slots = 1
fill = bikes / (bikes + slots) * 100
print(f"{name}: {bikes} bikes")
print(f"{name}: {fill:.0f}% full")
The port in dock-report.js carries the format spec across on its last line:
const name = "Harbor Square";
const bikes = 14;
const slots = 1;
const fill = bikes / (bikes + slots) * 100;
console.log(`${name}: ${bikes} bikes`);
console.log(`${name}: ${fill:.0f}% full`);
Run with node dock-report.js, it prints nothing, not even the first line: JavaScript can’t read
the file, so none of it runs. The error’s carets point at fill, and its message names the
problem:
SyntaxError: Missing } in template expression
The carets mark where the trouble starts: the placeholder read fill as its expression, then
found a colon where it expected the closing brace.
Here’s the port with the number rounded inside the placeholder:
const name = "Harbor Square";
const bikes = 14;
const slots = 1;
const fill = bikes / (bikes + slots) * 100;
console.log(`${name}: ${bikes} bikes`);
console.log(`${name}: ${fill.toFixed(0)}% full`);
It prints what the Python script prints:
Harbor Square: 14 bikes
Harbor Square: 93% full
Next up: Exercise: Print a Dock’s Fill Rate, where you work out another dock’s fill rate and print it, rounded to a whole percent.