A function can send a value back to the code that called it. The return statement does two things: it sends a value back to the caller, and it stops the function immediately. A function that returns a value can be used anywhere a value can: in a variable, in math, in a condition, or inside another call.
function sayHello() {
return "Hello World";
}
let message = sayHello();
console.log(message);
The value after return is sent back to the caller, and the call sayHello() is replaced by that value. message now contains "Hello World".
Most functions return the result of some work:
function celsiusToF(c) {
return c * 9 / 5 + 32;
}
let temp = celsiusToF(100);
console.log(temp);
console.log(celsiusToF(0) + 10); // in math
console.log(celsiusToF(37) > 100); // in a comparison
A function can return any type of value, not just numbers: strings, booleans, arrays, even other functions.
function fullName(firstName, lastName) {
return firstName + " " + lastName;
}
console.log(fullName("John", "Doe"));
If a function never reaches a return, calling it gives back undefined:
function multiply(a, b) {
let x = a * b; // calculated... then thrown away
}
let result = multiply(4, 3);
console.log(result);
console.log shows a value on screen; return hands it back to your code. A function that logs its answer instead of returning it looks like it works when you test it by hand, but gives undefined when you try to use the result. If you see undefined where you expected an answer, look for a missing return.
When a function reaches return, it stops. Code written after it will not run:
function multiply(a, b) {
return "Done";
// the next line will never run
return a * b;
}
console.log(multiply(4, 3));
Because return stops the function, you can use it inside an if to finish early based on a condition:
function checkAge(age) {
if (age < 18) {
return "Too young";
}
return "Access granted";
}
console.log(checkAge(12));
console.log(checkAge(20));
No else is needed: if the first return runs, the second line is never reached. The same idea gives you a clean chain of options:
function letterGrade(score) {
if (score >= 90) return "A";
if (score >= 80) return "B";
if (score >= 70) return "C";
return "F";
}
console.log(letterGrade(93), letterGrade(71), letterGrade(40));
Returning early is also how to reject bad input before doing any work. This is the guard clause pattern from JS Control Flow:
function divide(a, b) {
if (b === 0) return null; // guard clause
return a / b;
}
console.log(divide(10, 2));
console.log(divide(10, 0));
Functions that answer a yes/no question return a boolean. Name them with is, has, or can:
function isEven(n) {
return n % 2 === 0;
}
if (isEven(8)) {
console.log("8 is even");
}
true or false, so return it directly. return n % 2 === 0; is cleaner than if (n % 2 === 0) { return true; } else { return false; }, which says the same thing in five lines.
A function returns exactly one value. But that one value can be an array holding several pieces:
function minMax(numbers) {
return [Math.min(...numbers), Math.max(...numbers)];
}
const range = minMax([4, 8, 15, 16, 23, 42]);
console.log("Lowest: " + range[0]);
console.log("Highest: " + range[1]);
return a, b; does not return two things; it returns only b. Wrap multiple values in an array (or, once you know them, an object) instead.
Returned values are often used to update what a web page shows:
<p id="demo"></p>
<script>
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
</script>
The function knows nothing about the page. It just returns a number, and the calling code decides where to put it. Keeping calculation and display separate like this makes a function reusable anywhere.
Never put a line break right after return. JavaScript inserts a semicolon there (automatic semicolon insertion, from JS Statements) and returns undefined:
function broken() {
return
"hello";
}
function fixed() {
return (
"hello"
);
}
console.log(broken());
console.log(fixed());
If a returned value is long, start it on the same line as return, even if it is just an opening parenthesis.
return sends back undefinedundefinedWhat value is returned if a function has no return statement?
null0undefinedreturn, that something is undefined.What does this log?
function shout(word) {
console.log(word.toUpperCase());
}
let loud = shout("hey");
console.log(loud);
HEY then undefined. The function logs the uppercase word but never returns it, so loud gets undefined. Change the body to return word.toUpperCase();.What does check(5) return?
function check(n) {
if (n > 3) return "big";
if (n > 1) return "medium";
return "small";
}
"big". 5 is also greater than 1, but the first return already ended the function.area(r) so it returns the area of a circle (Math.PI * r * r), rounded to 2 placesisAdult(age) that returns a boolean, and use it inside an ifshout function from the Quick Check and fix it so loud holds "HEY"firstAndLast(word) that returns an array with a word's first and last letters