You’ve printed Harbor Square’s 93% full before, by writing bikes / (bikes + slots) * 100 straight into a template literal. Now the crew lead wants that fill rate on every dock’s line, and describeDock() already takes all three arguments. Pasting the formula into every line that shows it would repeat it, so it belongs in one small function.
The fill rate is one line of arithmetic. A full function declaration would work, but JavaScript has a shorter form for small functions, and you’ll see it in nearly every JavaScript file. In this lesson, you’ll write the fill rate in that form and learn when to reach for it.
Write the Fill Rate as an Arrow
In the Python script, the fill rate is a small helper of its own, so the formula lives in one place:
def fill_rate(bikes, slots):
return bikes / (bikes + slots) * 100
print(f"Harbor Square: {fill_rate(14, 1):.0f}% full")
The JavaScript port can keep it as a function declaration with function, braces, and return. For a one-line formula, though, a JavaScript developer would usually write an arrow function, a function made of a parameter list, the => arrow, and a body:
const fillRate = (bikes, slots) => bikes / (bikes + slots) * 100;
console.log(`Harbor Square: ${fillRate(14, 1).toFixed(0)}% full`);