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.
- Remove the
languageattribute from the<script>tag. There is no need for it and it has been deprecated. - No using
<!-- -->to wrap scripts as they are no longer necessary for modern browsers. - Always use
varto declare variables to avoid accidental globals. - Avoid global variables as much as possible. We will still sometimes use global variables when it makes it easier to illustrate a simple concept.
- Never use assignment as expressions. For example, avoid the following:
if( flag = (a && b) ){ ... } - Always use brace-delimited blocks in control structures, even simple ones.
- Indent the statements inside the braces.
- Place the opening brace on the same line as the control structure start.
- 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 }
- 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) { .... }; - Use object augmentation wisely. See the section on Object Augmentation at http://www.crockford.com/javascript/inheritance.html.
- Use
===and!==instead of==and!=to prevent unintended type coercion. - 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; } - Use the default operator:
||. Use this:var a = getValue() || 1;
…instead of this…
var a = getValue(); if (typeof a == "undefined") {... a = 1; } - 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.
- Use the .js file extension.
- Only embed JavaScript in HTML for code that belongs to the current page and session.
- Constrain lines to 80 characters.
- Break lines right after operators or comma.
- Indent the line after a line break.
- Comment Use:
- Add meaningful comments
- Avoid obvious comments.
- Use single-line comments when possible (
//rather than/* */).
- Declare all variables with
varat the beginning of each function. - Declare inner functions right after the
varstatements. - Put a space between “function” and the opening parens “(” for anonymous functions:
var myFunc = function (arg) { ... }; - Use only letters, digits and underscores for identifiers.
- Don’t start identifiers with _.
- Don’t use $ or \.
- Start all identifiers with lower case, except constructors and global variables.
- Start constructors with upper case.
- Use ALL_CAPS for global variables.
- Do not put more than one statement in the same line.
- End all statements with a semi-colon.
- Only use expressions as statements for assignments and invocations.
- Only use labels (if really needed) in for, while, do, and switch statements.
- Do not use parenthesis in return statements. Use this:
return a
…instead of…
return(a)
- Do not use the
withstatement. - Avoid the
continuestatement. - Whitespace use:
- Include a space between any keyword and an open parenthesis:
for ( ... ). - Do not put a space between a function name and the open parenthesis:
execute(abc). - Include a single space after each comma.
- Include a single space after each semi-colon in a
forstatement.
- Include a space between any keyword and an open parenthesis:
- Use
{}instead ofnew Object(). - Use
[]instead ofnew Array(). - Only use the comma operator inside the for statement control and then only if it’s absolutely necessary.
- Avoid
eval(). - Do not pass strings to
setTimeout()orsetInterval(). Instead, pass an actual function or closure. - 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:
- Exclude the
typeattribute from the<script>tag.- We disagree with this recommendation as the
typeattribute is required in HTML 4. Excluding it will make the HTML invalid.
- We disagree with this recommendation as the
- Place
<script src=...."></script>as late as possible inside<body>.- 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.
- Use 4 spaces as indentation, not tabs.
- 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.
- Avoid the creation of global functions.
- 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.
One Response to “JavaScript Style Guide Conformance”
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.