JavaScript Cheat Sheet

JavaScript Cheat Sheet

Data Types

JavaScript is a loosely typed language which means a variable's value defines its type. JavaScript has 7 data types grouped as follows:

Primary / Primitive (Have no properties and are immutable)

  • String (typeof == "string") - "abc" | "123" | "" (zero-length)
  • Number (typeof == "number") - 123 | 456.789
  • Boolean (typeof == "boolean") - true | false

Composite / Reference (Are objects so have properties and are mutable)

  • Array (typeof == "object") - [ "abc", "123", 123, [ "rabbit", "hole" ], { foo: "bar" } ]
  • Object (typeof == "object") - { aString: "abc", aNumber: 123, aBoolean: true, anArray: [ "rabbit", "hole" ], anObject: { aDream: "within a dream" } }

Special (Classed as primary / primitive but with no corresponding object constructor)

  • Undefined (typeof == "undefined") - Variable does not exist or has not had a value set
  • Null (typeof == "object") - null

Certain operations will cause the JavaScript interpreter to coerce a variable's type to allow it to complete the requested operation without causing an exception. For example adding a number or a boolean to a string will convert the former variable to a string too (and concatenate the two). Adding a boolean to a number will convert the boolean to a number before adding the values together.

Also note that whilst the primitive types are not objects (unless instantiated with the new keyword, see below), they still have properties/methods available to them from their corresponding object constructor. This is because JavaScript temporarily creates an object wrapper whilst it accesses/performs the requested property/method. This object is immediately destroyed afterwards which explains why you can't access a property that you just added to a primitive, it's gone already!

Built-In Objects

Everything in JavaScript except primitive values are objects. Note that objects in JavaScript are addressed by reference which means assigning an object to the value of another variable does NOT make a copy of the object. It merely creates another pointer to the same object.

String

Instantiation

'string', "string", String(thing), new String(thing)

Properties

length

Methods (most common)

charAt(index), indexOf(needle), match(regexp), replace(needle|regexp, newNeedle), search(needle|regexp), slice(start, exclusiveEnd), split(delimiter|regexp,limit), substr(start, inclusiveEnd), substring(start, exclusiveEnd), toLowerCase(), toUpperCase, trim(), valueOf()

Number

Instantiation

new Number(value)

Methods (most common)

toFixed(decimals), toPrecision(length), toString(), valueOf()

Boolean

Instantiation

new Boolean(value)

Methods

toString(), valueOf()

Date

Instantiation

new Date(milliseconds|dateString|year, month, date[, hours[, minutes[, seconds[, milliseconds]]]])

Methods

get|set + UTC + Date|Day|FullYear|Hours|Milliseconds|Minutes|Month|Seconds|Time + (),
to + Date|GMT|ISO|LocaleDate|LocaleTime|Locale|Time|UTC + String(),
toJSON(), now(), parse(dateString), valueOf(),
UTC(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]])

Math

Instantiation

Math objects don't need to be instantiated and so can just be used with the required property or method directly.

Methods (most common)

abs(x), ceil(x), floor(x), max(x, ...), min(x, ...), pow(base, exponent), random(), round(x), sqrt(x)

RegExp

Instantiation

/pattern/modifiers, new RegExp(pattern, modifiers)

Methods (most common)

exec(string), test(string)

Also note that the String object's match(), replace(), search() and split() methods all accept RegExp patterns as arguments. Learn more about JavaScript regular expressions.

Array

JavaScript arrays are classed as objects except with a numerical index (rather than names/strings). As objects, they can contain mixed collections of data types including objects, functions and other arrays.

Instantiation

[element0, ...], new Array(element0 , ...|arrayLength)

Properties

length (number of elements)

Methods (most common)

concat(array2, ...), indexOf(needle), isArray(object), join(separator), shift(), pop(), unshift(item1, ...), push(item1, ...), sort(), reverse(), slice(start, exclusiveEnd), splice(index, numToRemove, itemToAdd1, ...), valueOf()

Object

Objects contain name:value pairs. The names must be a string (they can be numbers or reserved words but must be enclosed in quotes). The values can be of any data type including arrays, functions (methods) and other objects.

Instantiation

{name: value, ...}, new Object(value)

Properties

Whatever you define

Methods (most common)

Whatever you define, hasOwnProperty(name), propertyIsEnumerable(name), toString(), valueOf()

Function

Functions can be created as a declared function or as a function expression and can be assigned to a variable or object property (as a method). Function expressions can be created without a name as an anonymous function expression. They can even invoke themselves (self-invoked/self-executing/immediately-invoked function expression) as in run automatically on script load. All functions, regardless of how they are created can receive arguments via parameters. When invoked (or called), functions execute the code/procedure contained within. Functions often return a computed value back to the caller of the function. This return value can also be another nested function as in the module pattern. Yes, functions can be nested too (see closures below).

Declaration/Creation

function functionName(param1, ...) { code }, new Function(param1, ..., code), var functionName = function (param1, ...) { code }, functionName: function (param1, ...) { code }, (function (param1, ...) { code })()

Properties

length (number of parameters expected), arguments (.length, [i])

Invocation

functionName(arg1, ...), objectName.functionName(arg1, ...), new functionName(arg1, ...), (function (arg1, ...) { code })()

Closures

Closures allow us to create and access more secure, private variables within functions. Perfect for function factories, they also make it possible to persist an outer function's declared variables and arguments from within the inner function to be returned by the factory.

function makeMyCar( car ) {
	count = 0;
	return function( colour ) {
		count++;
		console.log( "You are #" + count + " in the " + car + " queue. Your chosen colour is " + colour + ".");
	};
}  
  
var fiestaFactory = makeMyCar( "Fiesta" );
fiestaFactory( "Goblin Green" ); // You are #1 in the Fiesta queue. Your chosen colour is Goblin Green.  
  
var bentleyFactory = makeMyCar( "Bentley" );
bentleyFactory( "Posh Purple" ); // You are #1 in the Bentley queue. Your chosen colour is Posh Purple.  
  
fiestaFactory( "Perky Pink" ); // You are #2 in the Fiesta queue. Your chosen colour is Perky Pink.

Hoisting

JavaScript will automatically hoist all variable and function declarations to the top of the current scope, regardless of where they were declared in the script. Note that initialisations of variables and functions expressions will not be hoisted.

console.log( x ); // undefined (the variable definition of x has been hoisted but not initialised yet)
var x = 123;
console.log( x ); // 123 (now the variable x has been initialised)

Strict Mode

If we want to enforce a stricter environment and provide more error/exception information, we can tell browsers to compile in strict mode by placing the following either at the top of the script (global setting for the whole script) or within a function (local setting).

"use strict mode"

Strict mode enforces a boatload of restrictions such as preventing the use of undeclared variables, duplication of object and function parameters and assigning values to non-writable object properties.

JavaScript Reference

Here are some handy places to find a detailed reference for JavaScript: