How to Negate a Number in JavaScript?

Converting positive number to negative and vice versa in JavaScript

In JavaScript, you can negate a number (i.e. convert a positive number to negative, and a negative to positive) in the following ways:

Using Unary Negation Operator

You may negate a number using the unary negation operator (-) like so:

-n

This would convert a positive number to a negative number, and a negative number to a positive number. For example, you can use this in the following way:

// ES6+
const negate = (num) => -num;

console.log(negate(1234)); // -1234
console.log(negate(-1234)); // 1234

console.log(negate(0)); // -0
console.log(negate(-0)); // 0

You can rewrite the "negate" function as a function declaration/statement (instead of using arrow function), to support versions of ES prior to version 6.

Using Arithmetic Operators

You may convert a positive number to negative or vice versa by simply multiplying it by -1:

n * -1

Similarly, you may also divide the number by -1 to negate it:

n / -1

You could use either of these, for example, like so:

const negate = (num) => num * -1;

console.log(negate(1234)); // -1234
console.log(negate(-1234)); // 1234

console.log(negate(0)); // -0
console.log(negate(-0)); // 0
const negate = (num) => num / -1;

console.log(negate(1234)); // -1234
console.log(negate(-1234)); // 1234

console.log(negate(0)); // -0
console.log(negate(-0)); // 0

As an alternative to dividing and multiplying by -1, you may subtract the number from 0 instead:

0 - n

One important difference in subtracting the number from 0 is the fact that this returns 0 for both, positive and negative 0. This is different from dividing and multiplying by -1, which returns -0 when 0 is negated.

For example, you could use it in the following way:

const negate = (num) => 0 - num;

console.log(negate(1234)); // -1234
console.log(negate(-1234)); // 1234

console.log(negate(0)); // 0
console.log(negate(-0)); // 0

Hope you found this post useful. It was published . Please show your love and support by sharing this post.