HOWTO · JavaScript
JavaScript Negative Number
In this article, learn how to work with negative numbers in JavaScript. Discover methods for creating negative values through direct assignment, mathematical operations, and the Math library. Enhance your programming skills and understand the significance of negative numbers in various applications.
On this page
This JavaScript example assigns two numeric values and prints them:
const whole = -10;
const decimal = -3.14;
console.log(whole);
console.log(decimal);
-10
-3.14
Create a negative number with the unary minus
Place the unary minus operator (-) before a numeric literal or variable to get its opposite. Write a literal such as -10 or -3.14 when the value is known in advance. For a variable that may contain either sign, -value reverses its sign; it does not guarantee a result below zero. For example, negating -4 gives a positive value. Use a comparison when the goal is to classify a value rather than change it.
Use arithmetic to calculate a negative result
Subtraction can produce a value below zero when the amount subtracted is greater than the starting value, as in 5 - 10. Adding a value written with a minus sign, as in 5 + (-3), reduces the starting value. These are ordinary arithmetic expressions, so choose them when the calculation itself determines the result.
Multiplication by -1 reverses the sign of a numeric value: value * -1 is equivalent to -value. This is useful when sign reversal is the intent. It is not a general way to force a value below zero: a negative input becomes positive, and zero remains zero in magnitude. If the input can have either sign and the result must not be positive, use the Math.abs() approach in the next section.
Make a value non-positive with Math.abs()
Math.abs(value) returns the absolute value, or magnitude, of a number. Negate that result with -Math.abs(value) to get a value that is never greater than zero. This is the appropriate choice when a numeric input may have either sign and the result should be non-positive.
For example, Math.abs(-25) returns 25, and -Math.abs(25) produces -25. If value is 0, the expression evaluates to negative zero (-0), which compares equal to zero and is not less than zero. A non-numeric input that cannot be converted to a number produces NaN; validate or convert input separately if callers can provide text or other non-numeric values. Math.abs() is a built-in function; it is not necessary to multiply its result by -1 unless you also want to reverse the sign.
Check whether a number is negative
Use value < 0 to check whether a number is below zero. This comparison returns true for negative numbers and false for positive numbers and either form of zero. It checks the sign without changing the value. If input may not already be numeric, convert and validate it before relying on this comparison, since JavaScript coercion can affect comparisons involving strings and NaN never compares as less than zero.