Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return two variables in one function [duplicate]

Tags:

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?

like image 460
Adam Mo. Avatar asked Nov 02 '13 02:11

Adam Mo.


People also ask

Can a function return 2 variables?

Create a function getPerson(). As you already know a function can return a single variable, but it can also return multiple variables. We'll store all of these variables directly from the function call.

Can I return 2 values from a function in C?

No, you can not return multiple values like this in C. A function can have at most one single return value.

Can we return 2 variables in Python?

Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.


1 Answers

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.

like image 107
SnoringFrog Avatar answered Oct 04 '22 15:10

SnoringFrog