Thoughts on the Idea of a "Best Practice"
With the launch of our new JavaScript Best Practices course, you may be wondering how we decided on each featured topic. This course was a huge undertaking due to the significant amount of material we could have covered, some of which was left on the shelf for another day. The end result is still our longest course to date, and is filled to the brim with broad applications and juicy tidbits we think every JavaScript developer should know.
Given that there are many opinions about what makes the absolute best JavaScript code, we thought we'd illustrate just a couple debated topics to show why we think these are the top practices for performance, safety, and legibility.
Bracketing Blocks of Code
Many folks love their unbracketed, one-line block statements. They really enjoy that they can leave off the curly brackets that conventionally close a block of code, like so:
if(thisValueIsTrue) thisThing = done;
else thisOtherThing = doneInstead;
or the following, which can be more misleading because of its visual impression:
if(thisValueIsTrue)
thisThing = done;
else
thisOtherThing = doneInstead;
The above examples also apply to loops, which don't require brackets in JavaScript if the loop executes only one statement. The arguments for the one-line block statement are usually that it tightens up code into a more legible style, and that JavaScript doesn't even scope to blocks. The first example above does indeed save two lines of code (two!) versus the second, and does approach a more natural left-to-right reading style that some find very intuitive and useful.
We've taught in JSBP that curly brackets are instead a two-character sacrifice that can be very important to make at all times, especially in team-maintained code. Check out what happens in the second example above, if code is added (ostensibly by someone else) without analyzing the existing block or bracket structure:
if(thisValueIsTrue)
thisThing = done;
thisNewThing = doneToo;
probsThisTooYouGuys = boom;
else
thisotherThing = doneInstead;
This code will quickly produce an error because that else keyword has no immediately preceding if-block to associate with, although the editing developer probably got some visual cues that it did. And understandably so; the code appears like two "blocks." Many developers might avoid you on the playground if they were forced to analyze your code for lack of brackets, in order to not make errors with minor, but necessary, additions.
We view the following as a better style for these reasons of safety and kindness. Although the second example is one line longer, it still retains legibility:
if(thisValueIsTrue) { thisThing = done; }
if(thisValueIsTrue) {
thisThing = done
} else {
thisOtherThing = doneInstead;
}
Comma-Delimited Variable Statements
Another example of personal style and prevention versus performance is the debate over separating variable declarations, and potentially assignments, with commas. Check out the following setup:
var dudeOne = "cool";
var dudeTwo = "smart";
var dudeThree;
JavaScript, like other languages, offers a way to group multiple variable declarations using only one var keyword and commas:
var dudeOne = "cool",
dudeTwo = "smart",
dudeThree;
In the first example, the JavaScript parser--which figures out whether some code is even valid in the grammar of the language--will need to look up that var keyword three times, two more than is absolutely necessary. Some devs like saving the minor performance hit that those extra lookups provide, especially if a great deal of variables are declared in the context of the code. Enough of us at Code School liked this performance pick-up, and so we teach it as a best practice in the new course.
On the other hand, some find the presence of the var keyword to be particularly helpful! They prefer to recognize what's going on in a line of code immediately. Losing that var keyword, especially later in a file, makes it appear that the new variable might have been declared elsewhere--even though the comma might signal otherwise. Context always applies.
Additionally, the comma-delimted variable declaration can get dense if crowded onto one line like so:
var dudeOne = "cool", dudeTwo = "smart", dudeThree;
There's a great legibility argument for NOT using a single line when employing commas. If the assignments present here were lengthier, maybe from using compound logical assignment or function calls with namespace headers or both, those three "dudes" could get really dense to read in one line. Bad news, bro.
Another valid reason that some developers may choose to place var keywords on every declaration is to prevent the effects of missing commas. Automatic Semicolon Insertion in JavaScript can produce unintended results. Check out what happens to the "dudes" in this case:
var dudeOne = "cool";
dudeTwo = "smart" //Forgot a comma here, oops!
dudeThree; //Now dudeThree is a reference, not a declaration.
//An undefined reference, too.
Definitely bad news if you can't remember to put your commas in. We view the better performance impact associated with a single var, albeit minor, as something to strive for--and with striving comes a responsibility to ensure your code has no missing syntax, in similar fashion to the first topic about brackets. Nevertheless, comma-delimited variables are just one best practice idea of many in which personal style, preference, and precision can indeed play a role.
This is by no means a comprehensive sample of all the controversial best practices out there in the development wilds. These do, however, demonstrate the idea that your approach to building your best code should take into account not only your preference of personal style, but also the best performance, maintenance, and safety considerations within the context of your particular application.
We're sure there may be differing views, and we appreciate those who value the art of development so intensely as to have a passionate opinion! We hope you'll join in on a discussion and share the best practices you recommend so that the whole Code School community can continue learning together.
We hope you enjoy our JavaScript Best Practices course, and wish you luck as you continue your journey in development!