0

I'm running two seemingly identical statements to check whether a number is positive, negative or zero.

The if statement returns the expected result.

The switch statement always returns the default.

Why?

In this example I pass "2" (type: number) and I get + in the if statement and ? in the switch statement.

// Verify whether a number is positive, negative or Zero:

function myFuncIf(y) {
  let result = null;
  console.log("y is " + y);
  console.log("y is " + typeof(y));

  if (y > 0) {
    return "+";
  } else if (y < 0) {
    return "-";
  } else {
    return "?";
  }
}

function myFuncSwitch(y) {
  let result = null;
  console.log("y is " + y);
  console.log("y is " + typeof(y));

  switch (y) {
    case (y > 0):
      result = "+";
      break;
    case (y < 0):
      result = "-";
      break;
    default:
      result = "?";
  }
  return result;
}
console.log(myFuncIf(2));
console.log(myFuncSwitch(2));
zstolar
  • 461
  • 1
  • 4
  • 9
  • 5
    That's not how the `switch ... case ...` statement works: _"The `switch` statement **evaluates an expression, matching the expression's value to a `case` clause**, and executes statements associated with that case, as well as statements in cases that follow the matching case."_ ([Source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch)) – Andreas Aug 03 '20 at 10:14
  • Does this answer your question? [switch statement to compare values greater or less than a number](https://stackoverflow.com/q/32576618/1220550) – Peter B Aug 03 '20 at 10:15

1 Answers1

1

switch matches the value. The value of y is 2. Your first case will match True. Your second will match False.

You probably want your switch to look like this:

  switch (Math.sign(y)) {
    case (1):
      result = "+";
      break;
    case (-1):
      result = "-";
      break;
    default:
      result = "?";
  }

See docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign

Peaceful James
  • 1,807
  • 1
  • 7
  • 16