JSLint Braces around If-Block

Viewed 5695

In Javascript, if an if expression does not have a curly bracket after it, the following statement is put inside the if block. That is,

if(foo)
bar();
baz();

is equivalent to

if(foo) {
  bar();
}
baz();

Douglas Crockford recommends not using the first because it is confusing and can cause hard-to-trace bugs if a programmer tries to add a statement to an if block without braces. For this reason, JsLint complains if you use the first form.

I use this all the time, and I feel like it's a non-issue provided that you put the statement on the same line as the if statement, like this:

if(foo) bar();
baz();

This is more concise visually than the full bracket form, and I've never had confusion with it. Just so I could pass JsLint and not have so much visual noise I have sometimes resorted to using a less idiomatic form that relies on operator short-circuiting, like this:

foo && bar();
baz();

You're probably all waiting for me to hurry up and ask a question, so here it goes: Is it generally considered bad practice to not use braces on one-line conditional statements if you format it correctly? Why? Is there a legitimate reason for JsLint to complain about it?

2 Answers
Related