Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 655
IGE DAMILOLA Avatar asked Aug 31 '26 06:08

IGE DAMILOLA


2 Answers

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();
like image 90
Swati Srivastava Avatar answered Sep 02 '26 18:09

Swati Srivastava


The closest to a tuple is using Object.seal() on an array which is initiated with the wanted length:

let arr = new Array(1, 0, 0);
let tuple Object.seal(arr)

Otherwise, you can use a Proxy:

let arr = [ 1, 0, 0 ];
let tuple = new Proxy(tuple, {
    set(obj, prop, value) {
        if (prop > 2) {
            throw new RangeError('this tuple has a fixed length of three');
        }   
    }
});

Update: There is an ECMAScript proposal for a native implementation of a Tuple type

like image 45
shaedrich Avatar answered Sep 02 '26 20:09

shaedrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!