Explain Codes LogoExplain Codes Logo

Convert a negative number to a positive one in JavaScript

javascript
functions
performance
best-practices
Anton ShumikhinbyAnton Shumikhin·Sep 25, 2024
TLDR

To convert any number to its positive equivalent in JavaScript, use Math.abs().

let positiveNumber = Math.abs(-42); // Output: 42, Life, Universe and Everything!

Alternative methods

While Math.abs() is straightforward, JavaScript offers several ways to flip a negative to positive.

The -1 multiplier

Flip the sign of a known negative number by multiplying it by -1.

let negativeValue = -42; let positiveValue = negativeValue * -1; // Output: 42, positively universal!

The sign inversive -x

Use a minus operator before a variable to inversely flip its sign, also known as talking to the -x.

let value = -42; let positiveValue = -value; // Output: 42, playing hide and seek with the minus sign!

Flip n' assign x *= -1

The *= operator is handy in loops and iterative logics to dynamically switch a number's sign.

let value = -42; value *= -1; // Now, value is positive 42 - transformation complete!

Playing opposites with -y

Assign negated value of another number to convert from negative to positive.

let y = -42; let x = -y; // x is now positive 42 - y's evil twin!

Attending special cases

Be guarded and know how to handle special cases:

  • For non-numeric values, Math.abs() returns NaN - Not-a-Number party!
  • null or empty input in Math.abs() returns 0, a technically positive number - Null's secret positive identity!
  • Be conscious of the number precision limit when dealing with large numbers.

Advanced usage and performance

For more performant solutions or creative uses, have a look at these options:

Bitwise operator ~~

Used in conjunction with negation, the Bitwise NOT (~~) operator can quickly convert values, but be cautious.

let value = -42; let positiveValue = ~~value > 0 ? value : -value; // Output: 42, Bitwise or bitlazy?

Abstracting to functions

Consider moving logic into a function for better reusability and readability.

function toPositive(num) { return Math.abs(num); } let result = toPositive(-42); // result is 42. The force is positive with this one.

Performance implications

In some cases, the performance can differ between these methods. Don't forget always to benchmark these methods against each other to find out the faster operation.