We use the increment & Decrement operators to increase or decrease the value of the variable by one. Typescript uses the ++
(increment) & --
(decrement) to denote them. We can either prefix or Postfix these operators.
Table of Contents
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
1 2 3 4 5 | let x=10 ++x; //increment the value by one x=x+1 console.log(x); //11 |
1 2 3 4 5 6 | let x=10 x--; //decrement the value by one x=x-1 console.log(x); //9 |
Prefix & Postfix
There are two ways you can use the operator. One is before the operand, which is known as Prefix. The other method is to use it after the operand, which is known as Postfix.
Prefix Example
1 2 3 4 5 | let a=10; a++; console.log(a) // 11 |
Postfix Example
1 2 3 4 5 | let a=10; ++a; console.log(a) // 11 |
Difference Between Prefix & Postfix
When we use the ++
operator as a prefix as in ++a
- The value of the variable
a
is incremented by 1 - Then it returns the value.
1 2 3 4 5 6 | a=10; b=++a; //a is incremented, a is then assigned to b console.log(b); //11 console.log(a); //11 |
When we use the ++
operator as a Postfix as in a++
,
- The value of the variable is returned.
- Then the variable
a
is incremented by 1
1 2 3 4 5 6 | a=10; b=a++; //a is assigned to b, then a is incremented console.log(b); //10 console.log(a); //11 |
Reference
Read More
- Complete Typescript Tutorial
- Typescript Operators
- Arithmetic Operators
- Unary plus / Unary minus Operators
- Increment/Decrement Operators
- Comparison / Relational Operators
- Equality Operator / Strict Equality Operators
- Ternary Conditional Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
- Nullish coalescing operator
- Comma Operator in Typescript
- Operator Precedence