Skip to content

Function Return Statements

A return statement ends a function and sends a value back to the code that called it. The call then stands for that value, so it can be stored in a variable, used in a calculation or tested in a condition.

function name(parameter) {
return value;
}
const result = name(argument);

A function that returns its result is more flexible than one that logs it, because the caller decides what to do with the value:

function addVat(price) {
return price * 1.2;
}
const total = addVat(15) + addVat(5);
console.log(total);
console.log(addVat(2.5).toFixed(2));

This prints:

24
3.00

Each call to addVat is replaced by the value it returns, so addVat(15) + addVat(5) is 18 + 6.

A function that returns a boolean makes a condition read like a question. Here canAfford holds the rule, and the loop uses it to decide what happens to each purchase:

function canAfford(balance, price) {
return balance - price >= 0;
}
let balance = 10;
const prices = [4.5, 3.2, 2.8];
for (const price of prices) {
if (canAfford(balance, price)) {
balance -= price;
console.log(`Bought for £${price.toFixed(2)}, £${balance.toFixed(2)} left`);
} else {
console.log(`Cannot afford £${price.toFixed(2)}`);
}
}

This prints:

Bought for £4.50, £5.50 left
Bought for £3.20, £2.30 left
Cannot afford £2.80

The comparison balance - price >= 0 already produces true or false, so the function returns it directly rather than wrapping it in an if with return true and return false.

The function stops at the first return that runs, and no line after it in the function runs. This allows several exits, each handling one case, without else:

function grade(score) {
if (score >= 70) {
return 'Distinction';
}
if (score >= 50) {
return 'Pass';
}
return 'Fail';
}
console.log(grade(82));
console.log(grade(55));
console.log(grade(31));

This prints:

Distinction
Pass
Fail

A function that finishes without reaching a return returns undefined. Logging a value is not the same as returning it, so the caller of the function below receives nothing it can use:

function logTotal(prices) {
let sum = 0;
for (const p of prices) {
sum += p;
}
console.log(sum);
}
const result = logTotal([2, 3]);
console.log(result);

This prints:

5
undefined

Function Return Statements 2 looks at undefined returns and other pitfalls in more detail.

Steve Griffith covers this topic in his video JavaScript Function Return Statements.