We all write our own jQuery code and since creating custom jQuery plugins is so easy, we all create our own jQuery plugins. And all of us have our own code syntax preferences. For example:
function myFunction() { ... } // some prefere it like this function myFunction() { ... }
If you want to publish your jQuery plugins following jQuery core code writing guidelines is a good idea. This would make your code more easier to read to other jQuery developers. Follow the link above and go through the guidelines (it will only take a few minutes). The guidelines page shows gives you general guidelines, but I went through the jQuery core code and found several additional ones. I lay they out at the end of this post.
In short, the official guidelines are as follows: (Taken from official docs)
- Use tabs to indent your code
- Use liberal spacing":
function myFunction ( myVar, myVar2 ) { // Pay attention to spaces around // the brackets and curly brackets }
- Use strict equality checks whenever possible (===)
- Braces should always be used on blocks and statements should not be on the same line as a conditionals:
// NO: if ( true ) blah(); // YES: if ( true ) { blah(); }
- When checking an object type:
String: typeof object === "string" Number: typeof object === "number" Function: jQuery.isFunction(object) Array: jQuery.isArray(object) Element: object.nodeType See full list on official docs page (link above)
- Don't use
"string".match()
for RegExp, instead use.test()
or.exec()
- Node related rules:
.nodeName
should always be used in favor of.tagName
..nodeType
should be used to determine the classification of a node (not.nodeName
).- Only attach data using
.data().
Now let’s see other additional rules that I could spot reading the jQuery core code.
Additional jQuery code / syntax guidelines:
- The first thing that I noticed was multiline comments did not use common
/* comment */
syntax. In jQuery core all multiline comments use line comment syntax// comment
.// This is an example of multiline // comment syntax used in jQuery core.
- Local variables are declared and initialized on one line just below the function declaration with no extra line:
function someFunction () { var target = arguments[0] || {}, i = 1, name; // Empty line and then the rest of the code }
- When declaring objects, there is no space between property name and colon:
{ myName: "", myFunc: function( ) {} }
- All strings are in double quotes
" "
, not single quotes' '
:var myMarkup = "<a href='/a'>a</a>";
- The last but not least, variable naming uses camelCase.