A Javascript function returns one and only one value.
function sum(x, y) {
return 3 + 39;
}
let life = sum(3, 39);
console.log(life); // 42
I bet you already knew that not returning a value from a function, would return ‘undefined’.
Anywho.. you are in a pickle if you want to return multiple values. There is no return(sum, diff);.
However, a lot of problems need multiple ’things’ from the function output. What we do is to create an object in the function, populate it with multiple values and return the object to caller. The object packages all required variables.
function op(x, y) {
let sum = x + y;
let diff = x - y;
const result = { sum: sum, diff: diff };
return result;
}
const result = op(5, 4);
console.log(result); //{ sum: 9, diff: 1 }
Or, you could compress the whole function to ..
function op(x, y) {
return { sum: x + y, diff: x - y };
}
console.log(op(5, 4)); //{ sum: 9, diff: 1 } - same result, fewer lines