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
JavaScript includes() vs indexOf() with NaN
More Relevant Posts
-
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
To view or add a comment, sign in
-
-
🌙 Evening Post — Explanation & Answer ✅ Why This Map Has Two Entries This morning’s code was: const map = new Map(); map.set({}, "first"); map.set({}, "second"); console.log(map.size); 💡 Correct Output 2 Yes — two entries, not one 😄 Here’s why 👇 🧠 Simple Explanation : 🔹 Objects are compared by reference, not by value Even though both keys look like {}: {} !== {} Each {} creates a new object in memory. So JavaScript sees this as: Key 1 → one object reference Key 2 → another object reference They are completely different keys. 🔹 How Map works Map allows any type as a key Keys are matched by reference Different object references → different entries So: map.size // 2 🎯 Key Takeaways : Map keys are compared by reference {} and {} are never the same key Objects are not value-equal by default This behavior is different from plain objects 📌 To use the same key, you must reuse the same reference: const key = {}; map.set(key, "first"); map.set(key, "second"); 💬 Your Turn Did you expect the size to be 1 or 2? 😄 Comment “Got it wrong 😅” or “Knew this 👍” #JavaScript #LearnJS #FrontendDevelopment #CodingInterview #Maps #TechWithVeera #WebDevelopment
To view or add a comment, sign in
-
-
𝗪𝗲𝗹𝗰𝗼𝗺𝗲 𝘁𝗼 𝗗𝗮𝘆 𝟵 Have you ever updated one variable… and another one changed automatically? 𝙋𝙖𝙪𝙨𝙚 𝙛𝙤𝙧 𝙖 𝙨𝙚𝙘𝙤𝙣𝙙 — 𝙬𝙤𝙪𝙡𝙙 𝙮𝙤𝙪 𝙚𝙭𝙥𝙚𝙘𝙩 𝙩𝙝𝙞𝙨 𝙘𝙤𝙙𝙚 𝙩𝙤 𝙢𝙪𝙩𝙖𝙩𝙚 𝙗𝙤𝙩𝙝 𝙫𝙖𝙡𝙪𝙚𝙨? { 𝚕𝚎𝚝 𝚞𝚜𝚎𝚛𝟷 = { 𝚗𝚊𝚖𝚎: "𝙰𝚕𝚎𝚡" }; 𝚕𝚎𝚝 𝚞𝚜𝚎𝚛𝟸 = 𝚞𝚜𝚎𝚛𝟷; 𝚞𝚜𝚎𝚛𝟸.𝚗𝚊𝚖𝚎 = "𝙹𝚘𝚑𝚗"; 𝚌𝚘𝚗𝚜𝚘𝚕𝚎.𝚕𝚘𝚐(𝚞𝚜𝚎𝚛𝟷.𝚗𝚊𝚖𝚎); // "𝙹𝚘𝚑𝚗" } Why did user1 change? Because: • Both variables point to the same memory address • No copy was created • Only the reference was shared 𝘛𝘩𝘪𝘴 𝘪𝘴 𝘑𝘢𝘷𝘢𝘚𝘤𝘳𝘪𝘱𝘵’𝘴 𝘝𝘢𝘭𝘶𝘦 𝘷𝘴 𝘙𝘦𝘧𝘦𝘳𝘦𝘯𝘤𝘦 𝘣𝘦𝘩𝘢𝘷𝘪𝘰𝘳 — 𝘢𝘯𝘥 𝘪𝘵’𝘴 𝘥𝘦𝘦𝘱𝘭𝘺 𝘵𝘪𝘦𝘥 𝘵𝘰 𝘮𝘦𝘮𝘰𝘳𝘺. 𝙏𝙝𝙚 𝙈𝙚𝙣𝙩𝙖𝙡 𝙈𝙤𝙙𝙚𝙡 (𝙈𝙚𝙢𝙤𝙧𝙮 𝙁𝙞𝙧𝙨𝙩) JavaScript mainly uses two memory areas: -> Stack Memory • Stores primitive values • Fixed size • Fast access -> Heap Memory • Stores objects, arrays, functions • Dynamic size • Accessed via references 𝙒𝙝𝙚𝙣 𝙥𝙖𝙨𝙨𝙚𝙙 𝙗𝙮 𝙫𝙖𝙡𝙪𝙚: A copy of the actual value is passed. Primitives (number, string, boolean, null, undefined, symbol) are always passed by value. 𝙒𝙝𝙚𝙣 𝙥𝙖𝙨𝙨𝙚𝙙 𝙗𝙮 𝙧𝙚𝙛𝙚𝙧𝙚𝙣𝙘𝙚: A memory address (reference) is passed, not the object itself. Objects & arrays live in heap memory. #JavaScript #JSFundamentals #MemoryManagement #FrontendDevelopment #ReactJS #BugFixing #InterviewPrep #LearningInPublic
To view or add a comment, sign in
-
🚀 LeetCode: 3Sum The goal is to find all unique triplets in an array that sum up to zero. This is a significant step up from Two Sum, requiring careful handling of duplicates to ensure every triplet in the result is unique. 🛠️ My Approach Sorting for Strategy: I started by sorting the array in ascending order. This is crucial as it allows us to easily skip duplicate values and use a directional two-pointer technique. 🔡 Fixed Element Loop: I iterated through the array, treating each element as a potential first part of a triplet. To optimize, if the current element is greater than zero, I break the loop immediately since no combination of following positive numbers can sum to zero. 🧹 Two-Pointer Optimization: For each fixed element, I used two pointers—one starting just after the fixed element (l) and one at the very end (r). 📍 If the sum is too high, I move the right pointer in. If the sum is too low, I move the left pointer out. When a sum of zero is found, I capture the triplet and then skip any identical adjacent values to avoid duplicate results. ❌ This approach transforms a potential O(n^3) brute-force cubic time complexity into a much more efficient quadratic solution. 📊 Efficiency Analysis ⏱️ Time Complexity: O(n^2) due to the nested two-pointer search inside the main loop. 💾 Space Complexity: O(1) or O(n) depending on the implementation of the sorting algorithm, as we don't use extra data structures for the search itself. Achieving a 91.76% runtime beat on this classic problem! Handling edge cases and duplicates is where the real engineering happens. 🚀👨💻 #LeetCode #JavaScript #CodingLife #Algorithms #WebDevelopment #ProblemSolving #SoftwareEngineering #TechCommunity
To view or add a comment, sign in
-
-
Stop Writing Redux the Hard Way. I used to write 50+ lines of boilerplate just to manage a simple counter in Redux. Action types. Action creators. Switch statements. Immutable update logic. Then I discovered createSlice from Redux Toolkit — and everything changed. In under 15 lines, you get: Auto-generated action creators Auto-generated action types Immer-powered state mutations (yes, you can "mutate" state directly) A clean, readable reducer No more switch statements. No more ...state spread operators. No more separate action files. Redux Toolkit isn't just a convenience — it's the official, recommended way to write Redux in 2026. If you're still writing Redux the old way, you're working harder, not smarter. What's one tool that completely changed how you write code? Drop it below. 👇 #Redux #ReduxToolkit #JavaScript #React #WebDevelopment #Frontend #SoftwareEngineering #CodeSmarter #LearnToCode
To view or add a comment, sign in
-
-
𝗪𝗵𝗲𝗿𝗲 𝗱𝗼𝗲𝘀 𝘆𝗼𝘂𝗿 𝗰𝗼𝗱𝗲 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝗹𝗶𝘃𝗲? 🗺️ Hi everyone! I just published Part 3 of my JavaScript deep-dive series on Medium! After looking at the engine and hoisting, we’re now moving into the "geography" of our code: 𝗦𝗰𝗼𝗽𝗲 𝗮𝗻𝗱 𝘁𝗵𝗲 𝗦𝗰𝗼𝗽𝗲 𝗖𝗵𝗮𝗶𝗻. If you've ever been confused by a variable "leaking" out of a loop, or wondered why you can't access a variable inside a function, this one is for you. 𝗜𝗻 𝘁𝗵𝗶𝘀 𝗽𝗮𝗿𝘁, 𝗜 𝗰𝗼𝘃𝗲𝗿: • 𝗧𝗵𝗲 4 𝗠𝗮𝗶𝗻 𝗦𝗰𝗼𝗽𝗲𝘀: Global, Function, Block, and the often-ignored Module scope. • 𝗜𝗺𝗽𝗹𝗶𝗰𝗶𝘁 𝗚𝗹𝗼𝗯𝗮𝗹𝘀: Why "forgetting" to declare a variable can pollute your entire app. • 𝗧𝗵𝗲 𝗦𝗵𝗮𝗱𝗼𝘄𝗶𝗻𝗴 𝗘𝗳𝗳𝗲𝗰𝘁: What happens when inner and outer variables have the same name. • 𝗧𝗵𝗲 𝗦𝗰𝗼𝗽𝗲 𝗖𝗵𝗮𝗶𝗻: How the engine "climbs the ladder" to find your data. • 𝗦𝗲𝗰𝗿𝗲𝘁 𝗦𝗰𝗼𝗽𝗲𝘀: Exploring the hidden scopes of Parameters and Named Function Expressions. Mastering scope is the key to writing clean, bug-free, and memory-efficient code. Read the full article here : https://lnkd.in/dCyyNdMh 🔗 𝗡𝗲𝘅𝘁 𝘀𝘁𝗼𝗽 𝗼𝗻 𝘁𝗵𝗲 𝘁𝗼𝘂𝗿: The wild world of 𝗖𝗼𝗲𝗿𝗰𝗶𝗼𝗻. Stay tuned! #JavaScript #WebDevelopment #Scope #SoftwareEngineering #TechCommunity #Medium #ProgrammingTips
To view or add a comment, sign in
-
Day 40 of me reading random and basic but important coding topicsss..... Today I read about event bubbling...... Event Bubbling is the process where an event starts at the most specific element (the target) and flows upward through its ancestors like a bubble rising in water. * The Flow: <td> → <tr> → <table> → <body> → window * The Mechanism: Most events (click, keydown, etc.) bubble by default. When the event triggers on the child, the browser checks the parent for a handler, executes it, and moves up. Why does this exist? Two words: Event Delegation. Instead of attaching 100 separate event listeners to 100 rows in a table (which is memory-expensive), we attach one listener to the parent <table>. * Logic is simple -: I don't care which row was clicked, I just care that the table was clicked..... * Trick is that:- We use event.target inside the parent handler to see exactly which child element triggered the event. Now let's see it's usefullness first..... 1. Memory Efficiency: One listener vs. thousands. This is a massive win for application memory usage, especially in Single Page Applications (SPAs) with large lists or infinite scrolls. 2. Dynamic Content: If you add new items to a list via AJAX, you don't need to attach new listeners. The parent is already listening. 3. Browser Load: Less time spent during the mounting phase of your components because the browser registers fewer bindings. Now the important cons which we usually avoid..... 1. The stopPropagation() Trap: We often use event.stopPropagation() to prevent parent handlers from firing. Risk: This creates a "Dead Zone." Analytics tools that listen on the document level to track user clicks will suddenly go blind to that part of your app. 2. Not Everything Bubbles: Events like focus, blur, and load do not bubble. (We have to use focusin / focusout or capture phase for those). 3. Deep Nesting Complexity: If your DOM is incredibly deep, an event bubbling all the way to the top technically takes CPU time, though in modern engines, this cost is negligible compared to the memory savings of delegation. Keep Learning!!!! #JavaScript #WebPerformance #FrontendDev #EventBubbling #SoftwareArchitecture
To view or add a comment, sign in
-
-
🚀 Optimizing Array Manipulation: The Two-Pointer Strategy 💡 Yesterday, I tackled the "Move Zeroes" challenge on LeetCode using JavaScript! 👨💻 The mission? Move all 0s to the end of an array while preserving the relative order of non-zero elements—all without creating a copy of the array. 🚫📋 Initially, a common approach is to filter and join arrays, but that results in $O(n)$ space complexity. To keep the solution professional and memory-efficient, I implemented the Two-Pointer technique. 🎯 🧠 The Logic: Pointer A (Slow): 🐢 Tracks the position where the next non-zero element belongs. Pointer B (Fast): 🐇 Iterates through the entire array to find non-zero values. The Swap: ✨ Whenever Pointer B encounters a non-zero element, we swap the values and increment Pointer A. 📊 The Result: ✅ Time Complexity: $O(n)$ (Clean, single-pass efficiency) ✅ Space Complexity: $O(1)$ (Optimized in-place manipulation) Mastering these "in-place" constraints is a game-changer for writing scalable, production-ready code. It’s not just about solving the problem; it’s about solving it efficiently. 💪 #JavaScript #WebDevelopment #LeetCode #Algorithms #CodingInterview #SoftwareEngineering #ProblemSolving #100DaysOfCode
To view or add a comment, sign in
-
-
I tried implementing the internal working of forEach and map to better understand how they operate under the hood. Both are higher order functions because they accept another function as an argument. Internally, they iterate over the array (typically via a loop) and execute the callback for each element. forEach : Iterates through the array. Executes the provided callback on each element. Does not return a new array (returns undefined). Primarily used for logging map : Iterates through the array. Executes the callback on each element. Stores the callback’s return value in a new array. Returns the new transformed array. Does not mutate the original array. Rewriting these methods manually with a for loop really clarifies their behavioral difference : forEach is about execution, map is about transformation. #JavaScript #WebDevelopment #FunctionalProgramming #LearnInPublic #ChaiAurCode
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development