JavaScript – How to Return Multiple Values in JavaScript

classjavascriptobject

Often I am writing a function that returns multiple values, such as a pair of coordinates:

function get_coords() {
  return ???;
}

If I was using a language like Python, I would use a tuple:

return (x, y)

Or, in an OOP language like Java, I would create a custom coordinate class:

class Coordinates {
  public int x;
  public int y;

  public Coordinates(x, y) {
    this.x = x;
    this.y = y;
  }
}

Then return like this:

return new Coordinates(x, y);

On to JavaScript.

In JavaScript, we have the option of returning a simple object:

return {x: x, y: y}

or a Java-like approach, with a custom object:

return new coordinates(x, y)

Are there any reasons to use one above the other?

Best Answer

Doing this is the best (and verbose) option right now.

return {x: x, y: y}

Or, less verbose but cleaner

return {x, y}

The caller would have to do this to use the values

var c = get_coords();
alert(c.x + ' ' + c.y);    // c.x and c.y holds the coordinates

If you care to use only single axis you could do -

alert(get_coords().x);

With the ECMAScript 6 you would be able to do destructuring (in caller).

var { x, y } = get_coords();

Too bad that we'll have to wait quite long to use ECMAScript 6 safely in production (in a cross-browser manner).

More info on destructuring - http://fitzgeraldnick.com/weblog/50/

Related Topic