JavaScript how to make a number negative

Learn how to make a positive number negative in JavaScript with an example.

Making a Number Negative in JavaScript

While a positive number is a number greater than 0, a negative number is a number less than 0. In JavaScript, you can make a number negative in a few different ways. Here are some examples.

Multiplying by -1

You can make a number negative in JavaScript by multiplying it by -1. For example:


let num = 10;

num = num * -1;

console.log(num); // Output: -10

The code above takes the number 10, multiplies it by -1, and assigns the value to the same variable, num. The result of the multiplication is -10, which is a negative number.

Using the Unary Negation Operator

Another way to make a number negative in JavaScript is to use the unary negation operator ( - ). The unary negation operator is a special type of operator that only takes one operand. For example:


let num = 10;

num = -num;

console.log(num); // Output: -10

In the code above, the unary negation operator is used to make the number 10 negative. The result of the operation is -10, which is a negative number.

Using the Math.abs() Method

The Math.abs() method is a built-in JavaScript method that returns the absolute value of a number. The absolute value of a number is the number without its sign. For example, the absolute value of 10 is 10, and the absolute value of -10 is 10. To use the Math.abs() method to make a number negative, you can do the following:


let num = 10;

num = -Math.abs(num);

console.log(num); // Output: -10

In the code above, the Math.abs() method is used to get the absolute value of the number 10. The result of the method is 10, which is then multiplied by -1 to make the number negative. The result of the multiplication is -10, which is a negative number.

Conclusion

In this article, we looked at how to make a number negative in JavaScript. We saw that it can be done by multiplying the number by -1, using the unary negation operator ( - ), or using the Math.abs() method.

Answers (0)