24

Consider the following code (demo):

function test(){
   var h = 'Hello';
   var w = 'World';
   return (h, w);

}

var test = test();

alert(test);

On execution the function test only returns the second value (i.e. 'World'). How do I make it return multiple values?

Aadit M Shah
  • 72,912
  • 30
  • 168
  • 299
Adam Mo.
  • 762
  • 2
  • 11
  • 26

4 Answers4

30

You cannot explicitly return two variables from a single function, but there are various ways you could concatenate the two variables in order to return them.

If you don't need to keep the variables separated, you could just concatenate them directly like this:

function test(){
  var h = 'Hello';
  var w = 'World';
  var hw = h+w 
  return (hw);
}
var test = test();
alert(test);

This would alert "HelloWorld". (If you wanted a space in there, you should use var hw = h+" "+w instead.

If you need to keep the two variables separated, you can place them into an array like so:

function test(){
  var h = "Hello";
  var w = "World";
  var hw=[h,w];
  return hw;
}
var test = test();
alert(test);

This allows the h and w values to still be accessed individually as test[0] and test[1], respectively. However, alert(test) here will display "Hello,World" because of the way alert() handles arrays (that is, it prints a comma-separated list of each element in the array sequentially). If you wanted to produce the same output as your example code, you would need use something like join(). join() will construct a string from an array, it takes one argument which serves as a separator between the elements. To reproduce the two alerts from my first example, you would need to use alert(test.join("")) and alert(test.join(" "), respectively.

My example could be shortened slightly by skipping the creation of the hw variable and just returning an array directly. In that case, test() would look like this:

function test(){
  var h="Hello";
  var w="World";
  return [h, w];
}

This could also be done as an object with return { h : h, w : w };, in which case you would access the individual variables as test.h and test.w, respectively.

SnoringFrog
  • 1,479
  • 1
  • 16
  • 30
19
function test(){ 
  var h = 'Hello'; 
  var w = 'World'; 
  return {h:h,w:w}
}

var test = test();

alert(test.h);
alert(test.w);

one simple way to do is to return Object containing multiple key value pairs.

Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
13

The comma operator evaluates each operand and then returns the value of the last one.

You'd need to either return an array:

return [h, w];

...or an object:

return { h : h, w : w };

Which you'd then use as:

var test = test();
alert(test[0]); // "hello" - in the case of the array version

...or:

var test = test();
alert(test.w); // "world" in the case of the object version
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
3

You can return an array or a new object.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445