Search code examples
javascriptsyntax

Does JavaScript have tuples?


I would love to know if there are python type tuples in JavaScript. I am working on a project and I need to just use a list of objects rather tan an array.


Solution

  • Javascript does not support a tuple data type, but arrays can be used like tuples, with the help of array destructuring. With it, the array can be used to return multiple values from a function. Do

    function fun()
    {
        var x, y, z;
        # Some code
        return [x, y, z];
    }
    

    The function can be consumed as

    [x, y, z] = fun();
    

    But, it must be kept in mind that the returned value is order-dependent. So, if any value has to be ignored, then it must be destructured with empty variables as

    [, , x, , y] = fun();