+ 2

What will this code return and why?

function addOne (x) { x--; var y = x++; var z = ++y; return z - y; } addOne(5);

1st Mar 2018, 8:14 AM
Briaה‎
2 ответов
+ 8
Where did you see this, in challenge I suppose? it's funny the code does a totally different job given the name : ) It returns zero by the way, I assume you already know pre and post increment/decrement, let's review that; function addOne(x){ x--; // x is still 5 x will decrement on the next instruction line. var y = x++; // here x becomes 4, and is still 4 when it is assigned to y, so y is 4 too. var z = ++y; // here y is incremented and becomes 5 before assigned to z, so z gets 5 too. return z - y; // both z & y is 5, so this is 5-5, equals zero. } FYI you can use Code Playground to test a code : ) Hth, cmiiw
1st Mar 2018, 9:02 AM
Ipang