Chapter 3. Statements and Expressions
Statements such as if and for can be used in two ways in JavaScript, with
curly braces for multiple contained lines or without curly
braces for one contained line. For example:
// Bad, though technically valid JavaScript
if(condition)
doSomething();
// Bad, though technically valid JavaScript
if(condition) doSomething();
// Good
if (condition) {
doSomething();
}
// Bad, though technically valid JavaScript
if (condition) { doSomething(); }The first two forms, which use an if statement without braces, are explicitly
disallowed in Crockford’s Code Conventions, the jQuery Core Style Guide, the SproutCore Style Guide, and the Dojo Style Guide. The omission of braces also generates warnings by default in
both JSLint and JSHint.
An overwhelming majority of JavaScript developers are in agreement that block statements should always use braces and always occupy multiple lines instead of one. This is because of the confusion created when braces aren’t included. Consider the following:
if (condition)
doSomething();
doSomethingElse();It’s difficult to tell the author’s intent in this code. There’s
clearly an error here, but it’s impossible to know whether the error is an
indentation error (the last line should not be indented) or braces are
missing because both line 2 and line 3 need to be executed inside the
if statement. Adding braces makes the
error easier to find. Here are two other examples with errors:
if (condition) { doSomething(); } doSomethingElse(); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access