Convert a negative number to a positive one in JavaScript
To convert any number to its positive equivalent in JavaScript, use Math.abs()
.
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
.
The sign inversive -x
Use a minus operator before a variable to inversely flip its sign, also known as talking to the -x
.
Flip n' assign x *= -1
The *=
operator is handy in loops and iterative logics to dynamically switch a number's sign.
Playing opposites with -y
Assign negated value of another number to convert from negative to positive.
Attending special cases
Be guarded and know how to handle special cases:
- For non-numeric values,
Math.abs()
returnsNaN
- Not-a-Number party! null
or empty input inMath.abs()
returns0
, 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.
Abstracting to functions
Consider moving logic into a function for better reusability and readability.
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.
Was this article helpful?