Embrace Curly Braces
In JavaScript (and many other C-style languages) you can do this:
if (condition)
foo();
While this code is perfectly valid, and will run as expected, you should never omit an if statement’s curly braces like this. Why? Take a look at this code:
if (condition)
foo();
bar();
This code is also perfectly valid, but it’s incredibly deceptive. In this example, only foo();
is attached to the if statement. Despite appearances, bar();
will run no matter what.
This code is functionally identical, but much clearer:
if (condition) {
foo();
}
bar();
Leaving out curly braces might save you a few keystrokes, but it’s a nightmare for code readability and maintenance. Save Future You from confusion and hassles: always use curly braces!