33

I have an arrow function that looks like this (simplified):

const f = arg => { arg.toUpperCase(); };

But when I call it, I get undefined:

console.log(f("testing")); // undefined

Why?

Example:

const f = arg => { arg.toUpperCase(); };
console.log(f("testing"));

(Note: This is meant to be a clean, canonical dupetarget for the specific issue with arrow functions above.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 3
    See also [Curly Brackets in Arrow Functions](https://stackoverflow.com/q/35440265/1048572) and [When should I use a return statement in ES6 arrow functions](https://stackoverflow.com/q/28889450/1048572) – Bergi Aug 10 '21 at 16:42

1 Answers1

39

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()});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875