16

I prefer this:

const foo = x => x + 1;

to this:

function foo(x) {
  return x + 1;
}

Is there an rule to enforce this?

sdgfsdh
  • 28,918
  • 18
  • 108
  • 208
  • 8
    Since they're not freely interchangeable, you probably *shouldn't*. – deceze Oct 05 '18 at 15:52
  • 4
    It's worth noting that those two are not necessarily equivalent, and enforcing one over the other could cause issues: https://stackoverflow.com/a/34361380/1650337 – DBS Oct 05 '18 at 15:53
  • @DBS I am not using features likely to cause issues (such as `this`) either – sdgfsdh Oct 05 '18 at 16:21

2 Answers2

10

You can use this ESLint prefer-arrow-callback rule which would flag with error/warning anywhere you could use an arrow function instead of a function expression

Kevin Amiranoff
  • 11,641
  • 7
  • 47
  • 85
5

Anser based on @JohannesEwald comment and @KevinAmiranoff answer.

I'm using the following rules:

https://www.npmjs.com/package/eslint-plugin-prefer-arrow

https://eslint.org/docs/rules/prefer-arrow-callback

https://eslint.org/docs/rules/func-style

npm install -D eslint-plugin-prefer-arrow

.eslintrc or package.json with eslintConfig:

"plugins": [
  "prefer-arrow"
],
"rules": {
  "prefer-arrow/prefer-arrow-functions": [
    "error",
    {
      "disallowPrototype": true,
      "singleReturnOnly": false,
      "classPropertiesAllowed": false
    }
  ],
  "prefer-arrow-callback": [
    "error",
    { "allowNamedFunctions": true }
  ],
  "func-style": [
    "error",
    "expression",
    { "allowArrowFunctions": true }
  ]
}

I think this works really well. If you need to disable the rules for a specific line I do it like this:

// eslint-disable-next-line func-style, prefer-arrow/prefer-arrow-functions
Ogglas
  • 50,115
  • 30
  • 272
  • 333