-2

I've got a question: whenever the code runs the output is false. Why?

    function isGreaterThan (numberOne, numberTwo) {
  switch (isGreaterThan) {
    case numberOne > numberTwo:
      return true;
      break;
    default:
      return false;
      break;
  }
}
console.log(isGreaterThan(67, 2));
  • 3
    You are you using a `switch` to do what an `if` would do best ? `switch` is meant for a "list" of possible options. – Isac Jun 07 '18 at 14:48
  • 5
    This is not a ternary operator example. – Kamil Naja Jun 07 '18 at 14:48
  • 2
    why not return the boolean expression instead of testing it and deciding to return `true` when it is `true`, and `false` when it is `false`? I mean: `return numberOne > numberTwo` is all you seem to need. – trincot Jun 07 '18 at 14:49
  • 1
    Cause `isGreaterThan` is a *function* and comparing it to a *boolean* with `case true` or `case false` will never match. – Jonas Wilms Jun 07 '18 at 14:53

3 Answers3

4

You could simplify this, to avoid the misuse of the switch statement:

function isGreaterThan (numberOne, numberTwo) {
  return numberOne > numberTwo;
}
console.log(isGreaterThan(67, 2));

Your switch statement is incorrect, in that you need to pass in a condition, and evaluate the outcome in each case statement.

Steve Vaughan
  • 2,163
  • 13
  • 18
2

This code is rather confused. For one thing, you're feeding to switch a reference to the function it lives in, not a numerical value.

You can greatly simplify the situation like so:

function isGreaterThan (numberOne, numberTwo) {
  return numberOne > numberTwo; //return the result of the comparison
}
Mitya
  • 33,629
  • 9
  • 60
  • 107
0

Your function is clearly not working as expected, because you are using a switch the wrong way.

First of all, you are switching using the function itself as an expression

switch (isGreaterThan) {

Then, you are comparing it with another expression

 case numberOne > numberTwo:

This is the equivalent of

if ( isGreaterThan == (numberOne > numberTwo))

And this check will never be true, because isGreaterThan is not even a boolean, but (numberOne > numberTwo) is

So this switch will always fallback to the default statement

default:
      return false;
      break;

That's why this function will always return false

As already mentioned from others, your function could work in this simple form

function isGreaterThan (numberOne, numberTwo) {
  return numberOne > numberTwo; 
}

Now, if you want an advise, I really think you don't understand how switch works, so please take a step back and learn how it's supposed to work. There was really no reason to use switch in this case.

By the way, a ternary operator (as mentioned in the title) in your case would work like

(numberOne > numberTwo) ? true : false
yannicuLar
  • 3,083
  • 3
  • 32
  • 50