JavaScript

  1. Home
  2. Computing & Technology
  3. JavaScript

Returning Multiple Values

Join the Discussion

Questions? Comments?

You can pass multiple values to a function but a function only returns a single value when it finishes running. What can we do then if we need the function to set more than one value?

There are in fact several solutions to this problem. The simplest to code is to simply create variables prior to calling the function and have the function update the values in those variables directly. For example:

function xyz() {
...
x = 1;
y = 'A';
}
var x = 0;
var y = '';
xyz();
document.write('x=' + x + ' and y = ' + y);

The disadvantage of this method of returning multiple values is that the same variables are always updated. This can lead to big problems if the function is called from several different places and the calls need to be independent.

The solution to this lies in the fact that any object can hold multiple properties. We can therefore return an object from our function and the multiple values we need to return can be returned in different properties of that object.

The simplest object type to use to do this is an Array. We don't even need to name our array in order to be able to use it to return multiple values as the function effectively names it for us. All we need to do is to keep track of which element in the array holds which of the returned values. For example:

function xyz() {
...
var x = 1;
var y = 'A';
return [x, y];
}
var a = xyz();
document.write('x=' + a[0] + ' and y = ' + a[1]);

This method of returning multiple values avoids our having to define the variables prior to calling the function but leaves us with not very meaningful names to refer to the different values returned. By using an Object instead of the Array we can give our returned values more meaningful names at a cost of making the code to return the values slightly more complicated. For example:

function xyz() {
...
var x = 1;
var y = 'A';
return {x : x, y : y};
}
var a = xyz();
document.write('x=' + a.x + ' and y = ' + a.y);

So there you are, three different ways of getting a function to effectively return more than one value.

Explore JavaScript

About.com Special Features

JavaScript

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.