Skip to content

Instantly share code, notes, and snippets.

@catdad
Last active August 29, 2015 14:00
Show Gist options
  • Save catdad/11239214 to your computer and use it in GitHub Desktop.
Save catdad/11239214 to your computer and use it in GitHub Desktop.
A simple, annotated forEach function
var forEach = function(obj, cb, context){
// check for a native forEach function
var native = [].forEach,
hasProp = Object.prototype.hasOwnProperty;
// if there is a native function, use it
if (native && obj.forEach === native) {
//don't bother if there is no function
cb && obj.forEach(cb, context);
}
// if the object is array-like
else if (obj.length === +obj.length) {
// loop though all values
for (var i = 0, length = obj.length; i < length; i++) {
// call the function with the context and native-like arguments
cb && cb.call(context, obj[i], i, obj);
}
}
// it's an object, use the keys
else {
// loop through all keys
for (var name in obj){
// call the function with context and native-like arguments
if (hasProp.call(obj, name)) {
cb && cb.call(context, obj[name], name, obj);
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment