Monday, July 13, 2015

Javascript coding style

https://github.com/airbnb/javascript

This style from Airbnb is very good except for spacing (I still prefer to set soft tab to 4 spaces for indent). In most editors, I like more spaces for easy code reading.

Here are some excerpts from airbnb

Use Array#push instead of direct assignment to add items to an array.
When you need to copy an array use Array#slice.
To convert an array-like object to an array, use Array#slice
When programmatically building up a string, use Array#join instead of string concatenation.
Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead.
Variable declarations get hoisted to the top of their scope, but their assignment does not.
Anonymous function expressions hoist their variable name, but not the function assignment.
Named function expressions hoist the variable name, not the function name or the function body.
Function declarations hoist their name and the function body.
Use // FIXME: to annotate problems.
Use // TODO: to annotate solutions to problems.
Leave a blank line after blocks and before the next statement
Perform type coercion at the beginning of the statement.
Use parseInt for Numbers and always with a radix for type casting.
Use camelCase when naming objects, functions, and instances.
Use PascalCase when naming constructors or classes.
Use a leading underscore _ when naming private properties.
When saving a reference to this use _this.
Name your functions. This is helpful for stack traces.
Accessor functions for properties are not required.
Assign methods to the prototype object, instead of overwriting the prototype with a new object.
When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass a hash instead of a raw value.
Add a method called noConflict() that sets the exported module to the previous version and returns this one.
For DOM queries use Cascading $('.sidebar ul') or parent > child $('.sidebar > ul')
Use find with scoped jQuery object queries.


No comments:

Post a Comment