4 ms·
> why does `...` use iterators?? If you couldn't use the iterator protocol, generators in particular would be a lot less powerful
by zero_shift 3y ago
> why does `...` use iterators??
If you couldn't use the iterator protocol, generators in particular would be a lot less powerful
- mmastrac 3y agoI think the JS spec would have been better served with a different syntax for generator/iterator destructuring. Most code I've seen assumes that: [a, b, ...rest] = array is implemented like this: a = array[0] b = array[1] rest = array[2...] When instead it is a giant performance footgun to the point where it should only be used outside of performance critical code. EDIT "next -> rest"
- postalrat 3y agoI don't assume it's implemented like "next = array[2...]". I don't even know what that means.
- mmastrac 3y agoSorry, I assumed that most people could understand the pseudocode syntax for a subarray operation. In Javascript, this is: array.slice(2)
- depressedpanda 3y agoI understood it, without even thinking about it. In my opinion it's more elegant than the real syntax, and I didn't even realize it wasn't real JavaScript until this comment thread made me look again.
- nightpool 3y agoIs it not able to be specialized like that when the object is a (non-sparse) array? What is preventing engines from making that optimization?
- IainIreland 3y agoIt's possible. We have plans to do so. There are a bunch of finicky corner cases, though. For example, destructuring will call the `return` method of the iterator when it's done (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...), so we have to be careful if somebody has defined `return` on the Array iterator prototype. You can supply a default value when destructuring, which is lazily evaluated, so we have to be careful about arbitrary side-effects taking place in the middle of the destructuring. We need to be able to fall back to something less optimized if we suddenly see a generator, or a user-written iterator. And so on. Fundamentally, it's the same thing that impedes most optimizations: there are hundreds of different patterns we could optimize, it takes a fair bit of thought to get it right, and we have finite resources, so we have to pick and choose. This particular pattern turns out to be idiomatic in a lot of React code, which is why we're looking at it now. (Or so people tell me; most JS I write is gross little testcases.)
- zamadatix 3y agoThanks for taking the time to drop these nuggets throughout the thread.