Increment operators, which alter numbers and data in our code, are a vital feature of every programming language. It is one of the most commonly used characteristics in almost every modern programming language. In the world of programming, Javascript is said to be the most of confusing and mysterious language for some of its unnatural behavior compared to other languages. To the new JS programmer, sometimes it creates a lot of confusion to get a topic at its finest.
However, to get right into the discussion of incremental operators in Javascript, there are two types of increment operators in JavaScript: post-increment and pre-increment. Understanding the difference between these two operators is crucial for writing efficient and error-free code because sometimes it creates a bit of confusion about when and where to use both post and pre-increment. Let's explore this-
Post-increment operator
The post-increment operator increments the operand's value after it has been evaluated. This signifies that the increment procedure will increase the operand's value after it has been evaluated and then increment the value. We can consider the following example:
let a = 10;
(a++);
console.log(a++); // Outputs: 10
console.log(a); // Outputs: 11
In the first console log, we are using the post-increment operator, and the value of "a" is first evaluated as 10 as initially it was assigned with the value of 10 to the variable "a". After the evaluation, the value of "a" is incremented to +1 which equals to 11. Thus, in the second console log, we are just logging the value of "a", which is now 11, as it was incremented in the previous step.
Pre-increment operator
The pre-increment operator increases the value of the operand before it is evaluated. This means that this increment process will increase the value of the operand first and then it will be evaluated.
We can consider the following example:
let a = 10;
++a;
console.log(++a); // Outputs: 11
console.log(a); // Outputs: 11
In the first console log, we use the pre-increment operator to increase the value of "a" to 11. The value of "a" is evaluated after the increment, and the console log returns 11. We are simply logging the value of "a" in the second console log, which is still 11, considering that it was incremented in the previous step.
To conclude, we can say that the process in which the operand is evaluated and increased defines post-increment and pre-increment operators. Simply we can understand that the post-increment operator evaluates the operand first and then increases its value, whereas the pre-increment operator evaluates the operand first and then increments its actual value.