JavaScript includes() vs indexOf() with NaN

 Evening Post — Why includes() Works but indexOf() Fails Here This morning’s code was: const arr = [1, 2, NaN, 4]; console.log(arr.includes(NaN)); console.log(arr.indexOf(NaN)); 💡 Correct Output true -1 Yes — same value, same array, different results 😄 Let’s understand why. 🧠 Simple Explanation : 🔹 includes() uses SameValueZero comparison That means: It can correctly compare NaN It treats NaN as equal to NaN So: arr.includes(NaN) ✔ Finds NaN ✔ Returns: true 🔹 indexOf() uses strict equality (===) Important rule 👇 👉 In JavaScript: NaN === NaN // false So when indexOf() checks each element: It compares NaN === NaN That comparison always fails Because of this: arr.indexOf(NaN) ❌ Cannot find NaN ✔ Returns: -1 🎯 Key Takeaways : includes() can find NaN indexOf() cannot find NaN NaN is the only value that is not equal to itself Prefer includes() for value checks 📌 This difference has caused real production bugs. 💬 Your Turn Did you expect both lines to behave the same? 😄 Comment “Surprising 😮” or “Knew this 👍” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #ArrayMethods #TechWithVeera #WebDevelopment

  • graphical user interface, application

To view or add a comment, sign in

Explore content categories