Transcript of the tutorial.
TOP
So another array method that we can use, which is actually a pretty new array method from a fairly
recent update, is the find method.
Now the find method returns the value of the first element inside an array that passes a certain test
in a callback function.
Now that sounds probably a little bit complex, but don't worry, we're going to do an example that
will really simplify this.
So again, say for example, we have this array of scores and we want to find the first score inside
this array, which is over 50.
Now that would be there, right?
So what the find method is going to do is iterate an array and fire a callback function for each item
in the array.
Now, as soon as it passes a certain condition, i.e. that item is over 50, it will return that value
right there and it won't carry on through the rest of the values in the array.
So let's do this.
Let's come down and we'll say const first.
High score is equal to scores, which is the array dot find.
And then this takes a callback function as an argument.
So we'll create that.
And inside the callback function we can take a parameter which is the individual score we currently
iterate.
And then inside here we need to return either a true or false value.
Now if we return true, it means the test was passed and it will return that value that we're currently
iterating.
If it's false, then it will disregard it and carry on to the next value and fire the callback function
for that.
So what we want to do is return true when the score is over 50, so we can say return score, which
is the individual item we are currently iterating and that is over 50.
Now that is either going to be true or false.
In this case it will be false, so it ignores it and carries on to the next item.
False goes to the next item, etcetera, until it reaches 60.
At this point, this statement right here, this is true.
So the fine method stops here.
It doesn't execute any more callback functions for the rest of the elements.
Instead because we've returned.
True, it takes this value that it's currently on and it returns it to this variable right here.
So let's see if this works.
I'm going to console dot log and then first high score like so.
And there we go.
So if we save this and preview, then we should see 60.
Cool.
Now let me change this to 30 and this to 90.
See if it works.
Save it and refresh and we get 90.
Cool.
So it's stopping when it first finds a value which passes this condition.
Now let's just simplify this arrow function a little bit.
We can do that and we can also take off the return keyword, scoot it up, take away the curly braces
like so, and this still works.
And we can see 90 right there.
So that is the find method.
It returns the first value inside an array, which passes a certain condition.