Arrow functions can have either a concise body or the usual block body. In a concise body, only an expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return statement.
An arrow function saves the binding of this in the closure that's created when the function is created. So it doesn't set this to the context of the call to the function. In your case, this was bound to window when you created the object, so this.
The most common and standard way of returning an object from an arrow function would be to use the longform syntax: const createMilkshake = (name) => { return { name, price: 499 }; }; const raspberry = createMilkshake('Raspberry'); // 'Raspberry' console.
An arrow function doesn't have its own this value. Instead, it uses the this value of the enclosing lexical scope. An arrow function also doesn't have the arguments object. Avoid using the arrow function for event handlers, object methods, prototype methods, and functions that use the arguments object.
When you use the function body version of an arrow function (with {}
), there is no implied return
. You have to specify it. When you use the concise body (no {}
), the result of the body expression is implicitly returned by the function.
So you would write that either with an explicit return
:
const f = arg => { return arg.toUpperCase(); };
// Explicit return ^^^^^^
or with a concise body:
const f = arg => arg.toUpperCase();
Examples:
const f1 = arg => { return arg.toUpperCase(); };
console.log(f1("testing"));
const f2 = arg => arg.toUpperCase();
console.log(f2("testing"));
Slightly tangential, but speaking of {}
: If you want the concise arrow's body expression to be an object initializer, put it in ()
:
const f = arg => ({prop: arg.toUpperCase()});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With