JavaScript Arrow Functions: Things to Remember
Arrow functions. Some people love them, others couldn't care less. What is important, is that people do use them. As such, you must be aware of some of the differences they present when compared to a standard function.
Arrow functions are a succinct alternative to a conventional function expression, but are restrictive in some situations when compared to "traditional" function expressions.
Characteristics:
Do not have their own bindings to
thisorsuper. This is important when working with objects.Do not have
arguments, which are an Array-like object accessible inside functions that contain the values of the arguments passed to that function.Do not have the
new.targetkeyword, which is a pseudo-property that allows you to determine whether a function or constructor was called using thenewoperator.call,applyandbindbehave differently than when used in a regular function.Can not be used as
constructors, again, important when working with objects.Can not use
yield, within its body, which is used to pause and resume a generator function.
Return Characteristics:
Arrow functions may implicitly return values by simply omitting the curly braces that traditionally wrap a function's body if their body only contains a single expression.
With a simple expression, a
returnis not needed:
param => expression.
Multiple params require parentheses. With a simple expression, a
returnis not needed:
(param1, paramN) => expression.
Multiline statements require body brackets and return:
param => {
let a = 1;
return a + param;
}
When using implicit returns, object literals must be wrapped in parenthesis so that the curly braces are not mistaken for the opening of the function's body:
const foo = () => { bar: 1 } // foo() returns undefined
const foo = () => ({ bar: 1 }) // foo() returns {bar: 1}