Here are two ways to find the first element of an array matching a condition in JavaScript.
- Using Array.prototype.find()
- Using Array.prototype.filter()
Method 1: Using Array.prototype.find()
To find the first element of an array matching a condition in JavaScript, use the “Array.prototype.find()” method. The find() method accepts a callback function as its argument and returns the first element for which the callback returns a true value. If no element satisfies the condition, find() returns undefined.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const firstNumberGreaterThanFive = numbers.find(num => num > 5);
console.log(firstNumberGreaterThanFive);
Output
6
Method 2: Using Array.prototype.filter()
To find the first element of an array that matches a condition using the Array.prototype.filter() method, you can filter the array based on your condition and then select the first element of the resulting array.
However, remember that the filter() method will process the entire array, even if the first matching element is found early on. This can be inefficient for large arrays, mainly if the match is found before.
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const filteredNumbers = numbers.filter(num => num > 5);
const firstNumberGreaterThanFive = filteredNumbers[0];
console.log(firstNumberGreaterThanFive);
Output
6
Conclusion
The Array.prototype.find() method is more efficient and direct for this purpose, especially with larger arrays. The Array.prototype.filter() method is more suitable when you want to obtain all elements that satisfy a specific condition, not just the first one.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.