How to Decrement a Number with JavaScript

Posted by

To decrement a number in JavaScript, you can use the -- operator. This operator subtracts 1 from the value of a number.

Here’s an example of how you can use the -- operator to decrement a number:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let num = 10;

num--;

console.log(num); // Output: 9

[/dm_code_snippet]

You can also use the -= operator to subtract a specific value from a number. For example:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let num = 10;

num -= 5;

console.log(num); // Output: 5

[/dm_code_snippet]

You can also use the Math.max() function to decrement a number. This function returns the maximum of a set of numbers. You can use it like this:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let num = 10;

num = Math.max(num - 1, 0);

console.log(num); // Output: 9

[/dm_code_snippet]

Finally, you can use the while loop to decrement a number. Here’s an example:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

let num = 10;

while (num > 0) {
  num--;
}

console.log(num); // Output: 0

[/dm_code_snippet]