Determining whether an array contains a given data point or value can be easily done using javascript Function called includes(). This function is a generic function and works with any array like objects. It intern returns a boolean value determining whether the value is present or not.

Finding whether an element exists in an Array

A simple example for using include is as follows, there can be nothing simpler as such.

You can see how the array of numbers can be used to test what is being included in the array. This way it returns back a boolean value telling us whether something exists in the array or not.

Finding whether an element exists in a specified index

In certain cases when we want to see whether there is a data point on a specific index. Let’s have a look at how we can check this out.

As we can see that we can pass the data as well as the index which we want to search for. The index refers to the data at the given index. So in this way you can easily find whether there is a certain data that is contained at a specific index.

Check whether a String includes() a Sub String

You can also check whether a simple string contains a sub string as well. Let’s see a simple example.

Using Includes() as Generic Method

As we have discussed, includes() is a generic function and here we will see the sample of the same. This sample is being taken up from MDN. Now let’s see a sample which tells whether a function has certain arguments.

Here you can see how the includes() can check whether there is an argument that is being passed to the function. You can also see the entire application working on the repl.it.

Check out all the other posts on JavaScript Essentials to get a Grasp of these JavaScript Utilities.

 


Also published on Medium.

Join our 2500+ fellow readers

Join our 2500+ fellow readers

Joining our mailing list will for sure keep you at the top of Web Development Ecosystem. Connect with us and also other fellow developers.

You have Successfully Subscribed!

Pin It on Pinterest

Share This