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.
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.
let x=10
++x; //increment the value by one x=x+1
console.log(x); //11
let x=10
x--; //decrement the value by one x=x-1
console.log(x); //9
Example of a decrement Operator.
let x=10
--x; //decrement the value by one x=x*1
console.log(x); //9
let x=10
x--; //decrement the value by one x=x*1
console.log(x); //9
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.
let a=10;
++a;
console.log(a) // 11
--a;
console.log(a) // 10
let a=10;
a++;
console.log(a) // 11
a--;
console.log(a) // 10
When we use the ++ operator as a prefix as in ++a
a=10;
b=++a; //a is incremented, a is then assigned to b
console.log(b); //11
console.log(a); //11
a=10;
b=--a; //a is decremented, a is then assigned to b
console.log(b); //9
console.log(a); //9
When we use the ++ operator as a Postfix as in a++,
a=10;
b=a++; //a is assigned to b, then a is incremented
console.log(b); //10
console.log(a); //11
a=10;
b=a--; //a is assigned to b, then a is decremented
console.log(b); //10
console.log(a); //9
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.
a=10;
b=5*--a;
console.log(b); //45
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)
a=10
b=(5*a--)+a
console.log(b); //59
Read More