Kodeclik Blog

Can a Javascript function return multiple values?

Let us learn more about Javascript functions and how they work. We know Javascript functions can take multiple arguments. But can they return multiple values?
We will embed our Javascript code inside a HTML page like so:
In the above HTML page you see the basic elements of the page like the head element containing the title (“Javascript function return values”) and a body with an empty script tag. The Javascript code goes inside these tags.

A basic Javascript function

Let us write a Javascript program to compute the number of permutations and the number of combinations of k elements chosen from a set of n elements. Recall that to find the number of permutations and combinations we need to use factorials. So, let us first write a factorial function and see if it works:
Note that the factorial function is defined recursively. The last line in the script computes (and prints) the factorial of 10. The output is, as expected:

A Javascript function to compute permutations

Let us now write another function to compute the number of permutations of k elements chosen from a set of n elements.
The output will be:

A Javascript function to compute combinations

Now if we would like this function to also return the number of combinations of “n choose k”, we cannot quite do that. We will have to write a new function, like so:
The output will be:

Packaging multiple return values from a function

If we desire to return multiple values, we must package them into an object like so:
The output is:
As you can see from the above program, we now have a single function (called “combinatorics”) that computes both permutations and combinations. It then packages them into a single object and then returns it. In the routine where we call the combinatorics function, the results are stored in the “answers” variable. We then deconstruct the answers variable to find the permutations and combinations and print them separately.
So the moral of the story is: a function cannot technically return multiple values in Javascript but this is not a limitation in any real sense because you can always package your desired multiple values into a composite object and return the object for possible deconstruction later.
Interested in learning more Javascript? Learn how to loop through two Javascript arrays in coordination and how to scramble a string in Javascript!
Want to learn Javascript with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.