My question is best illustrated with an example.
Is there a way to use syntax like
array.reduce(and)
instead of
array.reduce((a, b) => a && b)
in Javascript?
Similar questions hold for other binary operators, such as || + - *
and many, many others. A similar question exists for the !
operator, e.g., array.map(not)
.
EDIT:
Apologies, if not clear enough. I meant to ask whether JS has actual built-in aliases for the mentioned operators, like some other languages. I'm well aware that I can define my own functions to do this.
In effect, yes — they're called functions. :-)
const and = (a, b) => a && b;
let array = [true, false, true];
console.log(array.reduce(and)); // false
array = [true, true, true];
console.log(array.reduce(and)); // true
I've used an arrow function there, but it could be any kind of function.
JavaScript doesn't have any other way of doing that, but functions do the job nicely, providing reusable semantics for common operations.
I meant to ask whether JS has actual built-in aliases for the mentioned operators, like some other languages.
No — but the code you showed wouldn't be using an alias anyway. An alias would have looked like this: array.reduce((a, b) => a and b)