Image for post
Image for post
A 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:

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 tuples
const [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:

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

Web Developer, Oregonian, husband

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store