Use Arrow Functions
Arrow functions are a concise syntax that can often replace the regular function syntax.
For example, function(x, y) { return x * y }
can be replaced with (x, y) => { return x * y; }
.
However, arrow functions have different semantics and cannot replace regular functions in all cases.
In particular, the scope of arrow functions (including binding of this
) is established at creation time.
This difference makes arrow functions unsuitable for using them as methods, constructors,
and in call
, apply
, and bind
calls.
Learn More: Arrow Function Expressions (MDN)
This refactoring can change the semantics of your code in some cases.
Anonymous functions are converted into arrow functions unless there is direct usage of this
, arguments
, etc.
The replaced functions might be used in other parts of the codebase
in ways that are incompatible with arrow functions, for example:
- as methods
- as constructors
- with
bind
,apply
, orcall
In those cases, changing them into arrow functions may lead to undesired behavior and errors at runtime.
However, this refactoring does not convert functions that have reference to this
, unless they are
immediately bound, and will therefore prevent many of those errors.
const f = function() {
console.log("my function");
};
// problematic usages of 'f' that do not work with arrow functions somewhere else
// in the code, potentially in a different module:
const example1 = new f()
const example2 = {
exampleMethod: f
};
const example3 = f.bind(this);
Original Code
Changes
1 | const f1 = function (x) { | |
2 | return x * x; | |
3 | } | |
1 | const f1 = x => x * x | |
4 | 2 | |
5 | const f2 = function() { | |
3 | const f2 = () => { | |
6 | 4 | console.log(this); |
7 | }.bind(this); | |
5 | }; | |
8 | 6 | |
9 | 7 | const f3 = function named() { |
10 | 8 | console.log("not turned into arrow function"); |
11 | 9 | } |
Transformed Code
const f1 = x => x * x
const f2 = () => {
console.log(this);
};
const f3 = function named() {
console.log("not turned into arrow function");
}