In JavaScript, a function can return multiple values by returning an array or an object that contains the multiple values. For example:

function getValues() {
    return [1, 2, 3];
}
let values = getValues();
console.log(values[0]); // Output: 1
console.log(values[1]); // Output: 2
console.log(values[2]); // Output: 3

Another way to return multiple values is by using destructuring assignment:

function getValues() {
    return {
        value1: 1,
        value2: 2,
        value3: 3
    };
}
let { value1, value2, value3 } = getValues();
console.log(value1); // Output: 1
console.log(value2); // Output: 2
console.log(value3); // Output: 3

In ES6 you can use the ‘…’ operator to return multiple values

function getValues() {
    return [1, 2, 3, 4, 5];
}
let [value1, value2, ...rest] = getValues();
console.log(value1); // Output: 1
console.log(value2); // Output: 2
console.log(rest); // Output: [3,4,5]

You also can use return to return multiple values as well.

function getValues() {
    return 1, 2, 3;
}
let values = getValues();
console.log(values); // Output: 3

Keep in mind that this will only work if you use the return statement with a single value, otherwise, the returned value will be the last value.

Also Read:

Categorized in: