21 of the best jQuery Syntax Guidelines
Share
Every jQuery programmer should know these basic syntax rules or they will die a horrible keyboard death.
Read carefully and get back to basics!
- Spacing1: Opening braces are always prefixed by a space. ie – if ( instead of if(
- Spacing2: Always have spaces after commas and colons. ie – param, param or var; var
- Equality: Try to use === instead of == to help with comparisons
- Comments: Long comments should use /* … */
- Blocks: if/else/for/while/try always have braces and always go on multiple lines
- Function Calls: Always include extra spaces around the arguments. ie – foo( true );
- Null Checks: use === null or === undefined
- Assignments: Assignments should always have a semicolon after them. ie – var test2 = false;
- Regular Expressions1: should be done using .test() and .exec(). “string”.match() is no longer used
- Regular Expressions2: Use regexp to remove blank spaces from a string:
$(‘#title’).val().replace(/^s+|s+$/g, ”) == ”) - Nodes:
.nodeName
should always be used in favor of.tagName
- Strings: Strings should always use double-quotes instead of single-quotes
- Switch: Use switch statements to reduce code and improving performance
- Chain Selectors: Same time by chaining selectors. ie – $(“.someclass, h3”)
- First and Last: use :first and :last to dynamically select the first and last elements
- Even and Odd: use :even and :odd to dynamically select alternate elements
- Ditch target=_blank: Make all links open in new window $(‘a[href^=”http://”]’) .attr({ target: “_blank” });
- Alert(): use alert(“hi”); to help with debugging code
- Use a cheat sheet: Example cheat sheet
- Selector Context: give your selectors context. ie – var selectedItem = $(‘#listItem’ + i);
- IE Controls: Use specific jQuery to fix IE bugs: if ($.browser.msie) { // Internet Explorer fixes; }
Source(s): http://docs.jquery.com/JQuery_Core_Style_Guidelines