Skip to content
Advertisement

understanding lodash `.every` behavior

I have this very simple example that I cannot understand why it doesn’t work as I would expect.

const items = { custom: null, preset: null }
const val = ._every(items, null)

This returns false why???? Shouldn’t this code mean, if every property in the object fulfills this condition then return true?

Advertisement

Answer

For objects you should use a predicate like below :

const items = { custom: null, preset: null }
console.log(_.every(items , e=> e === 42));
console.log(_.every(items , e=> e === null));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

@Michael you are right. Documentation is not mentioning it explicitly. But if you check its method signature it expects Function for the second argument and also in those examples, there are some short usage versions of it. Those are :

// The _.matches iteratee shorthand. _.every(users, { 'user': 'barney', 'active': false }); // => false

// The _.matchesProperty iteratee shorthand. _.every(users, ['active', false]); // => true

// The _.property iteratee shorthand. _.every(users, 'active'); // => false

So your usage is _.property iteratee shorthand. And it expects a property name. Providing null value to the property name gives you the result : false.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement