The problem is approachDir . i++ and i-- are post -increment and post -decrement. This means that they update the variable after they return their original value. Thus, the function returns the original value, not the updated one. To update a variable before returning, you must use ++i or --i .
But you do not need to use the increment operator at all, since the local variable disappears immediately. Just return the new value.
function approachDir(i, a, b) { return a < b ? i + 1 : i - 1; }
You also need to reassign the variable in the loop:
for (var i = a; approachCond(i, a, b); i = approachDir(i, a, b)) { ... }
As you wrote the code, you assumed that the variables are passed by reference, not by value, so that the function increment will change the calling variable.
source share