The includes() versus the indexOf() method

Just like for strings, indexOf exists for arrays as well and as you expect, it'll return the position of the element in the array. Take a look:

const arr = ['apple', 'mango', 'banana'];console.log(arr.indexOf('apple')); // 0console.log(arr.indexOf('mango')); // 1console.log(arr.indexOf('apple') >= 0); // true => apple existsconsole.log(arr.includes('apple')); // true => apple existsconsole.log(arr.indexOf('pineapple') >= 0); // false => pineapple                                              // doesn't existsconsole.log(arr.includes('pineapple')); // false => pineapple doesn't                                         //exists

So what's the difference? There's not really a difference unless we talk about NaN and all that weird stuff. For instance:

const arr = ['Some elements I like', ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.