Why doesn't my arrow function return a value?Why doesn't my arrow function return a value? - Solution Checker - solutionschecker.com - Find the solution for any programming question. We as a solution checker will focus on finding the fastest possible solution for developers. Main topics like coding, learning.

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:


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

Solution 1

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:


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()});