Search code examples
javascriptarrow-functionseslint-config-airbnb

How to avoid "Arrow function expect to return a value" error in Airbnb ESLint


I am running eslint and it is recommended to return a value whenever an arrow function(lambda function) is used. Well that makes sense. However, I come across a case that is hard to walk around.

Dict = {}
Instances = [/* an array of items where items is a dictionary that contains data */]
Instances.map((item) => {
      Dict[item.name] = item.url;
});

My goal is to get the data from the Instances array and fill the dictionary Dict with it. I am using the array function to assign key value pair to the dictionary, but that violates the rule of the arrow function.

Is there any iteratools or functions other than map that would help me to achieve the goal, and avoid the rule violation?


Solution

  • Edit: This does not adhere to Airbnb's ES6 Style Guide.


    My goal is to get the data from the Instances array and fill the dictionary with it.

    Use .reduce

    .. and just pass an empty object as the accumulator, filling it up as you iterate through your array.

    const instances = [
     { name: 'foo', url: 'https://google.com' }, 
     { name: 'bar', url: 'https://stackoverflow.com' }
    ]
    
    const result = instances.reduce((dict, item) => {
      dict[item.name] = item.url
    
      return dict
    }, {})
    
    console.log(result)

    Why not .map?

    Array.map always returns a new Array and is meant for mapping each array element to another format.

    If your resulting data structure shouldn't be an Array, with the same length as the Array you are operating on, you should avoid using it.

    Why .reduce instead of .forEach?

    I use forEach only for doing "work" rather than transforming data. Transforming data is almost always achievable with just map and/or reduce.

    Here's what I mean by "work":

    const users = [userInstance, userInstance, userInstance]
    users.forEach(user => user.sendEmail('Hello World'))