This page looks best with JavaScript enabled

Return Multiple Values from Javascript Function

 ·   ·  ☕ 1 min read

A Javascript function returns one and only one value.

1
2
3
4
5
6
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.

1
2
3
4
5
6
7
8
9
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 ..

1
2
3
4
5
function op(x, y) {
  return { sum: x + y, diff: x - y };
}

console.log(op(5, 4)); //{ sum: 9, diff: 1 } - same result, fewer lines
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things