Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript "do-while" type loop

Tags:

javascript

I'm working with some JS code that I inherited on a project, and in several instances it has loops set up like this one:

while(text = someBufferObject.read()) {
  //do stuff with text
}

I'm assuming this is to achieve some sort of do-while type functionality. However, when I run this through JSLINT it complains that it "Expected a conditional expression and instead saw an assignment."

Is there a more accepted approach that I should use for these loops? I'm not sure if something like below is the best way or not:

text = someBufferObject.read()
while(text) {
  //do stuff with text
  text = someBufferObject.read()
}
like image 865
Duncan Johnson Avatar asked Nov 27 '22 15:11

Duncan Johnson


1 Answers

Is there a more accepted approach

Don't take JSLint's advice as gospel. It is dogmatic opinion from a cranky old man; some of it entirely sensible, some of it rather questionable.

while (variable= assignment), though it might sometimes be a mistaken comparator, is also a widely-understood idiom of C-like languages. Whether you use that approach or another is a matter of taste, something you should weigh up personally rather than blindly accept Crockford's edict.

JavaScript does have a do-while loop, so if your test is consistently at the end that would be a more appropriate construct:

do {
    text= someBufferObject.read();
    // do something
} while (text);

More commonly though what you're looking at is a mid-test loop. You may or may not prefer the break idiom as used by Python:

while (true) {
    text= someBufferObject.read();
    if (!text)
        break;
    // do something
}
like image 53
bobince Avatar answered Dec 15 '22 07:12

bobince