Skip to content

Tuples in Javascript

twitter logo github logo ・1 min read  

Here is a simple way to have tuples in Javascript:

// Make tuple
const Tuple = function(...arr) {

    // Set the value for our tuple
    const tupleobj = function tuple(indx) {

        // Return the index given
        return tupleobj.value[indx]


    // Give our tuple the array
    tupleobj.value = Object.freeze(arr)

    // Return the tuple
    return Object.freeze(tupleobj)


// Freeze tuple constant

this will make a working tuple (similar to Python 3's tuple in JS)

twitter logo DISCUSS (6)
markdown guide

What is the advantage of wrapping the object into a function instead of just return Object.freeze(arr)? With the function you can't take advantage of tuple restructuring, for example


It's so you can add your own methods, properties, etc... you could just restruct from the value of .value property anyways....


Adding your own methods and properties is what classes are for. Ideally you should avoid adding stuff to an object outside whatever function or constructor is used to create it, because if you pass it to another piece of code you can never be sure what properties and methods it has without checking, which can get quite annoying.

But that is a class, or atleast a constructor function, which are indeed, the exact same thing in JS... Tuple is indeed 'similar' to a class, it just doesn't require the 'new' keyword, and it callable.

Classic DEV Post from Jul 30 '19

PublishTo.Dev: Scheduling article publishing on

PDS OWNER CALIN (Calin Baenen) profile image
I am a 13 (as of Oct 30 of 2019) yr/o developer (I have been developing mini-projects for 4, years now, since I was 9), who makes projects in languages like: Java, HTML, Python 3, JS, CSS, and C#.