let i = 1; i = i++ - --i + ++i - i--; console.log(i);
The result shows 0 how is it working with i++ as 1, --i as 1, ++i as 2 and i-- as 2.
As I understand i++ should be 1, --i should be 0, ++i should be 1 and i-- should be 1.
As post increment or decrement should alter later, pre-increment or decrement works instant.
Please clarify what am I doing wrong in it.
Let's take it step by step:
i++ returns the value 1 as you say, but it also increments the variable i. so i now has the value 2.
--i takes 1 off i and returns the value of i, in this case therefore 1.
[So far we have i++ - --i having the value 0 therefore.]
Now ++i increments i which becomes 2 and returns that value
[So far therefore we have 0 - 2]
Finally we have i-- which returns the value of i which is 2 (and then takes 1 off it, but that isn't seen as we then update the lhs (the i variable) with -2 + 2 which is 0.