Difference between x++ and ++x
You probably must have learnt that x++
is the same as ++x
. ++x
happens prior to assignment (pre-increment), but x++
happens after assignment (post-increment). x++
executes the statement and then increments the value. ++x
increments the value and then executes the statement.
Case 1: x++
// If y = x++, the variable x will be incremented after assigning its value to y.
var x = 0;
var y = 0;function postIncrement(){
while(x < 3){
y = x++;
console.log("y = " + y);
}
x++;
}postIncrement();
Case 1 will yield the output below,
y = 0
y = 1
y = 2
Case 2: ++x
// If y = ++x, the variable x will be incremented before assigning its value to y.var x = 0;
var y = 0;function preIncrement(){
while(x < 3){
y = ++x;
console.log("y = " + y);
}
x++;
}
preIncrement();
Case 2 will yield the output below,
y = 1
y = 2
y = 3
Using simple example and the second way of variable declaration in JavaScript,
Case 1: x++
let x = 0;console.log(x); //outputs 0
console.log(x++); //outputs 0
Case 2: ++x
let x = 0;console.log(x); //outputs 0
console.log(++x); //outputs 1
Thank you for reading!
If you like my article, please hit this icon 👏 below as many times as possible, bookmark, share it with your friends and follow me for more stories. Feel free to ask questions. I welcome feedback.