DEV Community

Rakshith holla
Rakshith holla

Posted on

3 3

Negative Number to Positive Number without using abs() - asked in a interview

In JavaScript, we have a method called absolute - abs() to convert a negative number into positive number.

Usage - Math.abs(-7);

Now, we will see how we can perform the same operation without using the built-in absolute method,

const negativeToPositive = num =>{
  if(num < 0){
    return num * -1;
  }
  return num;
}

console.log(negativeToPositive(-8));
Enter fullscreen mode Exit fullscreen mode

Here we have written a function which based on the input number given, converts the negative number input to positive and for positive number input, it just returns the number.

Hope this was helpful😊.

Top comments (3)

Collapse
 
aarone4 profile image
Aaron Reese

Why?
Under what circumstances would you NOT want to use abs()? If I saw that function name I would be assuming there was an edge case that abs on its own didn't handle

Collapse
 
rakshithholla profile image
Rakshith holla

Hi,

Sorry, I missed to add that this was asked in a interview. abs() works fine.

Collapse
 
aarone4 profile image
Aaron Reese

So another answer would be to convert it to a string, replace "-" with "" and convert back to a number.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay