Check if two integers have the same sign

Fewer characters of code, but might underflow for very small numbers:

n1*n2 > 0 ? console.log("equal sign") : console.log("different sign or zero");

Note: As @tsh correctly mentioned, an overflow with an intermediate result of Infinity or -Infinity does work. But an underflow with an intermediate result of +0 or -0 will fail, because +0 is not bigger than 0.

or without underflow, but slightly larger:

(n1<0) == (n2<0) ? console.log("equal sign") : console.log("different sign");

Use bitwise xor

n1^n2 >= 0 ? console.log("equal sign") : console.log("different sign");

You can multiply them together; if they have the same sign, the result will be positive.

bool sameSign = (n1 * n2) > 0

Tags:

Javascript