How to Always Return a Negative Number in JavaScript?

Find out how to convert positive numbers to negative and leave negative numbers unchanged

To make sure that you always return a negative number in JavaScript, you can do either of the following:

Using Unary Negation Operator

You can convert the number to its absolute form, and then negate it using the unary negation operator (-):

-Math.abs(n)

This would convert a positive number to negative and ensure that an already negative number remains unchanged. For example, you can use this in the following way:

// ES6+
const neg = (num) => -Math.abs(num);

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

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

Using Arithmetic Operators

You can convert the number to its absolute form, and then negate it either by:

  • Multiplying or dividing the number by -1, or;
  • Subtracting the number from 0.
Math.abs(n) * -1
Math.abs(n) / -1
0 - Math.abs(n)

This would convert a positive number to negative and ensure that an already negative number remains unchanged. For example, you can use these in the following way:

// ES6+
const neg = (num) => Math.abs(num) * -1;

console.log(neg(1234)); // -1234
console.log(neg(-1234)); // -1234
// ES6+
const neg = (num) => Math.abs(num) / -1;

console.log(neg(1234)); // -1234
console.log(neg(-1234)); // -1234
// ES6+
const neg = (num) => 0 - Math.abs(num);

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

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


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