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.
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With