Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,845 questions

55,674 answers

573 users

How to check whether a number is positive/zero/negative without using conditional statements in JavaScript

1 Answer

0 votes
let n = 89;

// create text labels for each possible case
const result = [
    "negative",  // index 0
    "zero",      // index 1
    "positive"   // index 2
];

// compute an index without using any conditional statements
// (n > 0) becomes 1 if true, 0 if false
// (n < 0) becomes 1 if true, 0 if false
// index = 1 + (n > 0) - (n < 0)
let index = 1 + (n > 0) - (n < 0);

// print the classification
console.log(result[index]);

/*
  Checks:

  n = -3
  (n > 0) = 0
  (n < 0) = 1
  index = 1 + 0 - 1 = 0
  result = negative

  n = 0
  (n > 0) = 0
  (n < 0) = 0
  index = 1 + 0 - 0 = 1
  result = zero

  n = 89
  (n > 0) = 1
  (n < 0) = 0
  index = 1 + 1 - 0 = 2
  result = positive
*/



/*
run:

positive

*/

 



answered Jun 27 by avibootz

Related questions

...