Increment & Decrement Operators in JavaScript

We use the increment & decrement operators to increase or decrease the variable‘s value by one. JavaScript uses the ++ (increment) and — (decrement) to denote them. We can either prefix or postfix these operators. Increment & decrement operators operate on a single operand. Hence they are unary operators.

Syntax of Increment & Decrement Operator

Increment Operator ++x or x++. This is equal to x=x+1

Decrement Operator --x or x--. This is equal to x=x-1

Example of increment Operator.

Example of a decrement Operator.

Prefix & Postfix

There are two ways you can use the operator. One is before the operand, which is known as the prefix. The other method is to use it after the operand, known as Postfix.

Prefix Example

Postfix Example

Difference Between Prefix & Postfix

When we use the ++ operator as a prefix as in ++a

  1. The value of the variable a is incremented by 1
  2. Then it returns the value.

When we use the ++ operator as a Postfix as in a++,

  1. The value of the variable is returned.
  2. Then the variable a is incremented by 1

Precedence of the Increment & Decrement Operators

The increment & Decrement operators has a higher precedence than most other operators in JavaScript. You can refer to the Operator Precedence to know more about it.

In the code below, a is decremented first and then multiplied. Because — has higher precedence than multiplication.

In the following example a is returned for multiplication (a*10) and then decreased. Hence you will get the result 50

In the example below, a is returned for multiplication (5*10) and then decremented by 1. The new value of a is then added to the result (50+9= 59)

Reference

  1. Expressions & Operators
  2. Precedence & Associativity

2 thoughts on “Increment & Decrement Operators in JavaScript”

  1. i believe you have made a little mistake in your post and prefix example.
    postfix is a–, but you have it as –aa
    postfix means the operator comes after the variable.
    prefix is –a

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top