Javascript Array: indexOf() vs Array includes()
1 min readFeb 14, 2021
Array methods to find if an element exists
Array.prototype.indexOf (searchElement):
- It accepts an element as an argument and returns the first index when it finds the element
- returns -1 if the element could not be found
let a = [1,2,3,4,"5","6"];
a.indexOf("5") // returns 4
a.indexOf(5) // returns -1 , it looks for strict equal
Array.prototype.includes(searchElement,fromIndex)
- It accepts an element as a first argument and an index as a second argument from where the scanning should start
- returns a truthy value if an element is found and returns false in case it’s not found
let a = [1,2,3,4,"5","6"];
a.includes("5") // returns true
a.includes(5) // returns false,it looks for strict equal
a.includes(4,3) // returns true since `4` is present at index 3
a.includes(4,4) // returns false since it scans from index 4
Conclusion: what to use?
should consider includes since it returns a boolean value and avoids extra comparison with -1
, It suffices the need most of the time