There are several ways to return multiple values ββin JavaScript. You can always return multiple values ββto an array:
function f() { return [1, 2]; }
And refer to them as follows:
var ret = f(); document.write(ret[0]);
But the syntax is much better in JavaScript 1.7 with the addition of a destructuring destination (if you are lucky enough to focus on an environment that guarantees its support (for example, the Firefox extension)):
var a, b; [a, b] = f(); document.write("a is " + a + " b is " + b + "<br>\n");
Another option is to return an object literal containing your values:
function f() { return { one: 1, two: 2 }; }
Which can be accessed by name:
var ret = f(); document.write(ret.one + ", " + ret.two);
And, of course, you can do something really terrible, for example, change the global scope or even set the properties of the function itself:
function f() { f.one = 1; f.two = 2; } f(); document.write(f.one + ", " + f.two);
Read more (and the source of some of these examples):
https://developer.mozilla.org/en/New_in_JavaScript_1.7#Destructuring_assignment_(Merge_into_own_page.2fsection )
Wayne burkett
source share