Home >Web Front-end >JS Tutorial >How Can I Return Multiple Values from a JavaScript Function?

How Can I Return Multiple Values from a JavaScript Function?

Susan Sarandon
Susan SarandonOriginal
2024-11-24 19:43:34535browse

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()];
}

You can then access the values using destructuring assignment:

const [first, second] = getValues();

This approach is equivalent to:

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

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(),
    };
}

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

const {first, second} = getValues();

Alternatively, you can use the more verbose approach:

const values = getValues();
const first = values.first;
const second = values.second;

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!

Statement:
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