JavaScriptFundamental (ES6), part 1
Arrow function syntax in JavaScript
6 Arrow functions and the concise body
easyWrite the same small function five ways: with and without parentheses round a single parameter, with no parameter, with a concise body and with a block body. Then show what a block body returns when you forget return.
Stuck? Three hints, smallest first
- 1. One parameter may drop its parentheses; zero parameters may not.
- 2. A concise body is an expression, and its value is returned for you.
- 3. The moment you write
{, you are writing statements, and statements return nothing on their own.
const double = (n) => n * 2;
const square = n => n * n; // parentheses optional for one parameter
const greet = () => 'welcome'; // but required when there are none
const sum = (a, b) => a + b;
const withBlock = (n) => { const t = n * 2; return t + 1; };
const forgotReturn = (n) => { n * 2; }; // a statement, so nothing comes back
for (const f of [double, square, greet, sum, withBlock, forgotReturn]) {
console.log((f.name + '(2, 3)').padEnd(20), '->', f(2, 3));
}
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a concise body returns its expression', double(21), 42);
test('one parameter needs no parentheses', square(5), 25);
test('no parameters still need a pair', greet(), 'welcome');
test('two parameters, one expression', sum(3, 4), 7);
test('a block body needs the word return', withBlock(2), 5);
test('without it the arrow gives undefined', forgotReturn(2), undefined);
test('length is the declared parameter count', sum.length, 2);
test('and the name is inferred from the variable it was assigned to', double.name, 'double');
The concise body is the reason arrows read well in a map or a filter: no function, no return, no braces. The cost is that adding one debugging line forces you to add braces and a return, and forgetting the second is the single most common arrow bug — the sixth assertion is what it looks like.
The inferred name is worth knowing about: an arrow is anonymous, but assigning it to a const gives it that name, which is what you see in a stack trace.