0

Does javascript have an equivalent to Python's operator.add, or any other binary operators?

In Python:

from operator import add
from functools import reduce

# prints 15, requires defining the addition operator
print(reduce(lambda a, b: a + b, [1, 2, 3, 4, 5]))

# prints 15, does not require defining the addition operator
print(reduce(add, [1, 2, 3, 4, 5]))

In Javascript:

// prints 15, requires defining the addition operator
console.log([1, 2, 3, 4, 5].reduce((a,b) => a + b))

// is there a way to do this without defining the addition operator?
console.log([1, 2, 3, 4, 5].reduce(???)

2 Answers 2

1

The way you have done it is the most concise way that I'm aware of in JavaScript. You might want to supply a default value for your reduce to protect against an empty input array:

console.log([1,2,3,4,5].reduce((a,b) => a + b, 0))

// throws a TypeError...
console.log([].reduce((a,b) => a + b))

Sign up to request clarification or add additional context in comments.

Comments

0

Javascript is a low level language : no way until you define it.

See Array.prototype.reduce

const add = (acc, item) => {
    return acc = acc + item;
});

console.log([1, 2, 3, 4, 5].reduce(add, 0));

1 Comment

JavaScript does not have a built-in function to add an array of numbers, but it's hardly a low-level language. That means something specific in computer science. en.wikipedia.org/wiki/Low-level_programming_language

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.