In the previous blogpost we discussed the map method on arrays in JavaScript. We still have some useful methods the go. Next in line are the some and every methods. These methods are similar and can be very useful when validating data.
var isEven = function (n) { return n % 2 === 0 }; var areAllEven = [2, 4, 6].every(isEven); var someEven = [1, 2, 3].some(isEven);
The every method will check if for every element in the list, the callback functions returns true. If there is one single item in the array that returns false, the every method will return false as well. The some method is satisfied when there is at least one element in the array where the callback returns true.
var stockItem = { hasBeenShipped: true }; var selection = [/* list of stock items selected in a list */]; var hasNotBeenShipped = function (si) { return !si.hasBeenShipped }; var hasBeenShipped = function (si) { return si.hasBeenShipped }; $('#sendStockItems').attr('disabled', selection.every(hasNotBeenShipped)); $('#sendStockItems').attr('disabled', selection.some(hasBeenShipped));
The example here will disable a button when the selection in the list contains one or more items that already have been shipped. This code is very readable and concise. You can almost read exactly what it does: set attribute disabled when selection has some items that hasBeenShipped.
