JavaScript Style Guide Conformance

March 13th, 2008 | by ndunn@webucator.com |

We are updating our JavaScript courseware and our JavaScript tutorial and Ajax tutorial to mostly conform with the conventions recommended by Douglas Crockford at http://javascript.crockford.com/code.html and http://javascript.crockford.com/style1.html. First of all, here’s what we decided to do. Some of these had already been implemented in our courseware, but we hadn’t formalized those decisions.

  1. Remove the language attribute from the <script> tag. There is no need for it and it has been deprecated.
  2. No using <!-- --> to wrap scripts as they are no longer necessary for modern browsers.
  3. Always use var to declare variables to avoid accidental globals.
  4. Avoid global variables as much as possible. We will still sometimes use global variables when it makes it easier to illustrate a simple concept.
  5. Never use assignment as expressions. For example, avoid the following: if( flag = (a && b) ){ ... }
  6. Always use brace-delimited blocks in control structures, even simple ones.
    1. Indent the statements inside the braces.
    2. Place the opening brace on the same line as the control structure start.
    3. Place the closing brace on a line by itself and indent it so that it falls directly below the first character of the control structure. For example:
      while (some condition) {
          //do some interesting stuff
      }
  7. End function assignments with a semi-colon. That is to say, when assigning a function to a variable, the statement should end in a semi-colon.
    var myFunc = function (arg) { .... };
  8. Use object augmentation wisely. See the section on Object Augmentation at http://www.crockford.com/javascript/inheritance.html.
  9. Use === and !== instead of == and != to prevent unintended type coercion.
  10. Only use the ternary operator for value selection. Use this:
    var a = (x===y) ? 0 : 1;

    …instead of this…

    var a;
    if (x===y) {
        a = 0;
    } else {
        a = 1;
    }
  11. Use the default operator: ||. Use this:
    var a = getValue() || 1;

    …instead of this…

    var a = getValue();
    if (typeof a == "undefined") {...
        a = 1;
    }
  12. Use inner functions to avoid globals and excessive parameters. We plan to do this in our advanced JavaScript course and our Ajax courses, but not too early as inner functions are difficult to understand for JavaScript newbies.
  13. Use the .js file extension.
  14. Only embed JavaScript in HTML for code that belongs to the current page and session.
  15. Constrain lines to 80 characters.
    1. Break lines right after operators or comma.
    2. Indent the line after a line break.
  16. Comment Use:
    1. Add meaningful comments
    2. Avoid obvious comments.
    3. Use single-line comments when possible (// rather than /* */).
  17. Declare all variables with var at the beginning of each function.
  18. Declare inner functions right after the var statements.
  19. Put a space between “function” and the opening parens “(” for anonymous functions:
    var myFunc = function (arg) { ... };
  20. Use only letters, digits and underscores for identifiers.
    1. Don’t start identifiers with _.
    2. Don’t use $ or \.
    3. Start all identifiers with lower case, except constructors and global variables.
    4. Start constructors with upper case.
    5. Use ALL_CAPS for global variables.
  21. Do not put more than one statement in the same line.
    1. End all statements with a semi-colon.
  22. Only use expressions as statements for assignments and invocations.
  23. Only use labels (if really needed) in for, while, do, and switch statements.
  24. Do not use parenthesis in return statements. Use this:
    return a

    …instead of…

    return(a)
  25. Do not use the with statement.
  26. Avoid the continue statement.
  27. Whitespace use:
    1. Include a space between any keyword and an open parenthesis: for ( ... ).
    2. Do not put a space between a function name and the open parenthesis: execute(abc).
    3. Include a single space after each comma.
    4. Include a single space after each semi-colon in a for statement.
  28. Use {} instead of new Object().
  29. Use [] instead of new Array().
  30. Only use the comma operator inside the for statement control and then only if it’s absolutely necessary.
  31. Avoid eval().
  32. Do not pass strings to setTimeout() or setInterval(). Instead, pass an actual function or closure.
  33. Do not use the Function construction. Use this:
    var myFunc = function (arg){ statements; };

    …instead of…

    var myFunc = new Function (arg1, { statements; } );

Here are the recommendations we decided not to follow:

  1. Exclude the type attribute from the <script> tag.
    1. We disagree with this recommendation as the type attribute is required in HTML 4. Excluding it will make the HTML invalid.
  2. Place <script src=...."></script> as late as possible inside <body>.
    1. While we agree with this recommendation in general, we feel that it would complicate the learning process as students would have to search through HTML documents for the JavaScript sections. We’ll recommend that students do this as a best practice in their own code, but we will not always do it in the course samples.
  3. Use 4 spaces as indentation, not tabs.
    1. We have taught our JavaScript courses to many students using many computers and have never had an issue with using tabs. And it’s a lot easier to press tab than press the spacebar four times.
  4. Avoid the creation of global functions.
    1. We take this to mean that functions should be created as methods of classes. While we understand the point, we would have to start our classes by teaching object-oriented concepts, which wouldn’t make pedagogical sense. So, we’ll continue to use global functions in our JavaScript courseware.
  1. One Response to “JavaScript Style Guide Conformance”

  2. By ndunn@webucator.com on Apr 7, 2008 | Reply

    We have completed this update for our JavaScript courseware and made the changes live in our online JavaScript tutorial. The Preloading Images Demo illustrates several of the changes that we made (hanging curly brackets, variable capitalization, no language attribute).

    One thing I still want to do is ids and names of HTML elements are written in camelCase. It’s not specified in the Crockford guidelines and we didn’t think to do it on this run through.

You must be logged in to post a comment.