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.
Or, less verbose but cleaner
The caller would have to do this to use the values
If you care to use only single axis you could do -
With the ECMAScript 6 you would be able to do destructuring (in caller).
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/