Return two variables in one function
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.
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.