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()
}
7 Answers 7
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
}
1 Comment
You only need to wrap it in another set of parentheses to make JSLint happy.
while((text = someBufferObject.read())) {
//do stuff with text
}
4 Comments
I can only imagine that's a problem with JSLINT, that's completely valid javascript, it's a lot better than the second solution anyway.
Comments
See if JSLINT complains about this:
while (NULL != (text = someBufferObject.read())) {
//do stuff with text
}
4 Comments
Neither example is a "do-while", they're just different code styles that essentially do the same thing. JSLint is simply informing you that the first style goes against best practices.
3 Comments
JSLint is complaining because it's a JavaScript code-smell -- using a single-equals (assignment operator) instead of double- or tripe-equals (equality/identity operator) is a common mistake.
If your code works, don't sweat the warning. It's an automated tool, not an omniscient tool.
Comments
while((text = someBufferObject.read()) !== undefined) {
//do stuff with text
}
is also accepted by jsLint and a style less cryptical than the paranthese workaround: while((a = b)) { ... }