Home > Web Front-end > JS Tutorial > body text

How Can I Return Multiple Values from a JavaScript Function?

Susan Sarandon
Release: 2024-11-24 19:43:34
Original
529 people have browsed it

How Can I Return Multiple Values from a JavaScript Function?

Can You Return Multiple Values in JavaScript?

Traditionally, JavaScript functions can only return a single value. However, there are ways to simulate returning multiple values.

Array as Return Value

One method is to return an array containing the desired values. For instance:

function getValues() {
    return [getFirstValue(), getSecondValue()];
}
Copy after login

You can then access the values using destructuring assignment:

const [first, second] = getValues();
Copy after login

This approach is equivalent to:

const values = getValues();
const first = values[0];
const second = values[1];
Copy after login

Object as Return Value

Another option is to return an object with named properties for each value. This provides a more structured and labeled method of returning multiple values:

function getValues() {
    return {
        first: getFirstValue(),
        second: getSecondValue(),
    };
}
Copy after login

To access the values in this case, you can use the ES6 object destructuring syntax:

const {first, second} = getValues();
Copy after login

Alternatively, you can use the more verbose approach:

const values = getValues();
const first = values.first;
const second = values.second;
Copy after login

Recommendation

The recommended approach for returning multiple values in JavaScript is to use an object. This provides clear labeling, ease of adding new values, and better type safety in TypeScript and JSDoc compared to using arrays. Solely return arrays for simple tuples with a clear ordering, such as coordinate pairs [x, y].

The above is the detailed content of How Can I Return Multiple Values from a JavaScript Function?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template