Beginner · 9 min
Find and test array items
Find one matching value or test whether some or all values meet a condition.
Find the first match
find() returns the first matching item, or undefined when no item matches. Use optional access when the result might be missing.
const products = [{ name: "Pen", price: 2 }, { name: "Book", price: 8 }];
const item = products.find(product => product.price > 5);
console.log(item?.name ?? "Not found");Output
Book
Test a collection
some() checks whether at least one item passes a test. every() checks whether all items pass. For an empty array, some() is false and every() is true.
const scores = [6, 8, 4];
console.log(scores.some(score => score >= 8));
console.log(scores.every(score => score >= 5));Output
true false
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Find an available product
Find the first product whose stock is greater than 0. Display its name.
Change the predicate to product.stock > 0.