Knowing What an Arrow Returns
In this lesson, you grew a one-line arrow into a body and saw why an arrow with braces needs return.
- The translator’s formatters are one-line arrows. She wants each email amount rounded to the whole
euro first, as a named step that reads clearly, so
forEmailneeds a rounding line. Today’s fees are whole euros already, so the quote lines shouldn’t change. - In Python,
for_email()gainsrounded = round(amount), and thereturnline now formatsrounded. The script’s two lines print as before. - In JavaScript, the rounding line is a statement, and only a body can hold statements, so the
arrow gets braces. It uses
Math.round()in place of Python’sround(). On an exact half they differ: Python’sround()goes to the even whole number, andMath.round()goes up, to the larger number. - The format line moves into the body, now formatting
rounded, still with noreturn. The Bauer Legal line then readsBauer Legal: undefined, 2 working days, and nothing complains, so the email would go out to the client like that. The Nordwind line, from the one-lineforSheet, prints as before. - The format line still runs: it works out the euro text, then the text is thrown away, because nothing hands it back to the caller.
- The braced body ends without a
return, so the call givesundefined, where a Pythondefwould giveNone, and the template literal turns thatundefinedinto text. - Python splits the two forms the same way: a lambda returns its one expression with no
returnkeyword, like an arrow without braces, and adef’s body always needs itsreturnline, like an arrow with braces. Where the comparison stops: a lambda can’t grow a body, but an arrow can, so nothing reminds you to add areturnwhen it does. - One fix is
return euroFormat.format(rounded);. The other keeps the arrow one expression, with no braces:const forEmail = (amount) => euroFormat.format(Math.round(amount));. - Watch out when an arrow returns an object, like a fresh empty tally for each day’s quotes, which
Python’s
lambda: {"total": 0}returns as a dict. Without parentheses,() => { total: 0 }returnsundefined, because JavaScript reads the braces as a body.() => ({ total: 0 })returns the object, because the parentheses make JavaScript read the braces as a value.
Here’s the braced forEmail without its return, the version that returns undefined:
const forEmail = (amount) => {
const rounded = Math.round(amount);
euroFormat.format(rounded);
};