Home > Mobile >  JavaScript return condition
JavaScript return condition

Time:10-14

Is it possible to have conditions in return in JavaScript?

Like in this case:

if
  (A > 0 || B > 0)
    return "A";
  else return "C"

As long as A or B is > 0 return the one that is > 0 (so A or B). Is that possible? Like another condition as return, for example?

CodePudding user response:

Maybe this is similar to what you are trying to do. My function eval() takes two parameters A and B, and checks different conditions to see which is the positive number. I am using the Logical AND && instead of || because I want my code to know the value of each parameter in each condition.

function eval(A, B) {
  if (A > 0 && B <= 0) {
    console.log("A");
  }
  if (A <= 0 && B > 0) {
    console.log("B");
  }
  if (A > 0 && B > 0) console.log("Both A and B are positive numbers");
}

eval(2, -5);
eval(0, 8);
eval(1, 1);

CodePudding user response:

if(A > 0 || B > 0)
    return A > 0 ? "A" : "B";
else return "C";

CodePudding user response:

Try this.

    return (A > 0 || B > 0) ? "A" : "C"

It's a ternary operator. Here you have more information: Conditional (ternary) operator

  • Related