Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

178
Views
Shorthand for if/else in javascript

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));
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

In the solution below, the numCheck() method is tested by using the Array.prototype.map() method, considering three possible situations.

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

const numbers = [1, -1, 0];

console.log(numbers.map(number => numCheck(number)));

about 4 years ago · Juan Pablo Isaza Report

0

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 ) ) 

about 4 years ago · Juan Pablo Isaza Report

0

A shorter solution:

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!