ES6 arrow function returns undefined instead of desired value

为君一笑 提交于 2020-12-08 05:08:51

问题


Easy function that works in JS without ES6:

var evenOrOdd = function(n){
   if(n % 2 == 1){
      return "Odd";
   } else {
      return "Even";
   }
}

console.log(evenOrOdd(3)); //returns odd

My attempt at restructuring this using ES6:

const evenOrOdd = (n) => {(n % 2 == 1) ? "Odd" : "Even"};

console.log(evenOrOdd(3)); //returns undefined

I'm following these examples here: 2ality and stoimen.

Why is this arrow function returning undefined?


回答1:


You have to remove the {}.

const evenOrOdd = n => (n % 2 === 1 ? "odd" : "even")

console.log(evenOrOdd(3)) //=> "odd"


来源:https://stackoverflow.com/questions/44852417/es6-arrow-function-returns-undefined-instead-of-desired-value

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