Return value types
Learn to return numbers, arrays and objects and how to return multiple values.
Returning multiple values
A function returns a single value with return. But sometimes you want to return more than one value; for example both the smallest and largest number. To do this, you put the values inside an array or an object.
Example: function minMax(a, b) { return [Math.min(a, b), Math.max(a, b)]; }. Here return gives back a two-element array. In the call const result = minMax(3, 8);, result is [3, 8]. Then result[0] gives the minimum and result[1] the maximum.
Returning an object
The other way to return multiple values is to use an object. An object gives names to values, which makes the code more readable; you do not have to remember order.
Example: function minMax(a, b) { return { min: Math.min(a, b), max: Math.max(a, b) }; }. Here return gives back an object. In the call const r = minMax(3, 8);, you access the minimum with r.min and the maximum with r.max. Named fields make the code clearer.
Exercise Smallest and largest
Define a function called minMax. It should take a nums array parameter. Find the smallest value with const min = Math.min(...nums) and the largest with const max = Math.max(...nums). Then return both as an array with return [min, max].
Show example solution
function minMax(nums) {
const min = Math.min(...nums);
const max = Math.max(...nums);
return [min, max];
}
Test yourself
-
What is the best way to return both min and max from a function?
- Write return twice
- Two values separated by a comma: return min, max
- Assign them to global variables
- Return an array: return [min, max]
Show answer
Return an array: return [min, max] — Correct. With an array, multiple values are returned in a single return.
-
Return an array
function minMax(a, b) { const min = Math.min(a, b); const max = Math.max(a, b); return ____; } console.log(minMax(3, 8));Show answer
function minMax(a, b) { const min = Math.min(a, b); const max = Math.max(a, b); return [min, max]; } console.log(minMax(3, 8)); -
Match the return type
- return 5
- Returns a number
- return [a, b]
- Returns an array
- return {x, y}
- Returns an object
- return
- Returns undefined