How to resolve no-param-reassign error in a function

Viewed 764

In a Node/JS function, I'm getting ESLint no-param-reassign the code is for update a candidate as follow

update(candidate) {
    const { id } = candidate;
    if (!id) {
      throw new UserInputError('id is mandatory');
    }

    return this.tx(tableName)
      .returning(Object.values(columnsByProperties))
      .where('id', id)
      .update(prepareCandidate(candidate))
      .reduce((_, b) => camelcaseKeys(b), null)
      .then(x => {
        if (!x) {
          throw new UserInputError(`Candidate "id" with ${id} is not found`);
        }
        x.preferredContact = x.preferredContactHours;
        return x;
      });
  }

The error specifically is here Assignment to property of function parameter 'x'

.then(x => {
   if (!x) {
     throw new UserInputError(`Candidate "id" with ${id} is not found`);
     }
     x.preferredContact = x.preferredContactHours;
     return x;
});
1 Answers

You can replace:

x.preferredContact = x.preferredContactHours;
return x;

With this:

return { ...x, preferredContact: x.preferredContactHours };

This way you return a new object instead of modifying the function's parameter.

Now, elaborating a bit. As the rule's documentation says:

Assignment to variables declared as function parameters can be misleading and lead to confusing behavior, as modifying function parameters will also mutate the arguments object.

"Confusing behavior" is to be understood as, for example, odd side effects. I remember wreaking havoc in an app because inside a function, I mutated an array that was passed as a parameter. The array was also mutated in the calling code which was bad. That's the kind of thing ESLint helps prevent!

Related