Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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

ID: 647000 • Letter: O

Question

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?

Explanation / Answer

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

return {'x': x, 'y': 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/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote