Last active
September 30, 2015 06:24
-
-
Save softwarespot/e1cb80dbca520862dabe to your computer and use it in GitHub Desktop.
Demo of $.each and $.map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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