JavaScript Cheat Sheet

November 26, 2010

JavaScript Basics

Variables

Undeclared variables are global not local, and discouraged.

Variables are type agnostic.

Semicolons are optional but encouraged.

Table 1 Primitive types in JavaScript
Type Description
number A numerical value, capable of handling integer and floating-point values
boolean A logical value, either true or false
string A sequence of characters
null No value
undefined An unknown value
var x = 1 + parseInt("2", 10);

IUse the parseInt function to do numerica addition.

Anything that is not a primitive type is an object.

Primitive types are promoted to objects as needed.

Conditionals

As in most C-like languages, true is equivalent to the number one (1) and false is equivalent to the number zero (0). Javascript coerces values of different types before evaluating.

Table 2 Conditional Operators
Operator Description
== Returns true if both values are equal.
=== Returns true if both values are equal and of the same type.
!= Returns true if values are not equal.
!== Returns true if both values are not equal or not of the same type.
< Returns true if the left value is less than the right value.
<= Returns true if the left value is less than or equal to the right value.
> Returns true if the left value is greater than the right value.
>= Returns true if the left value is greater than or equal to the right value.

Switch Statement

switch ( variable ){
    case 1: // code to execute when variable equals 1
        break;
    case 2: // code to execute when variable equals 2
        break;
    default: // ... when variable equals something else
        break;
}

Loops

While, Do While, For

Functions

function myFunction ( variableOne, variableTwo )
{
    // code to execute within this function
}

Functions can be declared and used anywhere within a block of JavaScript code. Variables that contain primitive values are passed into a function by value, whereas objects are passed in by reference. Functions can optionally return a value using the return keyword.

Functions implicitly return undefined if you don’t supply a return value.

Functions can also be assigned to a variable, like this:

var myFunctionVariable = function ( variable )
{
    // code to execute within this function
}

Once a function is defined within a variable, it can be passed as an argument into any other function. Within the receiving function, you can call that function by placing parentheses after the variable’s name and optionally including arguments, like this:

function myFunction ( myFunctionVariable )
{
    myFunctionVariable( "aString" );
}

Other Special Characters

Ternary

The question mark and colon can be used in a comparison or calculation in the same way you would use an if-then-else statement in code. For example, suppose you want to increment or decrement the value of variable Q, depending on whether the value of the variable increment is true or false. You could write that code in either of two ways:

if (increment) { Q++; } else { Q--; }
// or
Q=increment ? Q+1 : Q-1;

The Comma Separator

The comma separator is used to separate items in lists, such as function parameters, items in an array, and so on, and under some circumstances, can also be used to separate expressions.

When used to separate expressions, the comma separator instructs the interpreter to execute them in sequence. The result of the expression is the rightmost expression. This use of the comma is generally reserved for locations in your code where a semicolon has special meaning beyond separating statements.

If you need to increment multiple values at each stage of the loop, you could make your code harder to read by indexing one value off of the other (maybe) or by placing additional assignment statements prior to the start of the loop and as the last statement in the loop. However, this practice tends to make it harder to spot the loop iterator variables and thus makes the code harder to follow.

Instead, you should write the for loop as shown in this snippet, which displays an alert with five characters each, taken from different places in two strings:

var string = "The quick brown fox jumped over the lazy dog.";
var stringb = "This is a test.  This is only a test.";
for (var i=0, j=4; i<5; i++, j++) {
        alert('string['+i+'] = '+string[i]);
        alert('stringb['+j+'] = '+stringb[j]);
}

Object-Oriented JavaScript

JavaScript doesn’t follow object-oriented design patterns but does provide support for common conventions including constructors and inheritance.

Declaring an Object

To define an object, first create a new function with the desired object name.  This function works as the constructor handling any arguments.  Persist instance variables with the this keyword.

function myObject()
{
    this.myVariable = 5;
    // constructor code goes here
}

To create a new member function, create a new anonymous function and assigne it to the prototype property of the object. This must be done outside the constructor. Not to be confused with assigning a function to a member variable of a class.

myObject.prototype.memberMethod = function()
{
    // code to execute within this method
}

Create a new object instance with the new keyword.

var myObjectVariable = new myObject();

Freeing Objects

delete myObjectVariable;

The JavaScript runtime automatically garbage collects objects when their value is set to null. However, setting an object to null doesn’t remove the variable that references the object from memory. Using delete ensures that this memory is reclaimed in addition to the memory used by the object itself.

Arrays

Arrays are objects so must be initialized

var myArray = new Array();

or

var myArray = [];

Reference the elements using the index value (integer, zero based) inside square brackets. Notice they hold any type of data.

myArray[0] = "first value";
myArray[1] = 5;

Generic objects and arrays can be used with associative properties, where strings replace the index number.

myObject["indexOne"] = "first value";
myObject["indexTwo"] = 5;

When you use a string as an index, you can use a period instead of brackets to access and assign data to that property:

myObject.name = "Apple Inc.";
myObject.city = "Cupertino";

You can declare an object and it’s contents inline:

myObject = {
    name: "Apple Inc.",
    city: "Cupertino"
}

A variation of the for loop is available for iterating within the properties of an array or object. Called a for-in loop, it looks like this:

for ( var index in myArray )
{
    // code to execute within this loop
}

Getters and Setters

Recent WebKit builds have support for getter and setter functions. They behave like a variable but really call a function to change values.

myObject.__defineGetter__( "myGetter", function() { return this.myVariable; } );
myObject.__defineSetter__( "mySetter", function(aValue) { this.myVariable = aValue; } );
...
var someVariable = myObject.myGetter;
myObject.mySetter = someVariable;

Inheritance

Inherit from other objects using the prototype keyword. Note the prototype keyword used in 2 places. This must be done on the constructor function names, not the variable instance name of a class.

MyChildObject.prototype = MyParentObject.prototype;

This copies the functions and variables of the parent into the child object but does not copy the default values. You must execute code equivalent to the original constructor, or copy the values of an instance of the parent class.

Recent WebKit builds include the ability to extend an existing DOM object via the code>prototype keyword. This results in a smaller memory footprint and easier function overloading vs inheritance.

Copying an Object

http://developer.apple.com/library/safari/#documentation/ScriptingAutomation/Conceptual/JSCodingGuide/OOJavaScript/OOJavaScript.html

…a work in progress…

Leave a Comment