Why doesn't my arrow function return a value?

假如想象 提交于 2019-11-26 01:23:45

问题


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.)


回答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:

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


来源:https://stackoverflow.com/questions/45754957/why-doesnt-my-arrow-function-return-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!