+ 1

do you also find Javascript postfix and prefix combinations confusing?

let a = 3 let b = a++ let c = ++a console.log(++c); //--> 6 why the answer is 6 instead of 5 still confuses me to this day

15th Aug 2023, 7:55 PM
Alwell Kariboro
Alwell Kariboro - avatar
2 Answers
+ 4
I'll try to explain. - The prefix increment operator first increases the value by one and then assigns it (or passes it to whatever function it's in). - The postfix increment operator first passes or assigns the value, and then increases it after it has already been assigned somewhere. Let's look at this code line by line: 1. let a = 3. Obvious, 'a' now has a value of 3. 2. let b = a++. This is using postfix, therefore the current value of 'a' is assigned first to 'b', and then the value of 'a' is incremented. This means that 'b' becomes 3, and 'a' becomes '4' because it was incremented after assignment. 3. let c = ++a. This uses prefix, and that means the value of 'a' is incremented, and then that value (which is now '5'), becomes the value of 'c'. 4. console.log(++c). This uses prefix notation and it outputs the result of what's in the function call. Since 'c' is now '5' as I just explained, using the prefix operator means that the value of 'c' is increased by one first, and then that value (which is now '6') is passed to the function, and that function prints '6', as expected. Hope that helps. Cheers.
15th Aug 2023, 8:08 PM
Marcos Chamosa Rodríguez
Marcos Chamosa Rodríguez - avatar
+ 2
thanks! I'll keep re-reading this until it sticks!!
15th Aug 2023, 8:11 PM
Alwell Kariboro
Alwell Kariboro - avatar