Single-line and block body
Learn the difference between single-line implicit return and block body arrows.
Single-line concise body
When an arrow body is a single expression, you write it without curly braces and without the return keyword. The value is returned automatically.
const add = (a, b) => a + b;
const greet = (name) => `Hello, ${name}`;This style is called a concise body. The expression is evaluated and the result goes back to the caller. When you need a loop or several steps, this form is not enough.
Block body and return
When you need several statements or an explicit return flow, use a block body with curly braces. In that case return is required; otherwise nothing comes back.
const priceWithTax = (price, rate) => {
const tax = price * rate;
return price + tax;
};Implicit return does not work in a block body. If you forget the return line, the function returns undefined and the result is lost.
Exercise Write a block body arrow
Write an arrow function named formatPrice. Use a block body; first build the text with const text = price.toFixed(2);, then return text.
Show example solution
const formatPrice = (price) => {
const text = price.toFixed(2);
return text;
};
Test yourself
-
Which uses implicit return (concise body)?
- const f = (x) => { return x; };
- const f = (x) => { x };
- const f = (x) => x;
- const f = (x) => { console.log(x); };
Show answer
const f = (x) => x; — Correct. No curly braces, one expression on the line; the value returns automatically.
-
Missing keyword in block body
const half = (n) => { ____ n / 2; };Show answer
const half = (n) => { return n / 2; }; -
Match the body types
- concise body
- no braces, no return
- block body
- braces and return
- implicit return
- value returned automatically