3 ms·
Is there any particularly good, JavaScript-specific reason why the braceless version of if statements is discouraged? if (foo) bar(); Or is this just a
by pmjordan 17y ago
Is there any particularly good, JavaScript-specific reason why the braceless version of if statements is discouraged?
if (foo)
bar();
Or is this just a matter of taste as it is with C, C++, Java, C#, etc.?
- Sephr 17y agoIt's just a matter of Douglas Crockford's taste and he doesn't like them so you have to live with it.
- tlrobinson 17y agoAlong with increment/decrement operators, fall-through cases in switch statements, foo['bar'] style property access/assignment, bitwise operators, and a number of other things. His book ("JavaScript: The Good Parts") contains a lot of good information, but roughly half is what I would consider "style" preferences.
- adamc 17y agoTo be fair, he gives a very clear explanation of how he came to his opinion on case statements -- he started out favoring them. So it's more "opinion informed by experience" than just "opinion".
- DanHulton 17y agoNot javascript-specific, but it's well-enough documented that leaving out braces in if statements is a source of possible error. It's clearer and safer to use them.
- jdavid 17y agoif you want to do something like if (foo) bar(); you might as well write if(foo) bar(); i personally prefer if(foo){bar();} the reason to be explicit, is incase you are modifying your script via a compressor, sometimes you can not predict what line your code is going to be on, and its always best to be as explicit as possible. if you go to one of Crawford's talks, he mentions how he used to love writing switch case statements with fall through, until he spent hours debugging something because of it. most of the stuff he has in there is a really good start to having fairly readable and reliable code. i recommend following the pattern.
- litewulf 17y agoJavascript has implicit semicolon insertion. This means that some lines of code will not do what you'd expect if you make a dumb mistake.