Skip to content

Comment on Sparse array destructuring in JavaScript

Comments

I've used this for regexp's...

    const parse = /(\w+):(\d+)/.exec(str)
    if (parse) {
        const [, key, value] = match
    }
(Where the elided first entry is the original string)

I've also had bugs where I forgot the leading comma and had all the wrong captures. Depending on the situation, I might instead recommend named captures:

    const parse = /(?<key>\w+):(?<value>\d+)/.exec(str)
    if (parse) {
        const {key, value} = parse.groups
    }
Caveat is it takes a bit to convince TS this is sound, and you have to manually sync the names. (https://github.com/microsoft/TypeScript/issues/32098 would help)
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.