Javascript Decrement Operator | Pre and Post Decrement

Javascript Decrement Operator

In this article, we will see what is javascript decrement operator. The double minus sign (”–“) indicates the decrement operator. It allows us to decrement the current value of a variable by 1. It is divided into two types post decrement and pre-decrement.

Post decrement

syntax:

document.write(a--);

Value is decremented by ‘1’ only after printing the value.

Example:

var a = 10;
document.write("a =", a--); // a=10
document.write("a =", a--); //a=9
document.write("a =", a); //a=8
  1. In the above example code, we have created variable “a” and assigned the value “10”.
  2. Then print the variable “a” and the output is displayed as “a=10”.
  3. If you want to decrement the value of variable “a” by 1, you can use the Decrement operator like “a–“.
  4. After decreasing 1 value, then print the variable “a and the output is displayed as “a=9”. Because we decreased 1 value of the variable “a”.

Pre decrement:
syntax:

document.write(--a);

Value is decremented by ‘1’ only before printing the value.

Example:

var a = 10;
document.write("a =", --a); // a=9
document.write("a =", --a); //a=8
document.write("a =", --a); //a=7
  1. In the above example code, we have created variable “a” and assigned the value “10”.
  2. Then print the variable “a” using pre decrement and the output is displayed as “a=9”. Because we use pre decrement operator,

Leave a Reply