Monday, March 5, 2018

Increment and Decrement Operator

Increment ( ++ ) and Decrement (--) operators could play a important role in our coding life especially when you would do code re fragment.

Most of the interview rounds the interviewer will ask this question and most probably targeting a freshers. Her the post I will explain what these two operators are these, and we can see some coding example.

Let start....

Increment ++ operator:

It will increase a variable by 1 always. However some logic is there when you put ++ as prefix and as post fix to the variable.

1. Post fix ++  

let counter = 2;
counter++;      //Nothing but counter = counter + 1
console.log(counter); // Output : 3

So adding a post fix , increment the variable by 1 and assign to the variable. In this case ,
counter = counter + 1.


2. ++ Prefix operator:

This is totally different from the above example even I am using the ++. See the below code and remember the applied logic. 

let b = 1;
console.log(b++);    // 1
console.log(b);      // 2

Things To Remember:

1. console.log(b++), from this line before increment b value will be printed.
2. console.log(b); from this line after increment b value taken.  Because b=b+1 was taken now.
Same concept is applicable to -- operator.

Decrement -- operator:

1. Post Fix -- operator

let c = 1;
console.log(c--);    // 1
console.log(c);  // 0

2. -- Pre Fix operator

let d = 1;
console.log(--d);    // 0
console.log(d);      // 0



The below example is little tricky and you can get now more satisfaction of understanding pre and post operators.

let count = 1;
console.log( 2 * ++count ); // 4 , because of Prefix value increment here itself


let test = 1;
console.log( 2 * test++ ); // 2, because of post fix the old value only be used here

I hope you are satisfied with the the above example.






No comments:

Post a Comment