Javascript is an interesting language. While Ruby has a style guide, and Python has a few (including Google’s, they are not critical to how your code functions. They just help avoid those “strip whitespace” commits that touch every line in your repo and permanently ruin git blame
.
With Javascript, the style is the substance. Take these two for example:
var object = {
method: function(data){ ... },
_variable: 3
};
object2 = {
method: function(datae){ ... },
_variable: 2
}
var Klass = function(){
this.method = function(data){ ... };
this.variable = 4;
return this;
}
These seemingly small differences might not affect how a short script works, but they are critical to how your app works as a whole. The first declares a single object. The second declares a global variable. The third declares effectively a factory function.
Newlines can result in syntax errors for strings. Missing semicolons can ruin your JS after compression. Using reserved words as object keys can break your code in some browsers. Failing to use ===
can result in unexpected behavior.
It is essential to use a Javascript style guide. Frameworks like Express and Angular can help standardize things like object and module declarations, and CoffeeScript can provide syntax sugar to cover simple issues.
Otherwise, AirBnB’s style guide is comprehensive and helps show best practices. Pick something, and stick with it, especially if you are working on a team.