Returning Values
A function that returns a value hands something back to whoever called it, which is what makes functions composable.
return sends a value back and ends the function immediately. A function with no return gives undefined. Printing and returning are different things, and mixing them up is the commonest beginner mistake with functions.
EXERCISE
1Handing a Value Back
Without return, a function can do things but cannot answer questions, and answering questions is most of what functions are for.
A function that only prints:
function addAndPrint(a, b) {
console.log(a + b);
}
addAndPrint(2, 3); // 5 appears in the console
const result = addAndPrint(2, 3);
console.log(result); // undefined <- the answer was never handed back
console.log(result * 2); // NaN
A function that returns:
function add(a, b) {
return a + b;
}
const result = add(2, 3);
console.log(result); // 5
console.log(result * 2); // 10
console.log(add(add(1, 2), add(3, 4))); // 10
The second one can be used inside other expressions. The first one cannot, because it hands back nothing.
A function with no return gives undefined:
function nothing() {}
console.log(nothing()); // undefined
function alsoNothing() {
const x = 5; // work happens, but nothing is handed back
}
console.log(alsoNothing()); // undefined
console.log shows a value to a person. return hands a value to the rest of your program. They are completely different jobs, and a function that logs its answer instead of returning it is a function nothing else can use. When in doubt, return the value and let the caller decide whether to print it.
EXERCISE
2return Ends the Function Immediately
Nothing after a return runs, which is what makes early returns such a clean way to handle special cases.
Code after a return is dead:
function check(n) {
return n > 0;
console.log("never runs"); // unreachable
}
console.log(check(5)); // true
Which is exactly why guard clauses work:
function divide(a, b) {
if (b === 0) {
return "Cannot divide by zero";
}
return a / b;
}
console.log(divide(10, 2)); // 5
console.log(divide(10, 0)); // Cannot divide by zero
// The second return was never reached.
A bare return exits without a value:
function greet(name) {
if (!name) {
return; // stop here, hand back undefined
}
console.log(`Hello ${name}`);
}
greet(); // nothing prints
greet("Ada"); // Hello Ada
And a trap from automatic semicolon insertion:
function broken() {
return
42;
}
console.log(broken()); // undefined !
// JavaScript inserted a semicolon after `return`.
// The value must start on the SAME line:
function fixed() {
return 42;
}
console.log(fixed()); // 42
// For a long value, open a bracket on the return line:
function fixedLong() {
return (
42 + 8
);
}
console.log(fixedLong()); // 50
Pro Tip:
returnon its own line is one of the few places where JavaScript's automatic semicolons genuinely bite. The value has to begin on the same line as the keyword. If the expression is too long, put an opening bracket right afterreturnand the rest can wrap freely.
EXERCISE
3Returning More Than One Value
A function can only return one thing, so when you need several, you return a single object or array that holds them.
Returning an object, which is the readable choice:
function analyse(numbers) {
let total = 0;
let largest = numbers[0];
for (const n of numbers) {
total += n;
if (n > largest) largest = n;
}
return {
count: numbers.length,
total: total,
largest: largest,
};
}
const stats = analyse([3, 7, 2]);
console.log(stats.count); // 3
console.log(stats.total); // 12
console.log(stats.largest); // 7
Pulling the parts out by name as you receive them:
const { count, largest } = analyse([3, 7, 2]);
console.log(count); // 3
console.log(largest); // 7
// Take only the fields you need, and the names come with them.
// This is called destructuring, and it works on any object.
Returning an array, when order is the natural label:
function bounds(numbers) {
let low = numbers[0];
let high = numbers[0];
for (const n of numbers) {
if (n < low) low = n;
if (n > high) high = n;
}
return [low, high];
}
const [low, high] = bounds([3, 7, 2]);
console.log(low, high); // 2 7
Why an object is usually the better choice:
const [a, b] = bounds([3, 7, 2]);
// What are a and b? You have to go and read bounds to find out.
const { count, total } = analyse([3, 7, 2]);
// Self-explanatory, and the order they were written does not matter.
Return an object when the values have meanings, and an array only when the order is genuinely obvious, such as a pair of coordinates or a low and a high. Objects also survive change better: adding a fourth field breaks nothing, while inserting a third element into a returned array breaks every caller that was reading by position.
