javascriptreturnmultiple-variable-return

Return multiple values in JavaScript?


I am trying to return two values in JavaScript. Is this possible?

var newCodes = function() {  
    var dCodes = fg.codecsCodes.rs;
    var dCodes2 = fg.codecsCodes2.rs;
    return dCodes, dCodes2;
};

Solution

  • No, but you could return an array containing your values:

    function getValues() {
        return [getFirstValue(), getSecondValue()]
    }
    

    Then you can access them like so:

    const [first, second] = getValues()
    

    This is called destructuring assignment and is supported by every major JS environment. It's equivalent to the following:

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

    You can also return an object if you want to assign a name to each value:

    function getValues() {
        return {
            first: getFirstValue(),
            second: getSecondValue(),
        }
    }
    

    And to access them:

    const {first, second} = getValues()
    

    Which is the same as:

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

    It is highly recommended to return an object instead of an array unless the values make sense as a simple tuple, e.g. a coordinate pair [x, y]. With an array, it's easy to forget which value is which, it's harder to add more values later, and it's marginally more difficult to correctly type with TypeScript or JSDoc.