Member-only story
Return multiple values from a function — Javascript
2 min readJul 11, 2023
We have two options to return multiple values
Problem
Need to return sum
, diff
, product
, division
from a single function
function getValues(a,b){
const sum = a + b;
const diff = a - b;
const product = a * b;
const division = a / b;
return sum,diff,product,division;
// only last value (division) will be returned
}
console.log(getValues(10,20)) //0.5
The solution follows
Array Method
We can wrap the elements into an array and return it
function getValues(a,b){
const sum = a + b;
const diff = a - b;
const product = a * b;
const division = a / b;
return [sum,diff,product,division];
// wrap it as array
}
console.log(getValues(10,20)) // [30, -10, 200, 0.5]
When to use
When dealing with few return values, like useState
of react, just an current state and function to update.
Advantages —
- Easy destructing without need to know the names to get the values ( incase of few values returned)
Disadvantages —
- Index position should be maintained properly when accessing to avoid wrong values to be assigned
Object Method
We can wrap elements as an object and return it — Remember {sum,diff,product,division}
is same as…