Understanding postfix and prefix increment or decrement
Starting my javascript journey as a learning web developer,has not been smooth ,all because I started learning programming with my mobile device,which i will talk on later...
During the learning phase of javascript, or i will say mostly all programming languages, postfix and prefix increment or decrement has always been a problem for new programmers. So below is the explanation for this...
Prefix increment and decrement
i = 2;
x = ++i pre (before).
// x = 3, i = 3
The explanation for the above code follow thus...
- 'i' will be increase first before it's been assign to be the value of 'x'. Which makes x = 3 and i = 3.
i = 2;
x = --i pre (before).
// x = 1, i = 1
- 'i' will be decrease first before it's been assign to be the value of 'x'. Which makes x = 1 and i = 1.
Postfix increment and decrement
i = 2;
x = i++ post (after).
// x = 2, i = 3
The explanation for the above code follow thus...
- 'i' will be increase first after it's been assign to be the value of 'x'. Which makes x = 2 and i = 3.
i = 2;
x = i-- post (after).
// x = 2, i = 1
- 'i' will be decrease first after it's been assign to be the value of 'x'. Which makes x = 2 and i = 1.
Well going through this should give you a little understanding on this topic and this will make a good start for beginners.