useArrowFunction
Diagnostic Category: lint/complexity/useArrowFunction
Since: v1.0.0
Sources:
- Inspired from:
prefer-arrow-callback
Description
Section titled DescriptionUse arrow functions over function expressions.
An arrow function expression is a compact alternative to a regular function expression,
with an important distinction:
this
is not bound to the arrow function. It inherits this
from its parent scope.
This rule proposes turning all function expressions that are not generators (function*
) and don’t use this
into arrow functions.
Examples
Section titled ExamplesInvalid
Section titled Invalidconst z = function() { return 0;}
code-block.js:1:11 lint/complexity/useArrowFunction FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This function expression can be turned into an arrow function.
> 1 │ const z = function() {
│ ^^^^^^^^^^^^
> 2 │ return 0;
> 3 │ }
│ ^
4 │
ℹ Function expressions that don’t use this can be turned into arrow functions.
ℹ Safe fix: Use an arrow function instead.
1 │ - const·z·=·function()·{
2 │ - ····return·0;
3 │ - }
1 │ + const·z·=·()·=>·0
4 2 │
const delegatedFetch = async function(url) { return await fetch(url);}
code-block.js:1:24 lint/complexity/useArrowFunction FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This function expression can be turned into an arrow function.
> 1 │ const delegatedFetch = async function(url) {
│ ^^^^^^^^^^^^^^^^^^^^^
> 2 │ return await fetch(url);
> 3 │ }
│ ^
4 │
ℹ Function expressions that don’t use this can be turned into arrow functions.
ℹ Safe fix: Use an arrow function instead.
1 │ - const·delegatedFetch·=·async·function(url)·{
2 │ - ····return·await·fetch(url);
3 │ - }
1 │ + const·delegatedFetch·=·async·(url)·=>·await·fetch(url)
4 2 │
Valid
Section titled Validconst f = function() { return this.prop;}
Named function expressions are ignored:
const z = function z() { return 0;}
Function expressions that declare the type of this
are also ignored:
const z = function(this: A): number { return 0;}
How to configure
Section titled How to configure{ "linter": { "rules": { "complexity": { "useArrowFunction": "error" } } }}