Module 23: Functions and Scope
Arrow functions in depth
🏠The everyday picture
A formal letter and a text message can say the same thing. Arrow functions are the short form, and they're everywhere in modern code.
📘What it really is
- The full and short forms of the same function:
function square(n) { return n * n; }
const square = (n) => { return n * n; };
const square = n => n * n;
- Rules for the short form:
- one parameter: brackets optional (
n => ...); none or several: brackets needed (() => ...,(a, b) => ...); - one expression without curly braces: it's returned automatically;
-
with curly braces, you must write
return. -
Trap: returning an object needs round brackets:
() => ({ total: 0 }). Without them, the braces are read as a code block and nothing is returned. -
Default parameters:
(price, rate = 0.18) => price * (1 + rate). - Rest parameters collect any number of arguments into an array:
(...numbers) => numbers.length. - Arrow functions also handle
thisdifferently from normal functions, which matters with classes (Module 29).
🖱️Try it
Rewrite addGst and addDelivery as one-line arrow functions. Write sumAll(...numbers) that adds any number
of arguments, and makeLine(name, qty) that returns an object { name, qty } in one line. Test each.
✅Quick check
const f = () => { total: 0 }; returns undefined. Why?
Show the answer
The braces are treated as a code block, not an object. Write () => ({ total: 0 }).
Does n => { n * 2 } return anything?
Show the answer
No. With curly braces you need return.
