Javascript Cheat Sheet

Introduction

Not much here for outsiders. I have to deal with javascript now and then. But not often enough to remember the tricks.

Language summary

Types

	Numbers
	Booleans
	Null
	Undefined
	Object
		Function
		Array
		Strings
		Date
		RegExp 

Numbers

        Has a limited Real->Integer tower.
        Internal rep is double.
        Lots of Math.x stuff.
        Has a reasonable NaN value.
        Has Infinity = 1/0 and -Infinity.

        	parseInt("123") -> 123
        
        Or in base 2:
        
        	parseInt("11", 2) -> 3 

Strings

	Characters are strings of length 1.

	s.charAt(pos)
	s.charCodeAt(pos)
	s.indexOf(s1, start)
	s.lastIndexOf(s1, startPos)
	s.localeCompare(s1)
	s.match(re)
	s.replace(search, replace)
	s.search(regex)
	s.slide(start,end)
	s.split(separator, limit)
	s.substring(start, end)
	s.toLowerCase()
	s.toLocaleLowerCase()
	s.toUpperCase()
	s.toLocaleUpperCase()

Special values

	null = deliberately no value
	undefined = no value has been assigned
	
	The group (0, "", NaN, null, undefined) are false.
	Everything else is true.

Infix comparison operators

	The usual suspects from C.
	
	Also "===" and "!==" can and usually should be used to
	suppress automatic type coercion. The coercion rules
	for == and != are too bizarre to be believed. 

Short circuit evaluation

	if (x && x.getName())
	        ...
		Check for non-null and only then getName. 

Objects

	Objects behave as lists of key-value pairs.

	Create an empty object:
	
		var x = new Object() ;
	
	Literal objects:

		{name: "hugh", age: 54}

	Variables may be introduced anytime:
	
		var x = {name:"hugh", age:23} ;
	
	In the literal expression above, name and age are keys.
	
		x.name = "Bill" ;
	
	OR using associative array notiation:
	
		x["name"] = "Bill" ;
	
		The [] notation enables object component access using
		a runtime-computed key. The key can be any string expression.
	
	Objects may have hierarchical structure
	
		obj = { name: "Gorgo", age: 13, 
			description: { color: "Green", length: 158}} ;
	
	Getting object components:

		obj.description.color
	
	OR using associative array notation
	
		obj["details"]["color"] 

Iteration on keys


	Display the contents of any object:

	for (var key in obj)
	{       print(key + '=' + obj[key]) ;
	} 

Arrays

	var a = ["this", "is", "a", 123, 2.3];
	
	Arrays simply grow when higher index values are used.
	You can append this way:
	
		a[a.length] = item ;
	
	There cannot be an "index out of bounds error"
	
	Array operators:
	
	        a.toString()
	        a.toLocaleString()
	        a.concat(item1, ...)
	        a.join(sep)
	        a.pop()
	        a.push(item1,...)
	        a.reverse()
	        a.shift()
	        a.slice(start, end)
	        a.sort(compareFunction)
	        a.splice(start, delcount, item,...)
	        a.unshift(item...) 

Functions

	function add(x, y)
	{       var total = x+y ;
	        return total ;
	}
	
	Alternative definition:
	
		var add = function(x, y) { var total = x+y; return total ; } ;

	Without an explict return, a function will return the value undefined.

	You can use varargs via the special variable "arguments"
	
	        arguments.length
	        arguments[i]

	Functions can be used anonymously:
	
	        (function(){return arguments[1]+arguments[2]})(2, 3)
	        
	        = 5

	Also
		var x = function(){return arguments[1]+arguments[2]} ;
		
		x(2, 3)
		
		= 5 

	Variables
		var x = 234 ;

		IMPORTANT: Variables may be created anywhere in a function,
		but they become visible in the outermost block:
		There is no nested block scope inside curly brackets.
		This is most weird. For this reason, it is probably best
		to define all vars at the top of the outer scope. 

Classes and methods (sort-of)

	function Person(name, age)
	{	this.myname = name ;
		this.myage = age ;
		this.name = function()
		{	return this.myname ;
		}
		this.age = function()
		{	return this.myage ;
		}
	}

	VAR p = new Person("Hugh Sparks", 52) ;

	"Message expressions":

		p.name()
		p.age()
	
	You can later add methods to an existing "class":
	
		Person.prototype.capitalName() = function()
		{       return this.myname.toUpperCase() ;
		} 

Singleton packages

	Only selected components are visible:
	
	var simon = (function()
	{       var myVar = 5;
	        function init(x)
	        {       Can access myVar and methods.
	        }
	        function doPrivate(x)
	        {       Invisible outside.
	        }
	        function doSomething(x, y)
	        {       Visible outside.
	        }
	        return // Exports
	        {       'init' : init, 'doSomething': doSomething
	        }
	})() ;
	
	simon.init(x).doSomething 

Libraries to investigate

	dojotoolkit.org
	mochikit.com
	prototype.conio.net
	script.aculo.us 

References