DEV Community 👩‍💻👨‍💻

buginit
buginit

Posted on

Do You Really Know JavaScript Includes Method?

JavaScript includes method is very handy when you need to search or find something in the array or string, yes it works on both. It returns the Boolean value true if the array contains the value and false if not, and the same applied to the strings.

#1 Array Example

var array1 = [1, 2, 3];

console.log(array1.includes(2));
// expected output: true

var pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// expected output: true

console.log(pets.includes('at'));
// expected output: false

#1.1 Find by Specific Index

In JavaScript include method, you can also find values from specific indexes, as second parameter it receives fromIndex for example:

var array1 = [1, 2, 3];

console.log(array1.includes(2, 1));
// expected output: true

var array1 = [1, 2, 3];

console.log(array1.includes(2, 2));
// expected output: false

In the above example, we are passing fromIndex in the second parameter to tell the include() method that if the value exists from that specific index.

To read Full 9 examples of JavaScript Includes Method click here

Top comments (0)

All DEV content is created by the community!

Hey, if you're landing here for the first time, you should know that this website is a global community of folks who blog about their experiences to help folks like you out.

Sign up now if you're curious. It's free!