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?
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.
No, you can not return multiple values like this in C. A function can have at most one single return value.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With