JavaScript – Decrement (–)

JavaScript Decrement (–) Arithmetic Operator is used to decrement the given number by one.

Decrement Operator Symbol

The symbol used for Decrement Operator is --. There should be no space between the two - symbols.

Syntax

The syntax to use Decrement Operator with an operand is

</>
Copy
operand--
--operand

The first notation operand-- is called post-decrement, and the second notation --operand is called pre-decrement.

Post-decrement means, the value of the operand is decremented after the execution of current statement.

Pre-decrement means, the value of the operand is decremented and then the current statement is executed.

In both the cases, the Decrement operator modifies the original operand, and also returns the value.

Examples

In the following example, we take a numeric value and decrement it by using using Decrement (–) Operator.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var a = 4;
        document.getElementById('output').innerHTML += 'Original Value    : ' + a;
        a--;
        document.getElementById('output').innerHTML += '\nDecremented Value : ' + a;
    </script>
</body>
</html>

In the following example, we try to show the difference between pre-decrement and post-decrement notations.

Post-Decrement

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var a = 4;
        document.getElementById('output').innerHTML += 'a      : ' + a;
        var result = a--;
        document.getElementById('output').innerHTML += '\nAfter decrement\na      : ' + a;
        document.getElementById('output').innerHTML += '\nresult : ' + result;
    </script>
</body>
</html>

The value in result is same as a, because a is decremented after the execution of this assignment statement let result = a++;. Therefore, result is assigned with the value of a which is 4, and for the next statement, the value of a becomes 3, hence post-decrement.

Pre-Decrement

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var a = 4;
        document.getElementById('output').innerHTML += 'a      : ' + a;
        var result = --a;
        document.getElementById('output').innerHTML += '\nAfter decrement\na      : ' + a;
        document.getElementById('output').innerHTML += '\nresult : ' + result;
    </script>
</body>
</html>

Since, in pre-decrement, a is decremented first and then assigned to result, the value in result is 3.

Conclusion

In this JavaScript Tutorial, we learned about Arithmetic Decrement Operator, its syntax, and usage with examples.