WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES

How to Return Multiple Values from a Function in JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Return an Array of Values

A function cannot return multiple values. However, you can get the similar results by returning an array containing multiple values, as demonstrated in the following example.

  • <script>
  • // Defining function
  • function divideNumbers(dividend, divisor){
  •     var quotient = dividend / divisor;
  •     var arr = [dividend, divisor, quotient];
  •     return arr;
  • }
  •  
  • // Store returned value in a variable
  • var all = divideNumbers(10, 2);
  •  
  • // Displaying individual values
  • alert(all[0]); // 0utputs: 10
  • alert(all[1]); // 0utputs: 2
  • alert(all[2]); // 0utputs: 5
  • </script>

Alternatively, you can also return object if you want to label each of the returned values for easier maintenance, as demonstrated in the following example:

  • <script>
  • // Defining function
  • function divideNumbers(dividend, divisor){
  •     var quotient = dividend / divisor;
  •     var obj = {
  •         dividend: dividend,
  •         divisor: divisor,
  •         quotient: quotient
  •     };
  •     return obj;
  • }
  •  
  • // Store returned value in a variable
  • var all = divideNumbers(10, 2);
  •  
  • // Displaying individual values
  • alert(all.dividend); // 0utputs: 10
  • alert(all.divisor); // 0utputs: 2
  • alert(all.quotient); // 0utputs: 5
  • </script>

Related FAQ

Here are some more FAQ related to this topic:

Your Feedback:

We would love to hear from you, please drop us a line.