Re:Flatten Arrays in Vanilla JavaScript with Flat() and Flat...
by jacobolus on Wednesday January 05, 2022 @01:24PM
(#29812871)
Obviously you can alternately write:
But in some circumstances the other style can be more convenient / legible. The immediate question was about pushing to an array and then returning the array, for which the comma operator can be handy.
[ Parent
| on HN ]
Re:Flatten Arrays in Vanilla JavaScript with Flat() and Flat...
by wk_end on Wednesday January 05, 2022 @03:04PM
(#29814197)
No argument that the comma operator is a neat trick when you need it.
FWIW, it's 2022:
const output = [];
for (const n of [1, 2, 3, 4, 5]) {
if (n % 2) output.push(2 * n);
}
Re:Flatten Arrays in Vanilla JavaScript with Flat() and Flat...
by eyelidlessness on Wednesday January 05, 2022 @08:12PM
(#29817747)
Minority opinion: please `let` your mutable references. I know `const` doesn’t signal immutability, but we as humans with eyeballs and limited attention span certainly benefit from knowing when a value might change at runtime.
Re:Flatten Arrays in Vanilla JavaScript with Flat() and Flat...
by wk_end on Wednesday January 05, 2022 @11:19PM
(#29819337)
Disagree: virtually everything in JS is mutable, so this almost means "never use the `const` keyword". Pretending that the `const` keyword means something that it doesn't makes things harder for my limited human mind to understand, not easier. Plus using `let` inappropriately makes my linter yells at me, and I usually like to just do whatever my linter tells me.
Anyway, I use TypeScript, so if I really want to assert that my array is immutable (as immutable as stuff in JS-land gets anyway) I just write:
const input: readonly number[] = [1, 2, 3, 4, 5];
or even const input = [1, 2, 3, 4, 5] as const;
Re:Flatten Arrays in Vanilla JavaScript with Flat() and Flat...
by eyelidlessness on Wednesday January 05, 2022 @11:45PM
(#29819506)
I realize I could be clearer in what I’m asking for: please use const when you use reference types as values, and use let when you intend to mutate the reference. Using const and then changing a value is certainly allowed but it’s confusing and it’s missing an opportunity to signal in the code where changes might happen.
Re:Flatten Arrays in Vanilla JavaScript with Flat() and Flat...
by eyelidlessness on Wednesday January 05, 2022 @11:40PM
(#29819470)
I `readonly` and `as const` everything I possibly can. I do know that const doesn’t mean immutable, as I said, but I think it should and I think there’s value in establishing the idiom even if it’s not currently adopted. Because otherwise const basically means nothing unless you’re mutating everything already.