Sub topic 16
Returning Multiple Values
A JavaScript function can return only one value. That limit rarely matters in practice, because the one value can be an array or an object that holds several results. The caller then unpacks those results with destructuring. This chapter covers both styles, how to pick between them, and the mistakes that show up at the call site.
This chapter assumes you know how return works and that a function without one returns undefined. It also assumes you can read array and object literals and have seen destructuring syntax in parameter lists, which the chapter on options objects covered.
One Return Value, Many Results
Here is the core pattern. One function returns an array and another returns an object:
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); // 1 4
console.log(mean); // 4The function builds one container and returns it. Destructuring on the left of = pulls the pieces out into separate variables in the same statement. No hidden mechanism is involved: minMax returns an ordinary array, and you could also write const result = minMax(...) and read result[0].
Arrays: Results by Position
Array destructuring matches results by position. The first variable gets index 0, the second gets index 1, and so on. Because the caller chooses the names, arrays suit functions whose results callers will usually want to rename. React's useState returns [value, setter] for this reason: each caller writes const [count, setCount] or const [name, setName].
Array destructuring has a few tools for the call site:
function parseDate(text) {
const [year, month, day] = text.split("-").map(Number);
return [year, month, day];
}
const [y, , d] = parseDate("2026-11-25"); // skip the month with an empty slot
console.log(y, d); // 2026 25
const [first, ...others] = parseDate("2026-11-25"); // rest element
console.log(first, others); // 2026 [ 11, 25 ]
const [a, b, c, extra = "none"] = parseDate("2026-11-25"); // default for a missing slot
console.log(extra); // "none"Defaults in destructuring follow the same rule as default parameters. A default applies only when the value is undefined, either because the slot is missing or because it holds undefined. If the slot holds null, the variable gets null.
Positional results have a cost. Once more than two or three values come back, callers have to remember the order, and swapping two values of the same type, such as [min, max] and [max, min], produces no error. The code just gives wrong answers.
Objects: Results by Name
Object destructuring matches results by property name, so order does not matter and callers can take only the parts they need:
function analyze(nums) {
const total = nums.reduce((a, b) => a + b, 0);
return {
count: nums.length,
total,
mean: nums.length ? total / nums.length : 0,
max: nums.length ? Math.max(...nums) : undefined,
};
}
const { max, count } = analyze([2, 9, 4]); // any order, any subset
console.log(max, count); // 9 3
const { mean: average } = analyze([2, 9, 4]); // rename while unpacking
console.log(average); // 5
const { max: top = 0 } = analyze([]); // rename plus default
console.log(top); // 0In { mean: average }, the name on the left of the colon is the property to read, and the name on the right is the new variable. People often read it backwards. The analyze function returns undefined for max when the array is empty, so the default = 0 kicks in for that case.
With objects you can also add a new property later without breaking existing callers. Adding a value to the middle of a returned array shifts every position after it and breaks every caller that relies on those positions.
Choosing Between Arrays and Objects
| Question | Array | Object |
|---|---|---|
| How are results matched? | By position | By property name |
| Who picks the variable names? | The caller, with no extra syntax | The function, unless the caller renames with `key: name` |
| Can callers skip values easily? | Only with empty slots `[, , x]` | Yes, they list only the names they want |
| Is adding a result later safe? | Only at the end | Yes, anywhere |
| Good fit | Two or three closely related values, tuple-like pairs | Three or more values, or values callers pick and choose |
Use an array for a small, fixed pair whose meaning is obvious from context, such as [min, max], [key, value], or [state, setState]. Use an object for everything else.
Common Errors at the Call Site
Destructuring a missing result
Destructuring undefined or null throws a TypeError. This happens when a function sometimes returns nothing, for example from a guard clause:
function findRange(nums) {
if (nums.length === 0) return; // implicit undefined
return [Math.min(...nums), Math.max(...nums)];
}
try {
const [low, high] = findRange([]);
} catch (err) {
console.log(err instanceof TypeError); // true
}
const [low2, high2] = findRange([]) ?? [];
console.log(low2, high2); // undefined undefinedYou can fix this in either place. The function can always return the same shape, for example [undefined, undefined] or { found: false }, or the caller can fall back with ?? [] or ?? {}. Returning a consistent shape is usually better, because then every caller is safe without remembering to add the fallback.
Assigning to existing variables
When you destructure an object into variables that already exist, a line that starts with { is parsed as a block. Wrap the whole assignment in parentheses:
let total, mean;
({ total, mean } = { total: 12, mean: 4 }); // parentheses are required
console.log(total, mean); // 12 4Array destructuring has no block ambiguity, but if the previous line has no semicolon, a line that starts with [ can join onto it. This is the same automatic semicolon insertion hazard that the return chapter covers.
Order mistakes with arrays
Swapping names in array destructuring is silent:
function minMax(nums) {
return [Math.min(...nums), Math.max(...nums)];
}
const [hi, lo] = minMax([3, 1, 4]); // wrong order, no error
console.log(hi, lo); // 1 4 (hi actually holds the minimum)If this kind of bug keeps appearing, switch the function to return an object.
A Useful Side Effect: Swapping
Array literals plus destructuring also let you swap variables without a temporary variable. This uses the same mechanism: the right side builds one array, and the left side unpacks it.
let x = 1;
let y = 2;
[x, y] = [y, x];
console.log(x, y); // 2 1Exercise
Write a function splitName(fullName) that returns the first name and the last name of a string like "Ada Lovelace". Pick arrays or objects and justify the choice. Then show a call that gets only the last name, and say what happens if splitName returns undefined for an empty string and the caller destructures it without a fallback.
Show answer
An object is the clearer choice, because callers often want only one part and the names first and last document themselves. Code: function splitName(fullName) { const [first, ...rest] = fullName.trim().split(" "); return { first, last: rest.join(" ") }; }. Getting only the last name: const { last } = splitName("Ada Lovelace");, which gives "Lovelace". If the function returned undefined and the caller wrote const { last } = splitName(""), the statement would throw a TypeError, because you cannot destructure undefined. The fix is to always return an object, for example { first: "", last: "" }, or to write splitName("") ?? {} at the call site.
Exercise
What does this code log, and why? function pair() { return [1, null]; } const [a = 10, b = 20, c = 30] = pair(); console.log(a, b, c);
Show answer
It logs 1 null 30. The first slot holds 1, so its default is ignored. The second slot holds null, and destructuring defaults apply only to undefined, so b is null. The returned array has no third slot, which reads as undefined, so c takes its default of 30.