What is the difference between indexOf and includes?
Answer
indexOf(value, fromIndex) searches for the first occurrence of a value and returns its index, or -1 if not found. Works on both strings and arrays. For arrays: [1,2,3].indexOf(2) → 1. For strings: "hello".indexOf("l") → 2. Uses strict equality (===). includes(value, fromIndex) returns a boolean — true if the value is found. Cleaner for checking existence: if (arr.includes("admin")) reads better than if (arr.indexOf("admin") !== -1). Key difference: includes() correctly handles NaN — [NaN].includes(NaN) is true, but [NaN].indexOf(NaN) is -1 (because NaN !== NaN). Use indexOf when you need the position; use includes when you just need to know if the value exists. Both perform a linear search O(n) — use a Set for O(1) lookups.
Previous
What is the use of the Array.from() method?
Next
What is the prototype chain in JavaScript?