JavaScript Style
Fall 2008, David Matuszek
Many of the following points are drawn from JavaScript: The Good Parts by Douglas Crockford.
| Rules | Reasons |
|---|---|
Don't use global variables. All variables should be declared inside methods, using |
Global variables can be changed anywhere, making debugging harder. Global variables make conflicts more likely if you try to run independent subprograms in the same program.
|
| Variables should be declared at the top of each function. | JavaScript has no "block scope." Variables declared anywhere within a function are available throughout the function. |
| End every statement with a semicolon. | JavaScript's automatic semicolon insertion may put semicolons where you don't want them, leading to hard-to-find errors. |
Use === and !== instead of == and !=. |
The shorter versions try to convert their operands to the same type, using some complicated and unmemorable rules. |
Don't use the with statement. |
with automatically inserts a prefix before some variables
but not others. It usually does the "right" thing, but that's hard
to tell. |
Don't use the bitwise operators & and |. |
These work correctly for integers. JavaScript doesn't have integers.
Also don't use them in place of the logical operators && and ||. |
Before using eval, look for some other way of doing the same thing. |
eval is insecure, inefficient, and harder to read.
It's useful when you really need to create code dynamically, but
it's a poor substitute for knowing how to do things in JavaScript. |
If you deliberately fall through to the next case in a switch statement,
say so in a comment. |
This is done more often by accident than deliberately. |
| Always use braces with control statements, even if only one statement is being controlled. | As in Java, this helps to avoid future mistakes when code is added. |
Put open braces, {, at the end of lines, not at the
beginning (i.e. use Java style) |
Otherwise JavaScript is likely to insert a semicolon at the end of the line. |
Use ++ and -- only by themselves, not in more complex expressions. |
Pre/post increment and decrement are confusing. When they are used
just to increment or decrement (as a statement by themselves, or
as the only part of the "increment" of a for loop), they are okay. |
Declare your functions in the <head> of the page. |
This ensures functions are loaded before you try to use them. |
If you declare a function dynamically, use the formvar foo = function foo(...){...};instead of just function foo(...){...}; |
You can dynamically declare functions in, for example, if-then statements.
Functions declared in the latter form may (or may not) be "hoisted"--declared
statically at the top level. |
Don't use new Boolean, new Number,
or new String. Don't use void, either. |
These are useless. |