DEV Community

Rakshith holla
Rakshith holla

Posted on

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.