Utilities
type
// is this a function?
typeof someValue === 'function';
// is this an object?
someValue != null &&
Object.prototype.toString.call(someValue) === "[object Object]";
// works in modern browsers
Array.isArray(someValue);
// works in all browsers
Object.prototype.toString.call(someValue) === "[object Array]";
Combine and copy objects
// our helper function
function extend(first, second) {
for (var secondProp in second) {
var secondVal = second[secondProp];
// Is this value an object? If so, iterate over its properties, copying them over
if (secondVal && Object.prototype.toString.call(secondVal) === "[object Object]") {
first[secondProp] = first[secondProp] || {};
extend(first[secondProp], secondVal);
}
else {
first[secondProp] = secondVal;
}
}
return first;
};
// example use - updates o1 with the content of o2
extend(o1, o2);
// example use - creates a new object that is the aggregate of o1 & o2
var newObj = extend(extend({}, o1), o2);
Iterate over object properties
for (var myObjectProp in myObject) {
// deal with each property in the `myObject` object...
}
// works in all browsers
for (var prop in myObject) {
if (myObject.hasOwnProperty(prop)) {
// deal w/ each property that belongs only to `myObject`...
}
}
// works in modern browsers
Object.keys(myObject).forEach(function(prop) {
// deal with each property that belongs to `myObject`...
});
Iterate over array elements
// works in all browsers
for (var index = 0; i < myArray.length; i++) {
var arrayVal = myrray[index];
// handle each array item...
}
// works in modern browsers
myArray.forEach(function(arrayVal, arrayIndex) {
// handle each array item
}
Find an element in an array
// works in modern browsers
var indexOfValue = theArray.indexOf('c');
// works in all browsers
function indexOf(array, valToFind) {
var foundIndex = -1;
for (var index = 0; index < array.length; i++) {
if (theArray[index] === valToFind) {
foundIndex = index;
break;
}
}
}
// example use
indexOf(theArray, 'c');
// works in modern browsers
var allElementsThatMatch = theArray.filter(function(theArrayValue) {
return theArrayValue !== 'b';
});
// works in all browsers
function filter(array, conditionFunction) {
var validValues = [];
for (var index = 0; index < array.length; i++) {
if (conditionFunction(theArray[index])) {
validValues.push(theArray[index]);
}
}
}
// use example
var allElementsThatMatch = filter(theArray, function(arrayVal) {
return arrayVal !== 'b';
})
Turn a pseudo-array into a real array
var realArray = [].slice.call(pseudoArray);
[].forEach.call(pseudoArray, function(arrayValue) {
// handle each element in the pseudo-array...
});
Modify a function
Change a function's context
// works in modern browsers
function Outer() {
var eventHandler = function(event) {
this.foo = 'buzz';
}.bind(this);
this.foo = 'bar';
// attach `eventHandler`...
}
var outer = new Outer();
// event is fired, triggering `eventHandler`
// works in all browsers
function Outer() {
var self = this,
eventHandler = function(event) {
self.foo = 'buzz';
};
this.foo = 'bar';
// attach `eventHandler`...
}
var outer = new Outer();
// event is fired, triggering `eventHandler`
Create a new function with some pre-determined arguments
function log(appId, level, message) {
// send message to central server
}
var ourLog = log.bind(null, 'master-shake');
// example use
ourLog('error', 'dancing is forbidden!');
Trim a string
// works in modern browsers
' hi there! '.trim();
// works in all browsers, but needed in IE 8 and older
' hi there! '.replace(/^\s+|\s+$/g, '');
// works in all browsers
function trim(string) {
if (string.trim) {
return string.trim();
}
return string.replace(/^\s+|\s+$/g, '');
}
Associate data with an HTML element
// works in all browsers
var data = (function() {
var lastId = 0,
store = {};
return {
set: function(element, info) {
var id;
if (element.myCustomDataTag === undefined) {
id = lastId++;
element.myCustomDataTag = id;
}
store[id] = info;
},
get: function(element) {
return store[element.myCustomDataTag];
}
};
}());
// use it
// make the elements aware of each other
var one = document.getElementById('one'),
two = document.getElementById('two'),
toggle = function(element) {
if (element.style.display !== 'none') {
element.style.display = 'none';
}
else {
element.style.display = 'block';
}
};
data.set(one, {partnerElement: two});
data.set(two, {partnerElement: one});
// on click, either hide or show the partner element
// remember to use `attachEvent` in IE 8 and older, if support is required
one.addEventListener('click', function() {
toggle(data.get(one).partnerElement);
});
two.addEventListener('click', function() {
toggle(data.get(two).partnerElement);
});
// works only in the latest browsers
// make the elements aware of each other
var weakMap = new WeakMap(),
one = document.getElementById('one'),
two = document.getElementById('two'),
toggle = function(element) {
if (element.style.display !== 'none') {
element.style.display = 'none';
}
else {
element.style.display = 'block';
}
};
weakMap.set(one, {partnerElement: two});
weakMap.set(two, {partnerElement: one});
// on click, either hide or show the partner element
// remember to use `attachEvent` in IE 8 and older, if support is required
one.addEventListener('click', function() {
toggle(weakMap.get(one).partnerElement);
});
two.addEventListener('click', function() {
toggle(weakMap.get(two).partnerElement);
});
// works in all browsers
var data = window.WeakMap ? new WeakMap() : (function() {
var lastId = 0,
store = {};
return {
set: function(element, info) {
var id;
if (element.myCustomDataTag === undefined) {
id = lastId++;
element.myCustomDataTag = id;
}
store[id] = info;
},
get: function(element) {
return store[element.myCustomDataTag];
}
};
}());