A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

How to Return Multiple Values from a Function in JavaScript
Q:

How to Return Multiple Values from a Function in JavaScript

0

How to Return Multiple Values from a Function in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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. Let's take a look at 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 an object if you want to label each of the returned values for easier access and 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>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now