Underscore JS Some Function

underscore js some function

In this ongoing look at Underscore JS, we’ll take a look at the some function. It bears a close resemblance to the find function. The some function has a signature of _.some(list, [predicate], [context]). What it does is to scan the list parameter for any items that contain a truthy value and return true if this is the case. This is the default behavior without passing the optional predicate function. If you provide a predicate function, some will return true for any items in the list that pass the test of the predicate function. Let’s have a look at how to make use of the some() function now.

Mixed Array Example

This first example will use examine the contents of an array that has a combination of truthy and non truthy values. When we run this example code, we are in fact returned the true value since even though the array contains non truthy values, it also has at least one truthy value so that returns a true result.

Click Clear

Integer Array Example

This example of using some on an array of integers is pretty easy. Of course an array of integers is going to have mostly truthy values, so as we expect when running the code we get the result of true.

Click Clear

Predicate Function to check for Even Numbers

In this example, we will have a look at using a predicate function as the second option to see if any of the integers in our array are even. Let’s see how to do that.

Click Clear

Object Array Example

In looking at the Object Array example code, we can find out if any of the records that we have in our array have a true value for electric. So, haselectricCriteria looks to see if electric does not equal false. As we can see the Tesla is in fact electric, so when this example runs we find it is true.

Click Clear

Guard Clause Example

When we run this example guard clause code, we can see that both calls to the log function do in fact execute. The first scenario is triggered when an empty array or an object without any properties defined are found. If we inspect listOne and objectOne, clearly this is the case. In the second example, the logging is triggered when we have an array with at least one element that is not null and is not undefined or when we have an object that has at least one property that evaluates as true.

Click Clear

Underscore JS Some Function Summary

This tutorial used several code snippet examples to inspect how the some() function works in the Underscore JS Library. It’s a pretty simple mechanism of checking for truthy values in a variety of scenarios.