+ 6

JS: if var x = 5; var y = --x+x++; alert (y), What will be output & how?

if --x = 4 x++ = 5 then the output is 8 not 9. Why??

11th Aug 2017, 6:20 PM
Tahir Usman
Tahir Usman - avatar
4 Réponses
+ 11
Right, but this case is different. In the statement of y, the --x part has already reduced the value of x to 4. So x is not 5 anymore. Since x has become 4, the later part of y statement will treat x as 4. Therefore, if x is 4, x++ is also 4.
11th Aug 2017, 7:01 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 5
x++ should be 4 since it's post increment. --x makes x=4 and --x=4 x++ makes x=5 and x++ = 4 So, y = --x+x++ = 4+4 = 8
11th Aug 2017, 6:30 PM
Shamima Yasmin
Shamima Yasmin - avatar
+ 5
Thanks @ SY
11th Aug 2017, 9:06 PM
Tahir Usman
Tahir Usman - avatar
+ 3
but if we do it separately then var x = 5; alert (x++) we get 5.
11th Aug 2017, 6:41 PM
Tahir Usman
Tahir Usman - avatar