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.
- 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"
}; - 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. - JavaScript doesn't have block scope, so declare a function's variables at the top of the function body.
- Use the Module Pattern to encapsulate singletons.
- Use Cascade to call many methods on the same object in sequence in a single statement. Each method of the Cascade returns the object.
- 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. - Avoid the
for in
statement and use the conventionalfor
statement instead. - When to use arrays vs. objects. When the property names are small sequential integers, use an array. If not, use an object.
- Regular expressions are best when they are short and simple.
- The
array.sort
, sorts arrays of numbers incorrectly because its default comparison method does a string compare. - Use K&R style braces (put "
{
" at the end of the line) to avoid a serious language design flaw in JavaScript'sreturn
statement. - Don't use an assignment expression in the condition part of an
if
statement. - Don't allow
switch
cases to fall through to the next case. - Don't use implied global variables. Any variable used without declaring it, will be global by default.
- Avoid using
new
. - Always provide the radix parameter when using
parseInt
. - 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