Leon Gaban
Leon Gaban

Reputation: 39018

Reduce function returning assignment is throwing error (ESLint issue: no-return-assign)

My code (which works):

const calculateBalance = (coins) => {
  console.log('coins', coins);
  return coins.reduce((bal, coin) => (bal += parseInt(coin.balance)), 0);
};

Basically I just want to add up all the coin balances in my portfolio, however I'm getting an eslint error.

Arrow function should not return assignment.

enter image description here

Googling I found this: https://eslint.org/docs/rules/no-return-assign

One of the interesting, and sometimes confusing, aspects of JavaScript is that assignment can happen at almost any point. Because of this, an errant equals sign can end up causing assignment when the true intent was to do a comparison. This is especially true when using a return statement.

Here they have an example of what to do:

function doSomething() {
    return (foo = bar + 2);
}

However that is what I implemented, but eslint is still complaining... is there a way to update my code block above to make it pass?

Upvotes: 0

Views: 1363

Answers (1)

Asons
Asons

Reputation: 87191

From the specs. (here MDN)

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.


As your bal is your accumulator, simply do bal + parseInt(coin.balance)

Upvotes: 2

Related Questions