6.17 Exercise: Includes method
Okay, now our second exercise. So here we have an array of numbers, you've already seen the includes method before. So here we're going to do a console. Log of numbers.includes. With this method, we can check if a given element exists in the array. Now your exercise is to write a function like the includes method. So imagine that we don't have this method in the arrays, your job is to implement this method yourself. So I want you to create a function called includes that takes an array and a search element that we're going to call searchElement. If we have the search element in the array, we should return true, otherwise we should return false. So pause the video, do this exercise and when you're done, come back and continue watching the fix. Okay so here we need to iterate over this array. If you find an element that is equal to the search element, we return true, otherwise we return false. . Here we're going to use the for of loop. So, for let element of array, now if element = to searchElement, we will return true, so we don't need to search the rest of this array, we immediately return true. Otherwise, we get to this point, which means we didn't find that element in the array, so we return false. Now let's test that. So, I'm going to call the includes function, pass our array of numbers, as the first argument. And 1 as the second argument. Obviously, we have this number, so we get true, but if we pass -1, we get false. That's it for this little exercise on the includes method in JavaScript, we'll see you in the next video.