O'Reilly logo

Maintainable JavaScript by Nicholas C. Zakas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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(); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required