+ 2
Output
Plese explain me the output for the following code: function addOne(x){ x--; var y = x++; var z = ++y; return z - x; } addOne(5); The output is 0.
7 ответов
+ 18
For this you must learn about postfix and prefix in javascript
++i (Pre increment): It will increment the value of i even before assigning it to the variable i.
i++ (Post-increment): The operator will return the variable value first (i.e, i value) then only i value will incremented by 1.
And now apply it to your code.
Hope it will helpful for you.
+ 4
1) addOne(5) -> x = 5
2) x-- -> x = 4
3) var y = x++ -> first y = x -> y = 5, then x++ -> x = 6
4) var z = ++y -> first ++y -> y = 6, then z = y -> z = 6
5) return z - x = 0 - the output.
Prefix:
++x do incrementing x (adding 1) before assignment or returning (++ is at first place, before x)
Postfix:
x++ do incrementing after assignment (++ is at second place, after x)
+ 1
x = 6, y = 6, z = 6
You are getting output as z - x,
z - x = 6 - 6
= 0
Hence, you are getting answer as 0.
To know how the value of all variable came 6, see Максим Казадаев's explanation.
0
Which variable value do you need x, y or z?
0
ok ok all three
0
Thanks everyone 😊
0
Максим Казадаев one small correction......
Values of x and z are not 6..... rather it goes upto 5 after all operations.......try it by applying console.log() after each operation in your browser.......I tried it out