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")