Settings

Theme

Sparse array destructuring in JavaScript

codepipet.com

13 points by suhair 3 years ago · 17 comments

Reader

bastawhiz 3 years ago

It's called "array destructuring" because you're destructuring _arrays_, but this is treating arrays like _tuples_. If you're storing more than 3 (really 2) pieces of information about a single thing in a tuple, you're almost certainly misusing tuples. Why would you store a payment record, for instance, in a tuple of the form `[customerEmail, cardLast4, amount, currency, timestamp]` when you could just use an object, have consistent names that self-document the data structure, and never need to think about the ordering of elements in tuples?

This is really only even marginally appropriate if you want to do something like this:

  return Object.entries(myObject)
    .filter(([, value]) => value % 2 === 0)
    .map(([key, value]) => `${key} has even value ${value}`);
Skipping the key in the `filter` call is probably straightforward enough that nobody is going to be confused about what's happening. But if you're doing this for a tuple of any significant length, you're just papering over a much more serious problem that's already present in your code.
  • postalrat 3 years ago

    The rare case for me is when you really care about size. The destructured variables can be renamed by the minifier while an object will keep the property names.

    • tonto 3 years ago

      maybe interesting: the obj destructuring may be a bit faster than array destructuing (and not destructuring at all is sometimes a bit faster too). setup a small benchmark here https://jsbench.me/eolakmvsor/1

      just storing the data and accessing it as a tuple seems to not be the significantly slow part, but instead its destructuring the array that can be a bit slow. i remember seeing some threads with e.g. useState hooks in react needing array destructuring optimizations, but appears to still be a bit slower https://docs.google.com/document/d/1hWb-lQW4NSG9yRpyyiAA_9Kt...

      caveat: depends on browser (chrome vs firefox behavior is different for example) and may vary over time

    • bastawhiz 3 years ago

      That's where gzip or brotli come in. In a lot of cases the number of bytes over the wire hardly changes.

TAForObvReasons 3 years ago

Alternative:

    let { 0: one, 2: three, 4: five } = nums;
gregors 3 years ago

I'd at least place an underscore as is common in other languages

let [one, _, three, _, five] = nums

edit: I guess you can't do that in JS, so

let [one, _two, three, _four, five] = nums

jakear 3 years ago

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)
travisd 3 years ago

I’d flag this if I saw this in a code review. It’s to cute and hard to see what’s happening. Would much rather just see someone prefix with an underscore if they don’t need the variable (const [id, _email, name] = loadUserInfo(…); is preferable to const [id, , name]).

friedman23 3 years ago

I code typescript every day. I don't really hate javascript. This is terrible.

  • iLemming 3 years ago

    After writing Clojure & Clojuresript for a few years, any language that spins around its syntax would feel terrible. Modern JavaScript looks like a 400-pound diabetic who brags about his skin folds, "check this out man, I can hide two full-sized cans of beer and you wouldn't even know it..."

    What's the point of this cabalistic trick with commas? How does it improve anything about code? Readability, parseability, formatting, reasoning? I feel we're moving towards the day when the browsers would mark websites with a badge "built without use of JavaScript", so we know it can be trusted.

  • rubychill 3 years ago

    You can still do this in Typescript.

    • friedman23 3 years ago

      I never implied you couldn't? I was just saying I'm not a javascript or typescript hater.

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection