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/
In addition to the general design principles, like single responsibility, and least surprise, there's a JavaScript-specific reason that it's not a good idea: there's a huge difference between a boolean
and Boolean
in JavaScript that prevents it from working in the general case.
boolean
is a primitive type, not an object, and cannot have custom properties. Expressions like true.toString()
work because behind the scenes, it turns into (new Boolean(true)).toString()
.
Boolean
(with a capital B) is an object, but has very few good uses, and being used as a boolean
is definitely not one of them. The reason for that is, that every Boolean
is "true", regardless of its value, because all objects get converted to true
in a boolean context. For example, try this:
var answer = new Boolean(false);
if (answer) {
console.log("That was unexpected.");
}
So, in general, there's no way to add properties to a boolean in JavaScript that still lets it behave in a logical way. Modernizr can get away with it because the only add properties to "true" values, which sort of work how you would expect (i.e. they work in if statements). If video isn't supported at all, Modernizr.video
will be an actual boolean
(with the value false
), and can't have properties added to it.
Best Answer
It allows you to do method chaining, which a lot of people feel improves readability. It's a very common idiom in JavaScript, which means a lot of people expect it, especially if the rest of the code base is similar. Your second point about cloning the object also has merit, if used to make your object immutable. How beneficial that is depends on your specific application.