270 javascript rules

☆ crockford's javascript code conventions ☆

CODE LOCATION

JS code should either be: 1.) in an external file with a link from the html file (<script src="...) OR 2.) in the head of the html file in a <script> tag OR 3.) in some situations that can't be avoided, code might have to be in the html in a <script> tag

FUNCTIONS

All javascript code should be in functions, with rare exceptions. Use parameters to pass information INTO functions (no globals unless needed). doIt(x); Use the return mechanism to pass information OUT of functions. return sum;

VAR

All variables must be declared with 'var' before being used. - do not re-declare variables - do not re-declare parameters Avoid using global variables. Globals are declared outside of any function or are UNDECLARED. Only use a variable for ONE TYPE of value. Although variable declarations do not specify a type, the value stored in the variable has a type: string number bool object function array undefined null 'typeof' reveals type var x = "p"; console.log(typeof x); ==> string x=7; console.log(typeof x); ==> number

STATEMENTS

All statements must end with a semi-colon. Loop using: for, while, do while, for/in Branch using: if, if - else, if - else if - else, switch Arithmetic Operators: + - / * % += *= /= ++ -- Relational: == === != > < >= <=

OUTPUT

console.log simple output at load time may use document.write intrusive output, but useful at times alert() complex output involving dynamic changing of web pages will use: document.getElementById(id tag) + the innerHTML property (to change / augment html) + the style property (to change css)