**Converting negative to positive:**Here in this article we will learn how in JavaScript we can convert any negative number to positive number. This can be done in two different ways.

For example we can use simple mathematics logic or we can use build-in function. But we also want to know which method is faster in converting negative number to positive.

## 2 ways to convert negative number to positive.

- Using simple mathematics logic
- Using pre-build function Math.Abs()

## Method 1: Using mathematics logic.

Here first we have to make sure that the value should be negative, for that we can check with if condition that number value should be less then 0 (ZERO). So we can multiply it with -1, as by multiplying it gives us a

**positive value**.Let see how our JavaScript code look

```
// function which convert negative value to positive.
function ConvertToPositive(foo){
var bar=0;
// check our value should be in negative
if(foo<0)
{
bar=foo*-1; // multiply by -1
}
// return positive value;
return bar;
}
```

Now we call this JavaScript function , which gives alert message with the positive value. See the below code

```
// declare variable and assign negative value to it.
var foo=-10;
```

alert(ConvertToPositive(foo));

Its simply gives alert message which call our js function

**ConvertToPositive**and return a positive value.Wow!! we are done with method 1.

## Method 2: Using Math.Abs() function.

JavaScript function

**Math.Abs()**return the absolute value of the given number. If the given value is not a number, then it return NAN. And if given number is null, then it return 0.Now look at our below JavaScript code, to see the usage of

**math.abs()**pre-build function.```
var foo = Math.abs(-13);
```

var bar = Math.abs(null);

Here foo return positive value as 13, and bar result zero as it have null value.

**Conclusion:**Here we learn 2 different method for converting negative number to positive number in JavaScript. In method 1 we use simple mathematics logic, and in method 2 we use JavaScript pre-build Math.abs() function.

Both method gives us desired output. But as per benchmark method 1 i.e using mathematic logic is faster then math.abs() pre-buld function.

**Other Resource:**

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

** PS:** If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Post Comment

Your email address will not be published. Required fields are marked *