Destructuring Infinity

Wednesday, 03 January 2024

Did you know you can destructure from an infinite source of values in JavaScript? Well, you can.

function *numbers() {
    let i = 1;
    while (true) yield i++;
}

const [one, two, three, four] = numbers();

// one == 1
// two == 2
// three == 3
// four == 4

Since I noticed this, it's been rattling around my head looking for a use case. The idea of altering code execution by changing only the pattern you destructure to is intriguing to me.

It works on proxy objects too.

const shout = new Proxy({}, {
    get(target, prop, receiver) {
        return prop.toUpperCase() + '!';
    }
});

const {more, cake, now} = shout;

// more == "MORE!"
// cake == "CAKE!"
// now == "NOW!"

My brain is convinced there's some cute API trick to be played here. But if it exists, I'm yet to find it.

Maybe now this is rattling around your head too. I'm sorry about that. Whatever abomination it drives you to create in the end, please share it with me.