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

189
Views
I'm doing a function of inverting values, and the 0, is also inverting, how do I make the 0 not to be negative?

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

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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