dinmep
dinmep

Reputation: 127

Assignment to property of function parameter (no-param-reassign)

I have this function and while I have this working nicely, I'm getting ESLint error saying

57:5  error  Assignment to property of function parameter 'result'  no-param-reassign   
66:5  error  Assignment to property of function parameter 'result'  no-param-reassign

I'm unsure how to correctly resolve

export const fn = article => article.categoryValueDtoSet.reduce((result, item) => {
  if (item.language) {
    const language = item.language.languageValue;
    const category = item.categoryValue;
    result[language] = category;
  }
  return result;
}, { it: undefined, de: undefined, en: undefined );

I did some research and it seems I need to use Object.assign and I tried it, but probably did it wrong. How should I write my function, that I can resolve my problem?

Upvotes: 3

Views: 20152

Answers (1)

Son Nguyen
Son Nguyen

Reputation: 1482

This is a common ESLint issue that appears frequently on old codebase. You have modified the result variable which was passed as parameter. This behavior is prohibited by the rule.

To resolve it, copy the argument to a temporary variable and work on it instead:

export const fn = article => article.categoryValueDtoSet.reduce((res, item) => {
    const result = {...res}; // if result is object
    // const result = [...res]; // if result is array
    // Rest of your code can work without change
}

Note: The object spread operator is sugar syntax for Object.assign(). Both it and the array copy is not deep here for simplicity sake and could cause side effects because you are still accessing the original individual elements of the source object or array. Prefer to use a deep copy instead.

Upvotes: 10

Related Questions