Home > Back-end >  I'm doing a function of inverting values, and the 0, is also inverting, how do I make the 0 not
I'm doing a function of inverting values, and the 0, is also inverting, how do I make the 0 not

Time:06-16

Code in Javascript, please help me to make 0 not negative

function invertSign(val) {

    return (val * -1);
}

console.log(invertSign(1)) -1
console.log(invertSign(-2)) 2
console.log(invertSign(0)) -0

CodePudding user response:

You can use || 0:

function invertSign(val) {
   return -val || 0;
}

If -val evaluates to -0, it will be a falsy value, and so the || operator will evaluate to the second operand, which is 0. And so -0 is replaced by 0.

Alternatively, you subtract from 0:

function invertSign(val) {
   return 0 - val;
}

Here -0 never occurs, because the minus here is not a unary operator, but the binary one. 0 - 0 is just 0, so this may be the simplest solution.

CodePudding user response:

You can check if the value is zero, and if it is, then return 0


function invertSign(val) {
    if (val === 0) return 0;
    return (val * -1);
}

CodePudding user response:

Try adding an if statement to check if val === 0.

function invertSign(val) {
    if (val === 0) return val;
    return val * -1;
}

console.log(invertSign(1)); // logs -1
console.log(invertSign(-2)); // logs 2
console.log(invertSign(0)); // logs 0
  • Related