You have to define a new variable or a boolean (for example var forwards=true; at the beginning) for the direction of progress and complete the tests.
To begin again at the beginning it is a little more subtle because it should invert the movement only when the box come from the left (and not at first)... I leave you the care of resolving this thing. You will then have found the universal movement...
// for the first movement at the left or right limits (*) :
if (forwards) direction='bottom'; else direction='top';
// for the second movement at the left or right limits (*):
if (forwards) direction='left'; else direction='right';
// And conversely
if (forwards) direction='right'; else direction='right';
// Do not forget to change forwards at the end
if ( (box.xPos==0 && box.yPos==9) forwards=!forwards;
NB : Your variables isRightExtreme (box.xPos == 0) and isLeftExtreme (box.xPos==9) are useless
EDIT : (*) The conditions could be a little different because we arrive at the extremities of lines with different parities for box.yPos (box.yPos % 2 == 0 or !=0)