Javascript

HTML

Import:
<script type="text/javascript" src="js/file.js"></script>
Inline:
<script type="text/javascript">alert('Hello World');</script>
Call:
<button id="start" onClick="start()" style="">Start</button>

More Information

Basics

var name;
Initialize a local variable with value undefined
var name = 1;
Initialize variable with value 1
name = 1;
Initialize a global variable with value 1
typeof name
Returns the name of the variables type as string (e.g. "number")
a === b
Checks for value and type equality as opposed to == which only checks for value equality
document.write('Hello World
')
Write something to the page
window.location = 'http://www.google.com'
Load new url
alert('Hello World')
Open an alert dialog
console.log('Hello World')
Logs to the console in most modern browsers. F12 opens the console in chrome

Math

parseInt(string, base)
Returns an integer (base can be 2 for binary, 10 for decimal, 16 for hex, ...)
parseFloat(string)
Returns a float (always base 10)
Math.round(num * 100) / 100
Round to two decimal places

Special Types

NaN
Not a number. Gets returned when math operation fail. Use isNaN(value) to check for it because its not possible to check via the == operator
Infinity and -Infinity
Represents an infinite number. Use isFinite(nubmer) to check for it (returns false for NaN too)
undefined
Value of variables that hasn't been assigned yet
null
Placeholder for an object when there is no object

Global functions

decodeURI
TODO
decodeURIComponent
TODO
encodeURI
TODO
encodeURIComponent
TODO
eval
TODO
uneval
TODO

Objects

JavaScript objects are simply collections of name-value pairs. Similar to dictionaries or maps in other languages.

Create an object
var obj = new Object();
or
var obj = {};
Access properties
obj.name = "Simon";
or
var name = obj.name;
or
obj["name"] = "Simon";
or
var name = obj["name"];
Initialize object with properties
var obj = { name: "Carrot", "for": "Max", details: { color: "orange", size: 12 } }

Classes

function Person(first, last) { this.first = first; this.last = last; } Person.prototype.fullName = function() { return this.first + ' ' + this.last; } Person.prototype.fullNameReversed = function() { return this.last + ', ' + this.first; }

this refers to the object before the .. new creates a new object and binds it to this. For example: s = new Person("Simon", "Willison") s.fullName;

Common methods

obj.hasOwnProperty("prop")
Checks whether this objects contains the property directly. Unlike "prop" in obj it doesn't check the prototype chain
isPrototypeOf
TODO
obj.propertyIsEnumerable("prop")
Checks if the property can be used in a for ... in .. loop
obj.toString() and obj.toLocaleString()
Returns a string representation of the object. Some objects (e.g. Date) take the configured locale (country/language settings) into account
obj.valueOf()
Returns a primitive value for the object. If there is no primitive value the object itself gets returned. Note that this is usually called automatically via a process called autoboxing.

Describe: Prototype chain

Functions

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

Functions implicitly define the array arguments which contains all parameters. These can be more or less than declared in the function header.

func.apply(null, [2, 3, 4, 5])
Calls function using the content of an array as parameters. First parameter is an object or null if it's a simple function
call
TODO

Arrays

JavaScript objects are simply collections of name-value pairs.

Create an array
var a = new Array(); a[0] = "dog"; a[1] = "cat"; a[2] = "hen"; or var a = ["dog", "cat", "hen"];
a.lenhgt
Returns the lenght of the array. This must not be the amount of values since there could be gaps
Loop
for (var i = 0; i < a.length; i++) { //Do something with a[i] } Do not use the following because it will also loop over every property of the array object: for (var i in a) { // Do something with a[i] }
a.toString()
a.toLocaleString()
a.concat(item[, itemN])
Returns a new array with the items added on to it.
a.join(sep)
a.pop()
Removes and returns the last item.
a.push(item[, itemN])
Push adds one or more items to the end.
a.reverse()
Reverses the order of the elements in this array. Returns the reversed array.
a.shift()
a.slice(start, end)
Returns a sub-array.
a.sort([cmpfn])
Takes an optional comparison function.
a.splice(start, delcount[, itemN])
Lets you modify an array by deleting a section and replacing it with more items.
a.unshift([item])
Prepends items to the start of the array.