Returning multiple values in Javascript

Javascript is a dynamic language that provides several ways to store and return data. Statically defined languages such as C++ have difficulty with returning multiple values from functions. In C or C++, the common solution is using a struct that stores all the values that one may want to return from a function.

This is not the ideal solution, however, because every time this is necessary one needs to define a new struct. It quickly gets difficult to manage a program that works in this way. As a result, C and C++ programs use formal parameters as a way to return results. The idea is to make a variable to be passed by reference (or using a pointer).

Javascript, being a dynamic language, has other ways to achieve the same result. In Javascript, one can define objects on the fly, that is, the fields of an object can be created at running time.

Therefore a good solution for the problem is to return a new Javacript object with as many fields as necessary to hold the required values. For example:

function multiple_return() {
  var x = 1;
  var y = 2;
  return { myX : x, myY : y };
}

function user_function() {
  var res = multiple_return();
  alert("value is " + res.myX + " " " + res.myY);
}

Using Javascript Arrays to Return Multiple Values

Another possible solution involves creating an array with as many elements as necessary. The spirit of the solution is similar, however in this case one doesn't need to use field names. If all elements have similar functionality, then this is probably the best way to return multiple values.

Here is an example:

function return_with_array()
{
  x = 1;
  y = 2'
  // do something here
  return [1, 2];
}
Tags: javascript, functions, multiple, return
Article created on 2010-06-21 10:43:33

Post a comment