3

Can a function return two values?

Can a function return two values? { I came across this in C} Any possibility of something in JavaScript

Community
  • 1
  • 1
John Cooper
  • 7,343
  • 31
  • 80
  • 100

2 Answers2

6

You can't return two distinct values but you can return an object or array. This is perfectly valid, as long as you document the behavior for anyone else who might encounter the code. It's helpful if the two returned values are truly related. If not, it can become difficult to understand the function. And just returning a diverse array of values from an object would be considered a bad practice by many people since a function's purpose is usually to perform a discrete action which may return a discrete value.

// As an object
function() {
  return {val1: "value 1", val2: "value 2"};
}

// As an array
function() {
  return ["value 1", "value 2"];
}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
5

Not directly, but no one can stop you from returning an Array with multiple elements:

function modify(a,b) {
    return [a*2, b*2];
}

var res = multiple(5, 10);

console.log( res );

To push this a little further, we could use such a "mapped" result to call another method. Javascripts .apply() comes in pretty handy for this.

function add(v1, v2) {
    return v1 + v2;
}

and we could call

add.apply( null, modify(2,4) );

this effectively would be like

add(4, 8) // === 12
jAndy
  • 231,737
  • 57
  • 305
  • 359
  • please let the world know why you downvote. We should all learn from your infinite wisdom, stranger ! – jAndy Jul 04 '11 at 13:02
  • the downvote was a misclick by me, which has been changed to an upvote. Sorry. Now if only I could find out why I got my downvote... _Edit: mine was just undone._ – Michael Berkowski Jul 04 '11 at 13:03