Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

What is Decrement Operator in JavaScript



The decrement operator in Javascript decreases an integer value by one. This operator is often utilized in loops, counters, and mathematical computations where a value has to be decreased sequentially.

Types of Decrement Operators

The decrement operator (--) can be used in two ways ?

  • Post-decrement (x--):  It provides the current value of the variable prior to its decrement.
  • Pre-decrement (--x): It first decreases the value and then returns the variable's new value.

Syntax

x--;  // Post-decrement
--x;  // Pre-decrement

Example

Below is an example where the value of a is pre-decremented twice using the decrement operator twice ?

<html>
   <body>
      <script>
         var a = 33;
         a = --a;
         document.write("--a = ");
         result = --a;
         document.write(result);
      </script>
   </body>
</html>

Output

--a = 31

Example

Below is an example where the value of a is post-decremented twice using the decrement operator twice ?

<html>
   <body>
      <script>
         var a = 33;
         a = a--;
         document.write("a-- = ");
         result = a--;
         document.write(result);
      </script>
   </body>
</html>

Output

a-- = 33

Conclusion

The decrement operator in JavaScript is the simplest means of reducing a variable by 1. Much of its extensive use is within loops, counters, and calculations. But remember that when post-decrementing, it doesn't change the value right away, which can be a bit tricky sometimes

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-03-11T19:32:55+05:30

555 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements