[1, 2, 3] + [4, 5, 6] // -> "1,2,34,5,6"
[,,,].length // -> 3
[1, 2, 3] + [4, 5, 6] // -> "1,2,34,5,6"
[,,,].length // -> 3
The second is only weird in that you are constructing an array with implicit undefined values, which is exactly what I would expect to happen if my linter didn't complain about the syntax and I had to guess what might be happening.
Like GP said, comes from other languages. That line can be copy/pasted into python and it performs concatenation.
> [1, 2, 3] + [4, 5, 6] // -> "1,2,34,5,6"
What would you expect instead?
> [,,,].length // -> 3
Is there any use case where you would want to deal with sparse arrays?
> What would you expect instead?
If I let my first instinct speak:
[1,2,3,4,5,6]
And then if I think a little more, then maybe:
[5,7,9] //with obvious caveats
In no way do I expect what GP actually provided.
[1] https://tc39.es/ecma262/multipage/ecmascript-language-expres...
I am very happy with JS and TS and I think the coercion rules are easily worked around with linter rules and policies, but they are definitely weird and I think the language would be better if it simply threw exceptions instead. But then, such an issue shoud not be surprising for a language that was designed in 10 days.
If someone does not like the ECMAScript specification, that is fine. But at least use a proper unofficial documentation like MDN.
If you ask experts it is because you want to get an actual correct answer, but if you ask neophytes it is because you want to get an answer that might be obvious even if not correct.
An addition operation over two numerical vectors of length 3.
I would expect the result to match its inputs and provide a numerical vector of length 3.
Thus: [5, 7, 9]
So if applying an operator to arrays spread the operation across all the elements that way, it would imply that the same should happen generally for all object properties, with whatever weird implications that would entail.
a.foo = 1
b.foo = 'there'
a + b // { foo: '1there' } ?Not really. Now explain why [,,,].map((e,i) => i) is [,,,] instead of [1,2,3] please ;)
Array(4) // [empty × 4]
a=[]; a.length=4; a // [empty × 4]
Array(4).map(n => n) // [empty × 4]
[,,1,,].map(n => n) // [empty × 2, 1, empty]
My go-to way of avoiding this annoyance is "Array.from(Array(N))": Array.from(Array(4)).map((n,i) => i) // [0, 1, 2, 3]
Alternately there's a recent "fill" method, that assigns all elements (including empty ones) to a given value: Array(4).fill(1) // [1, 1, 1, 1]I don't think this is too weird if you think about it. JS allows trailing commas, so the last one is ignored. Effectively this is `[ undefined, undefined, undefined, ]`. A syntax error would have made sense here, but the length of three is a result of the usual syntax rules, not a particular strange quirk of JS.
"WAT $a .= "World!"; ?"