Introduction
In this lab, we will explore how to check if any element in an array is truthy using JavaScript. We will use the Array.prototype.some() method and a provided predicate function to test if at least one element in a collection returns true. Additionally, we will learn how to use the Boolean function as a default argument to simplify the code.
Testing if Any Array Element is Truthy
To start practicing coding, open the Terminal/SSH and type node.
To check if any element in a collection returns true based on a provided function, use Array.prototype.some(). If you want to use the Boolean function as default, you may omit the second argument, fn.
Here is an example code:
const any = (arr, fn = Boolean) => arr.some(fn);
You can test it using the following examples:
any([0, 1, 2, 0], (x) => x >= 2); // true
any([0, 0, 1, 0]); // true
Summary
Congratulations! You have completed the Test if Any Array Element Is Truthy lab. You can practice more labs in LabEx to improve your skills.