JavaScript ++ operator, javascript increment operator, increment operator in javascript, increment and decrement operators in javascript with examples, javascript decrement operator, JavaScript ++, javascript operator

var x = 10;
var x = x++;
var x = ++x;
console.log(x);
*output*
11
var x = 10;
var x;
var x = ++x;
console.log(x);

*output*
11   (If you are not clear, dont worry, we will explain this in this post as well)
var x = 10;
var y = x++;
var z = ++x;
console.log(x,y,z);

12 10 12
var x = 10;
var x = undefined;
var x = ++x;
console.log(x);

NaN
var x = 10;
var x = ++x;
var x = x++;
console.log(x);

11
var x = 10;
var x = ++x;
var x = x++;
var y =x;
console.log(x);
console.log(y);

11 11
var x = 99;
x = x++;
console.log( x );

99
var x = 10;
var x = ++x;
var x = x++;
var x = x++;
var x = x++;
var y =x;
console.log(x);

11
var x = 10;
var x = ++x;
var x = x++;
var x = ++x;
var x = x++;
var y =x;
console.log(x, y);

12 12


— — -I am sure that you all will be confused on above questions and it’s output…


Confusion !!!!!

Let’s explain it in a simple way.

You probably learned that x++ is the same as x = x+1. Well, that’s not the whole story. x = x++ and simple x++ both are not same.

When we do var x = x++; it simply means we are doing var x = x nothing else. you’ve just set x back to its old value: !! It is not same as var x = x + 1;
But
When we do x++ only: it is same as x = x + 1;

Example :

var x = 10;
var x = x++;
console.log(x);

the value of x is still > 10;
var x = 12;
x++;
console.log(x);

// Now the value of x is 13.


Another important question. what will be the output for the below code?

var x = 0;
var loop = function(){
while(x < 3){
console.log(“I’m looping!”);
x= x++;
}
};

loop();

Think! Think !! Think !!

— — — — — –

— — –

— –

— –

And the answer is it will run as an infinite loop as per the above explanation.



Read more technical blogs – https://jsmount.com



javascript increment operator, increment operator in javascript, increment and decrement operators in javascript with examples, javascript decrement operator, JavaScript ++, javascript operator

Leave a Reply

Your email address will not be published.