Friday, September 17, 2010

What I learned about JavaScript from Douglas Crockford

About a year and half ago, O'Reilly published Douglas Crockford's book: JavaScript: The Good Parts. It's a great book and is particularly useful if you have the opportunity to create new JavaScript code so that you can use the subset of the language that he describes.

One thing the book lacks is a summary of all the good advice in the form of a best practice list. Now, such lists are useful as long as we keep in mind that nearly every "rule" has an exception. Perhaps Crockford deliberately avoided the problems that can come from separating recommendations from their explanation and justification.

Nevertheless, I want to present some of his recommendations as a list that you can apply without necessarily knowing their background. I highly recommend that you consult Crockford's book for more details.

  1. Mitigate JavaScript's default global variables by creating a single global variable that acts as a container for your application.
    code example:

    var THEAPP = {};
    THEAPP.book = {
    "name": "JavaScript The Good Parts",
    "author: "Douglas Crockford"
    };


  2. When using the Function Invocation Pattern, save a copy of this in a variable (called "that" typically). This will allow an inner function access to the outer function's objects.

  3. JavaScript doesn't have block scope, so declare a function's variables at the top of the function body.

  4. Use the Module Pattern to encapsulate singletons.

  5. Use Cascade to call many methods on the same object in sequence in a single statement. Each method of the Cascade returns the object.

  6. The length property of an array is the largest integer property name in the array plus one. So assigning a smaller value than the current one to the length property truncates the array.

  7. Avoid the for in statement and use the conventional for statement instead.

  8. When to use arrays vs. objects. When the property names are small sequential integers, use an array. If not, use an object.

  9. Regular expressions are best when they are short and simple.

  10. The array.sort, sorts arrays of numbers incorrectly because its default comparison method does a string compare.

  11. Use K&R style braces (put "{" at the end of the line) to avoid a serious language design flaw in JavaScript's return statement.

  12. Don't use an assignment expression in the condition part of an if statement.

  13. Don't allow switch cases to fall through to the next case.

  14. Don't use implied global variables. Any variable used without declaring it, will be global by default.

  15. Avoid using new.

  16. Always provide the radix parameter when using parseInt.

  17. If you intend + to add, make sure that both operands are numbers.

Link to book description: JavaScript: The Good Parts
Link to Douglas Crockford's JavaScript Video