Methods

Array

array.concat(items) Create shallow copy of array with items added to the end.
array.join(separator)
array.pop() Remove (and return) last element
array.push() Add elements to end, returns length
array.reverse()
array.shift() Remove (and return) first element
array.unshift(item) Add elements to beginning, returns length
array.slice(start, end) Shallow copy
array.splice() Modifies original element, returns array of removed elements
array.sort(comparator) comparator = function(a, b){}

Function

function.apply(thisArg, argArray) Invoke function with thisArg as the receiver
function.bind(thisArg, argArray) Returns a function that has thisArg as the receiver.

Implementing Bind http://jsbin.com/vewapaci/3/edit

Object

Object.create(proto, propertiesObj) TODO!
Object.defineProperty(obj, prop, descriptor) Attaches prop to obj given the property descriptor object
Object.getOwnPropertyDescriptor(obj, name) name is a string
Object.getOwnPropertyNames(obj)
Object.keys() Returns an object's own properties
Object.getPrototypeOf() Return's the argument's prototype.

Inherited from Object.prototype

hasOwnProperty('propName') true if propName is a property
propertyIsEnumerable('propName')
isPrototypeOf() var person = {...}
var dev = Object.create(person, { propertyDescriptor });
person.isPrototypeOf(person) // true
valueOf() Called when an operator is used.
toString() Used as a fallback when valueOf() returns a reference value

JS Cheat Sheet

Arrays

  • Arrays are sparse. Specialized objects with a length property
  • Limited to 232 - 1 elements

Slice

fruits = ['apples', 'oranges', 'banana', 'pear', 'grape'];
basket = fruits.slice(2, 3);
//fruits = [ 'apples', 'oranges', 'banana', 'pear', 'grape' ]
//basket = [ 'banana' ]
  • (start, end), exclusive of end
  • Creates a shallow copy
  • Leaves original array unchanged
  • Returns an array of copied elements

Splice

fruits = ['apples', 'oranges', 'banana', 'pear', 'grape'];
basket = fruits.splice(2, 3);
//fruits = [ 'apples', 'oranges' ]
//basket = [ 'banana', 'pear', 'grape' ]
  • (start, count)
  • Removes count number of elements from the array
  • Inserts new elements into the original array
  • Returns an array of the removed elements (possibly empty)

forEach

someArray.forEach(function(element, index, array) {
 //
});
  • element
  • index
  • array - the original array

String

substr

str.substr(start[, length])
Returns length characters from start position.
If start is negative, it counts from the right.
If length is negative or start > length, then empty string is returned.

substring

str.substring(indexA[, indexB])
If an argument is less than 0, or NaN, it is treated as 0.

Functions

Function Declaration
foo();    // works
function foo() {
  console.log('hi');
}
foo();    // works
Function Expression
foo();    // fails
foo = function() {
  console.log('hi');
}
foo();    // works
Named Function Expression
foo();    // TypeError: undefined not a function
bar();    // ReferenceError: bar is not defined
foo = function bar() {
  console.log('hi');
}
foo();    // okay!
bar();    // ReferenceError: bar is not defined

Bit Manipulation

x >> n right shift (by n) sign is copied; effectively divide by 2n
x >>> 0 right-shift (by 0) without sign extension Cast native JS double to int
~~x double bit-wise not parseInt(x, 10), or Math.floor(x)
!!~array.indexOf(...) Fancy way of:
if (array.indexOf(...) >= 0)

Checks

typeof 1                // "number"
typeof '1'              // "string"
typeof true             // "boolean"
typeof undefined        // "undefined"
typeof null             // "object"
typeof {}               // "object"
typeof function(){}     // "function"
  
Checks for:
  • Number
  • String
  • Boolean
  • Object
  • Function
Returns function if an object has a [[Call]] internal property.
someArray = [...];

// ES5
Array.isArray(someArray);

// Polyfill
if(!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}
When you call toString on an object, you get [object Cnstrctr]
 _.isObject = function(obj) {
  return obj === Object(obj);
};
Checking for properties
obj.prop !== undefined
obj.hasOwnProperty('prop')
'prop' in obj
Checking for properties

Casts

+x
Cast to number
x + ""
Cast to string
!!x
Cast to boolean
config = typeof config !== 'undefined' ? config : 42;
Default values.

Object Internals

Internal Methods

[[Put]] Method: Add an own property to an object
[[Set]] Method: Modify a property already on an object
[[Delete]] Method: remove a property. Called by delete operator.

Methods Inherited from Object.prototype

hasOwnProperty() Determine if own property exists with given name
propertyIsEnumerable() Determine if property is enumerable (has enumerable attribute = true)
isPrototypeOf() Determine if object is prototype of another
valueOf() Called when operator is used on an object
toString() Called when valueOf() returns a reference value instead of primitive.
  • All properties added to an object are enumerable by default
    • Iterable with a for-in loop
    • Has an internal [[Enumerable]] attribute set to true

Types of Properties

Property Attribute Data Properties Accessor Properties
[[Value]] Automatically filled, even functions N/A
[[Enumerable]]
Counted by Object.keys()
true
[[Configurable]]
Can remove with delete, or update config
true
[[Writable]] true
Throw an error if attempt to change a nonwritable prop
N/A
[[Get]] N/A
[[Set]] N/A

Preventing Object Modification

Prevent Extension

Cannot add properties

Object.isExtensible(obj);
Object.preventExtensions(obj);
Seal

Cannot add properties

Cannot remove properties

Cannot change property type (data ⇔ accessor)

Object.isSealed(obj);
Object.seal(obj);
Freeze

Cannot add properties

Cannot remove properties

Cannot change property type (data ⇔ accessor)

Cannot write to data property

Object.isFrozen(obj);
Object.freeze(obj);

Defining an Accessor Property via Object Literal

var person1 = {
  _name: "Nicholas",

  get name() {        // ES5
    // ...
  }
}

Object Patterns

Singleton

var MySingleton = (function(){
  // store reference to instance
  var instance;
  
  function init(){
    // private variables
    return {

    }
  }

  // Singleton Return Object: A single accessor getInstance()
  return {
    getInstance: function(){
      if (!instance) {
        instance = init();
      }
      return instance;
    }
  }
})();
function Universe() {
  // cache the instance
  var instance = this;

  // declare variables, init

  // redefine constructor
  Universe = function() {
    return instance;
  }

  /* May need to preserve prototype....
  Universe.prototype = this;
  instance = new Universe();
  instance.constructor = Universe;
  */
}

Factory

function createPerson(name, age) {
  var o = new Object();
  o.name = name;
  o.age = age;
  return o;
}
Call a method that creates an object then returns it.

Constructor Pattern

function Person(name, age) {
  this.name = name;
  this.age = age;
}
  • Methods are created for each instance.
  • Get around this by pointing method to externally defined function, or attaching to prototype.
new Person('Tuan', 32);
Use a function as a constructor with the new operator.
  • prototype property gets added.
  • Each instance gets a [[Prototype]] property, __proto__.

new-Agnostic Constructors

function User(name){
  if (!(this instanceof User)) {
    return new User(name);
  }
  this.name = name;
}
Requires extra function call :(
function User(name){
  var self = this instanceof User
           ? this
           : Object.create(User.prototype);
  self.name = name;
  return self;
}

Inheritance

Suppose we have the following:

function Parent(){
  this.name = name || 'Adam';
}

Parent.prototype.sayName = function(){}

Classical #1 - Set Prototype

function Child(){}
Child.prototype = new Parent();
  • Inherit properties added to parent as well as child.
  • Cannot define arguments when calling child constructor

Classical #2: Borrow Constructor

function Child(a, b, c, d){
  Parent.apply(this, arguments);
}
  • The child's constructor simply executes the parent constructor
  • Nothing from parent's prototype is inherited

Classical #3: Borrow Constructor, Set Prototype

function Child(){
  Parent.apply(this, arguments);
}
Child.prototype = new Parent();
  • Requires two calls to parent constructor

Classical #4: Shared Prototype

Child.prototype = Parent.prototype
  • Modifying the child prototype will affect parents!

Classical #5: Temporary Constructor

var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();

Child.uber = Parent.prototype;          // store the super class
Child.prototype.constructor = Child;    // restore constructor
  • Create a proxy
  • no reference to the original parent...

Prototypical Inheritance

function Parent(){
  //....
}
var parent = new Parent();

// Inheritance here:
function F(){} // empty function
F.prototype = parent;

var child = new F();
  • Methods can be attached to prototype as properties.
var child = Object.create(parent)
  • Since parent is in instance, parent's own properties are now on child's instance
var child = Object.create(Parent.prototype)
  • Only copies over the prototype properties.

Design Patterns

Publish/Subscribe

var publisher = {
  subscribers: {
    any: []       // any is 'event'
  },
  subscribe: function(fn, type) {
    type = type || 'any';
    this.subscribers[type].push(fn);    // add callback to the event
  },
  unsubscribe: function(){},
  publish: function(publication, type) {
    this.visitSubscribers('publish', publication, type);
  },
  visitSubscribers: function(action, arg, type) {
    // iterate thru the subscribers for a given 'type'
    var subscribers = this.subscribers[type];

    subscribers.forEach(function(element, index, array){
      element(arg);
    });
  }
}
## Modular Design Patterns

AMD

define(function(require){
  var lib = require( "package/lib" );

  // behaviour for our module
  function foo(){
    lib.log( "hello world!" );
  }

  // export (expose) foo for other modules
  return {
    foobar: foo
  };
});

// -- Consuming the module
require(["foobar", "baz"], function ( foobar, baz ) {
  // rest of your code here
  foobar.doSomething();
});
  • Browser-first approach to development
  • Asychronous
  • Require.js

CommonJS: require() and exports

// -- foobar.js ------------------
var lib = require( "package/lib" );
 
// behaviour for our module
function foo(){
  lib.log( "hello world!" );
}

// export (expose) foo to other modules
exports.foo = foo;




// -- Consuming the module -------
var foobar = require("./foobar.js").foobar,
    test   = new foobar();

 
  • Server-first approach to development
  • File I/O
  • CommonJS, Node

Events

  • on(name, callback, context)
  • off(name, callback, context)
  • trigger(name)