Tuples in JavaScript

Tuples in JavaScript

Image for postA Tuple? sort of

No, JavaScript doesn?t have tuples. But with array destructuring, we can pretend it does! In languages where tuples actually exist, their benefits include grouping multiple types of values together, being immutable, and being more memory efficient than other types of grouping mechanisms. In JavaScript, arrays already allow multiple types to be grouped. For our purposes, a ?tuple? in JavaScript will simply be an array of known length, whose values are of a known type, such as an array of three numbers: [45, 30, 90]. We won?t worry about immutability or efficiency here.

So what?s the advantage of using a tuple in JavaScript? When combined with array destructuring, it can allow a function to return multiple values. Consider this function:

function getCoordinates(element) { let x, y, z; // do stuff to get coordinates return [x, y, z];}

We can consume the function like this: const [x, y, z] = getCoordinates(el);. How is that different than returning an object? After all, we can still destructure a returned object: const { x, y, z } = getCoordinates(el);. The real benefit comes when the tuple-returning function is used multiple times in the same scope. No renaming of variables is needed because they?re destructured by position!

// with returned objectsconst {x: Ax, y: Ay, z: Az } = getCoordinates(A);const {x: Bx, y: By, z: Bz } = getCoordinates(B);// with returned tuplesconst [Ax, Ay, Az] = getCoordinates(A);const [Bx, By, Bz] = getCoordinates(B);

So, what are the downsides?

The positional destructuring that is so useful can also limit its use. The returned value is not self-documenting like an object is. The returned value is order-dependent, so a consumer wishing to ignore beginning or middle values must destructure with empty places or throwaway variables:

const [, , thisOne, , thatOne] = getTuple();const [_1, _2, thisOne, _3, thatOne] = getTuple();

As with all coding patterns, there will be places it is useful and places where another pattern is a better fit.

No Responses

Write a response