Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Last active September 30, 2015 06:24
Show Gist options
  • Save softwarespot/e1cb80dbca520862dabe to your computer and use it in GitHub Desktop.
Save softwarespot/e1cb80dbca520862dabe to your computer and use it in GitHub Desktop.
Demo of $.each and $.map
// jQuery source outlines differences
const items = [1, 2, 3, 4, 5];
// MAP
// $.map() returns a new array
const array = $.map(items, function (item, index) { // item first then index
console.log(item);
// Multiply the item by 2 and return so as to push on to the internal stack
return item * 2;
});
console.log('Return from $.map(): %o ', array);
// EACH
// $.each() returns the same array passed in
const array = $.each(items, function (index, item) { // index first then item
console.log(item);
// Break the loop
if (item === 3) {
return false;
}
});
console.log('Return from $.each(): %o ', array);
// NOTE: $.map() can't be "broken" unlike $.each() as false in $.map() is considered a value whereas in $.each(), the callback is a predicate of true or false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment