Push returns the length of the array, though, so that won't work.
(acc.push(2*n), acc)
In an expression position, the push statement will be executed, then its return will be discarded, and the final expression will be the result of the expression. Is it “better”? Almost certainly not. But it lets you stay in expression syntax while executing statements. (Much more useful for logging than meaningful runtime side effects IMO, but I think it should be more widely known in general.)Edit: and I’m glad to see another reference to it down thread!
[1, 2, 3, 4, 5].reduce((acc, n) => n % 2 === 1 ? acc.concat([2*n]) : acc, []) [1, 2, 3, 4, 5].reduce((acc, n) => (n % 2 ? acc.push(2*n) : null, acc), []) let input = [1, 2, 3, 4, 5], output = [];
for (let i = 0; i < input.length; ++i) {
let n = input[i];
if (n % 2) output.push(2*n);
}
return output;
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.FWIW, it's 2022:
const output = [];
for (const n of [1, 2, 3, 4, 5]) {
if (n % 2) output.push(2 * n);
}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; [1, 2, 3, 4, 5].reduce((acc, n) => n % 2 === 1 ? [ ...acc, 2 * n ] : acc, [])