Sub topic 3
Early Returns and Guard Clauses
This chapter assumes you can declare and call functions, use arrays and objects, and know that a function without return produces undefined.
Early Returns and Guard Clauses
A guard clause is an if check at the top of a function that returns as soon as a special case applies. Once the edge cases have been handled, the main logic can run without extra nesting.
function discount(price, isMember) {
if (price <= 0) return 0; // guard clause
if (!isMember) return price; // guard clause
return price * 0.9;
}
console.log(discount(100, true)); // 90
console.log(discount(-5, true)); // 0Returning Multiple Values
A function returns exactly one value. To hand back several results, wrap them in an array or an object and destructure them at the call site. Use an array when the order of the results is obvious, and an object when names make the code clearer.
function minMax(nums) {
return [Math.min(...nums), Math.max(...nums)];
}
function stats(nums) {
const total = nums.reduce((a, b) => a + b, 0);
return { total, mean: total / nums.length };
}
const [lo, hi] = minMax([3, 1, 4]);
const { mean } = stats([2, 4, 6]);
console.log(lo, hi, mean); // 1 4 4Implicit Returns in Arrow Functions
When an arrow function has an expression body (no braces), it returns that expression implicitly. If the expression is an object literal, wrap it in parentheses. Without them, JavaScript reads the braces as a block.
const double = (x) => x * 2;
const toPoint = (x, y) => ({ x, y });
const broken = (x, y) => { x, y }; // block body, returns undefined
console.log(double(4), toPoint(1, 2), broken(1, 2));
// 8 { x: 1, y: 2 } undefinedThe Line Break After return Pitfall
Automatic semicolon insertion adds a semicolon after return when the next token is on a new line. The function then returns undefined, and the code that follows never runs.
function getConfig() {
return
{
debug: true
};
}
console.log(getConfig()); // undefinedReturning Functions
A function can return another function. The inner function is a closure: it keeps access to the outer function's parameters after the outer call has finished.
function makeMultiplier(factor = 2) {
return (n) => n * factor;
}
const triple = makeMultiplier(3);
console.log(triple(5), makeMultiplier()(5)); // 15 10What async Functions Return
An async function always returns a Promise. The value you return becomes the value that Promise resolves to.
async function getTotal() {
return 42;
}
const result = getTotal();
console.log(result instanceof Promise); // true
result.then((value) => console.log(value)); // 42Exercise
Why does const make = (id) => { id }; return undefined, and how do you fix it so it returns an object?
Show answer
The braces are parsed as a block body containing the expression statement id, and a block body has no implicit return. Wrap the object in parentheses: const make = (id) => ({ id });.
Exercise
What does getTotal().then(v => v + 1) resolve to if getTotal is async and returns 42?
Show answer
It resolves to 43. getTotal() returns a Promise resolving to 42, and then returns a new Promise resolving to 42 + 1.