find() Method – How to Find the Element that First Passes a Test
Whenever you use find() on an array, the method returns the calling array’s value that first passes the function argument’s test.
But if no element passes the test, find()
will return undefined
.
Syntax of the find()
Method
find()
accepts two arguments: a “callback function” and a “thisValue.” Here is the syntax:
Argument 1: callback
A function is the first argument accepted by the find()
method. It is a required argument containing the code you want the computer to use to test each item of the calling array.
The callback function returns the value that first passed the test or undefined
if it finds no item.
Keep in mind that find()
’s function argument accepts three parameters: currentItem
, index
, and an array
.
Parameter 1: currentItem
The currentItem
parameter is required. It represents the current calling array’s item the computer is currently processing.
Parameter 2: index
The index
parameter is optional. It represents the index number of the item the computer is currently processing.
Parameter 3: array
The array
parameter is also optional. It represents the calling array.
Argument 2: thisValue
A thisValue
is the second argument accepted by the find()
method. It is an optional argument representing the value you want to use as the function argument’s this
value.
Suppose you do not provide a second argument. In that case, the computer will use undefined
as the callback function’s this
value.
Example 1: How to Use find()
without a thisValue
Argument
Here is an example of the find()
method without a thisValue
argument:
The snippet above used the find()
method to find the first color having lengths greater than three (3
).
Example 2: How to Use find()
with a thisValue
Argument
Here is an example of the find()
method with a thisValue
argument:
In the snippet above, we used the find()
method to find the first color having lengths greater than three (3
).
Observe that we used the itemLength
callback function to add find()
’s this
value to each iteration of the colors
array’s items—except the first one.
In other words, we used the callback function to mutate the original array.
Therefore, the colors
array’s current content will be: