Home > Enterprise >  Shorthand for if/else in javascript
Shorthand for if/else in javascript

Time:01-09

I wrote the function to check if a given number is positive, negative, or zero. Is there a shorthanded way?

Is it possible to test the condition with map (using object to index the conditions)? i was inspired by second solution in this question but not sure how it applies here.

const numCheck = (num) => {
  if (num == 0) {
    return "zero";
  } else {
    return num > 0 ? "positive" : "negative";
  }
};

const num1 = 3;
console.log(numCheck(num1));

CodePudding user response:

const numCheck = (num) => {
  return (num == 0) ? "zero" : ((num > 0) ? "positive" : "negative");
};

const num1 = 3;
console.log(numCheck(num1));

CodePudding user response:

you can do that, simply use Math.sign() :

const numCheck = n => ['negative','zero','positive'][1 Math.sign(n)]
 
console.log( numCheck( 4 ) ) 
console.log( numCheck( 0 ) ) 
console.log( numCheck( -3 ) ) 

CodePudding user response:

A shorter solution:

var numCheck = (num) => num == 0 ? "zero" : num > 0 ? "positive" : "negative";
const num1 = 3;
console.log(numCheck(num1));

  •  Tags:  
  • Related