21 of the best jQuery Syntax Guidelines

By Sam Deering

Every jQuery programmer should know these basic syntax rules or they will die a horrible keyboard death.

Read carefully and get back to basics!

  1. Spacing1: Opening braces are always prefixed by a space.  ie – if ( instead of if(
  2. Spacing2: Always have spaces after commas and colons. ie – param, param or var; var
  3. Equality: Try to use === instead of == to help with comparisons
  4. Comments: Long comments should use /* … */
  5. Blocks: if/else/for/while/try always have braces and always go on multiple lines
  6. Function Calls: Always include extra spaces around the arguments. ie – foo( true );
  7. Null Checks: use === null or === undefined
  8. Assignments: Assignments should always have a semicolon after them. ie – var test2 = false;
  9. Regular Expressions1: should be done using .test() and .exec(). “string”.match() is no longer used
  10. Regular Expressions2: Use regexp to remove blank spaces from a string:
    $(‘#title’).val().replace(/^s+|s+$/g, ”) == ”)
  11. Nodes: .nodeName should always be used in favor of .tagName
  12. Strings: Strings should always use double-quotes instead of single-quotes
  13. Switch: Use switch statements to reduce code and improving performance
  14. Chain Selectors: Same time by chaining selectors. ie – $(“.someclass, h3”)
  15. First and Last: use :first and :last to dynamically select the first and last elements
  16. Even and Odd: use :even and :odd to dynamically select alternate elements
  17. Ditch target=_blank: Make all links open in new window $(‘a[href^=”http://”]’)    .attr({ target: “_blank” });
  18. Alert(): use alert(“hi”); to help with debugging code
  19. Use a cheat sheet: Example cheat sheet
  20. Selector Context: give your selectors context. ie – var selectedItem = $(‘#listItem’ + i);
  21. IE Controls: Use specific jQuery to fix IE bugs: if ($.browser.msie) {   // Internet Explorer fixes;  }


No Reader comments



Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.