Javascript cheatsheet
Core: * Scoping : All scoping is function based. Curly braces do not define a scope * List of all types: Object, String, Number, Boolean, null, undefined * Beyond types, built-in claseses also include: Array, Date, Function, Global, Math * Strings and Numers are immutable * Missing members evaluate to undefined * null and undefined are not the same * False is : false, null, undefined, "", 0, NaN * Any type can be passed as any parameter to any function * Lambda supported: x = function(){};
Types: * Objects: See "object system" below * Strings
* Create: with String(blah)
* string.length, string.replace(old,new)
- Numbers
- Create number with Number(blah)
- Numbers are unreliable; IEEE-754/Double semantics
- Booleans
- null
- undefined
C syntax: * Statements end in a semicolon * for (var i=0, j=foo.length; i < j; i+=1) {} * if (expression) {} else if {} else {} (braces optional for single statements, but use them) * switch (expression) { case 'a': foo; break; default: bar; } * throw new Error(reason) or throw { name : blah, message: bar }; * try {} catch (e) {}. Only one catch block so need to examine exception e. * function name(parameters) {} * "var blah" defines a variable within function scope; without this, assumes global. Assigning to variable is optional. * identifiers start with letter, underscore, or dollar sign, optionally followed by same or digits * Both // and / / comments supported * ++/--, +=/-= supported * Labelled breaks supported * No implicit return value; statements must perform a "return blah" to return a value
Object system: * Object inhertiance is "prototype" based, not class based. An object inherits from zero or one parent objects. * If a member lookup fails, will ask parent. Works for scalar members and member methods. * Hash/Object unification so:
* Hash creation ala {abc: 123, def: 456} is also an "object literal", creating an object inline
* Can fetch hash/object members via either dot or subscript (foo.bar or foo['bar'])
* Can skip quotes around keys in object literal syntax (ala Perl)
- Create a new object based on an existing object: var new_object = object(existing_object);
- Create a new object with an object literal or new Object()
- Object/hash keys can only be strings, no other types
- Objects are passed by reference
- All object link to object.prototype eventually but mostly not useful
- Delete members with "delete obj[name]"
- Use "typeof xyz" to determine variable's type. Can walk inheritance tree via "value instanceof Type". Can use "value.constructor" for introspection too.
Patterns: * Create boolean with Boolean(blah) or !!blah * Use === and !== for comparision; skips type coercion to avoid errors * Math in built-in Math.* namespace (Math.random, Math.floor) * string.length * Double-quote and single-quote treated the same * Strings are 16-bit, UCS-2, somewhat incomplete UTF-16 * for (var name in object) { if(object.hasOwnProperty(name)) {} } * Skip final comma in lists or IE gets confused * Don't use with statement * Arrays
* Create: Array literal uses square bracket (preferred syntax over "new Array")
* Read/update: Simple subscripts. Generally can't use dot syntax because integer not valid dot syntax.
* Delete: Use "delete array[n]". Leaves a hole (as undefined). Use "array.splice(n,1)" to close hole.
* Append: via x.push(q,r,s) or x[x.length]=z
* Inherits from Object (not a fundamental type). Indices become stringified keys. No need to predeclare.
* Has a length member, 1 higher than the highest integer subscript
* Do not use for..in (unless you know exactly how all members got added)
* Util funcs: reverse, join, pop, unshift, sort, splice, slice, concat
- Inside functions, "arguments" variable, arguments.length, and arguments.callee are defined
- Four function creation approaches:
1. function myFunction() { alert('hai!'); } # named function via function statement 2. var myFunction = function() { alert('hai!'); } # anonymous function via function operator 3. var myFunction = function myFunctionName() { alert('hai!'); } # named function via function operator 4. var myFunction = new Function("alert('hai!');") # anonymous function via contructor; avoid usageThe name of a named function is available via func.name read-only property
Javascript resources, tutorials, etc : See the javascript-resources note.
Props to Crocker and many others, from whom these notes have been cribbed.