

Just remember: only use find when you want a single element returned, and that it returns undefined if nothing is found! Otherwise, use the filter method when you need multiple elements returned. It’s one of several useful methods available on Arrays, for a more complete guide see How To Use Array Methods in JavaScript: Iteration Methods. The find () method does not change the original array. The find () method does not execute the function for empty elements. The find () method returns undefined if no elements are found. ConclusionĪrray.find is a simple but incredibly useful method for searching JavaScript arrays. The find () method executes a function for each array element. The index is probably not something you’ll need often - but it’s great to have available at times. In non-shorthand, non-ES6 form: const result = trees. Here’s a simple example with an array of strings: const trees = const result = trees.

find (testingFunction ) // that's it! Simple example: Using find() is super easy! The only required parameter of this method is a testing function, and it can be as simple or complex as needed. So if you only need a single value, use find()! When you need to find/return multiple values, reach for filter() instead. Another difference is when nothing is found, this method returns a value of undefined. The function and syntax of find() is very much like the Array.filter method, except it only returns a single element.

When you want a single needle from the haystack, reach for find()! When to Use Array.find Enable JavaScript to view data.The JavaScript Array.find method is a convenient way to find and return the first occurence of an element in an array, under a defined testing function. 規範 SpecificationĮCMAScript Language Specification # īCD tables only load in the browser with JavaScript enabled. If you need to support truly obsolete JavaScript engines that don't support fineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable.
