0

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?

gyre
  • 16,369
  • 3
  • 37
  • 47
Capella
  • 115
  • 1
  • 9
  • I also attempted replacing const with var and let (just to see) and nothing changed. – Capella Jun 30 '17 at 17:58
  • 3
    Remove the `{...}` around the function body. However, this has nothing to do with TCO because your function doesn't call another function. – Felix Kling Jun 30 '17 at 18:00
  • oh, interesting. I thought TCO were the ? and : --I'm learning. What's this called then? just optimization? and how do I give you "credit" for helping me? – Capella Jun 30 '17 at 18:01
  • 1
    `... ? ... : ...` is the [**conditional operator**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator). TCO is something that the runtime can do if there is a *function call* in tail position (basically meaning that a function call is the last operation in another function). I.e. for TCO to happen one would have to refactor their code to put a function call in tail position. But that has nothing to do with the conditional operator specifically. And again, there cannot be any TCO because your function doesn't call another function. – Felix Kling Jun 30 '17 at 18:02
  • TCO is something useful in the context of *recursive* functions. In your example, changing the code form an `if` statement to the condition operator is just "refactoring" the code. – Felix Kling Jun 30 '17 at 18:06
  • awesome. I'll see if I can adjust the tags. Appreciate the help and information. – Capella Jun 30 '17 at 18:13

2 Answers2

0

You have to remove the {}.

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

console.log(evenOrOdd(3)) //=> "odd"
gyre
  • 16,369
  • 3
  • 37
  • 47
Aftab Khan
  • 3,853
  • 1
  • 21
  • 30
0

(It may help others)

I'm trying to return a value from nested function, which is wrong

const isEmailExistsInDb = usrEmail => {
    userModel.countDocuments( {"email": usrEmail}, function (err, count){
        return tempCount > 0;
    });
};

Correct one is, have to return value from parent function

const isEmailExistsInDb = usrEmail => {
    let tempCount;
    mongoModel.countDocuments( {"email": usrEmail}, function (err, count){
        tempCount = count;
    });
    // count > 0 if document exists
    return tempCount > 0;
};
Bahu
  • 1,516
  • 2
  • 28
  • 49