3 ms·
I've never liked this corner of JS, and haven't kept up on ES6 or any of the modern dialects of JS, but it looks like `undefined` is still hanging around as a f
by philsnow 12y ago
I've never liked this corner of JS, and haven't kept up on ES6 or any of the modern dialects of JS, but it looks like `undefined` is still hanging around as a first-class thing?
const length = ([first, ...rest]) =>
first === undefined
? 0
: 1 + length(rest);
Having worked in languages that support multiple (destructuring or not) function definitions, this doesn't look quite right.
Here's something I typed into chrome's JS console:
> [1,2,3].length
3
> [undefined, 2, 3].length
3
Wouldn't the above-defined ES6 `length` function return 0 for the latter array?
To mock up a similar syntax that would handle this more gracefully (and more sensically):
const length = case
([]) => 0,
([first, ...rest]) => 1 + length(rest);
Wouldn't it be better in general to be able to destructure arguments using syntax? If you can't use a case-like syntax for this, what do you do to be able to handle different structures?
- peferron 12y agoYes, the ES6 `length` function would return 0 for [undefined, 2, 3]. I hope it was only used as an example in the article and nobody is planning to really use this. (Edit: see sibling comment; the article is already aware of this issue.) And yes, ES6 pattern matching is still quite limited.
- picks_at_nits 12y agoFrom the footnote: "Well, actually, this does not work for arrays that contain undefined as a value, but we are not going to see that in our examples. A more robust implementation would be (array) => array.length === 0, but we are doing backflips to keep this within a very small and contrived playground.” http://raganwald.com/2015/02/02/destructuring.html#fn:wellactually http://raganwald.com/2015/02/02/destructuring.html#fn:wellac...
- philsnow 12y agoah, thanks for pointing that out, I came here and ctrl+f'ed for 'undefined' but did not do the same in the article.