💛 Memoization in JavaScript — Make Your Functions Faster ⚡ Ever written a function that: 👉 Does heavy computation 👉 Gets called repeatedly 👉 Repeats the same work again? That’s wasted performance 😬 Memoization fixes this elegantly. ♦️ What is Memoization? Definition: Memoization is an optimization technique where we: 👉 Store results of expensive function calls 👉 Return the cached result when the same inputs occur again In simple terms: “If I’ve already solved this once, why solve it again?” ♦️ Simple Example Without Memoization function square(n) { console.log("Calculating..."); return n * n; } square(5); // Calculating... square(5); // Calculating... again 😑 Same input. Same output. Still recalculating ❌ With Memoization function memoizedSquare() { let cache = {}; return function (n) { if (cache[n]) { console.log("From cache"); return cache[n]; } console.log("Calculating..."); cache[n] = n * n; return cache[n]; }; } const square = memoizedSquare(); square(5); // Calculating... square(5); // From cache ✅ 🔥 Faster 🔥 Smarter 🔥 Efficient ♦️ Why It Works (Closures) The cache variable persists because of closures. So you can think of it as: Memoization = Closure + Cache Closures power many advanced JavaScript patterns. ♦️ Real-World Use Cases ✔️ Expensive computations ✔️ Recursive algorithms ✔️ Derived data calculations ✔️ Performance optimization in React ✔️ Reducing repeated logic calls ♦️ Classic Interview Example — Fibonacci Without Memoization function fib(n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } Time complexity: O(2ⁿ) 😱 With Memoization function memoFib() { let cache = {}; return function fib(n) { if (n in cache) return cache[n]; if (n <= 1) return n; cache[n] = fib(n - 1) + fib(n - 2); return cache[n]; }; } const fib = memoFib(); Now time complexity becomes O(n) ⚡ Massive improvement. ♦️ Generic Memoize Utility function memoize(fn) { const cache = {}; return function (...args) { const key = JSON.stringify(args); if (key in cache) return cache[key]; const result = fn.apply(this, args); cache[key] = result; return result; }; } const fastSquare = memoize(n => n * n); Reusable. Clean. Powerful. ♦️ Important Notes 1️⃣ Best for pure functions (same input → same output) 2️⃣ Be careful if function depends on: External state Randomness API calls 3️⃣ Trade-off: 👉 Faster execution 👉 More memory usage It’s a classic time vs space trade-off ⚖️ 🎯 Interview One-Liner Memoization is an optimization technique that stores results of expensive function calls and returns the cached result when the same inputs occur again, typically implemented using closures. If this helped, drop a 💛 or share 🔁 Next deep dive 👉 Prototypes and Prototypal Inheritance 😄 #JavaScript #JSInternals #LearnJavaScript #WebDevelopment #ProgrammingConcepts #WebDevJourney #BuildInPublic
JavaScript Memoization: Speed Up Functions with Caching
More Relevant Posts
-
⚡ Debounce vs Throttle — Deep JavaScript Insight Many developers know the definitions of debounce and throttle, but the real value comes from understanding why they exist and how they affect runtime behavior. Let’s break it down. --- 🔹 The Real Problem: Event Flooding Browser events like: • "scroll" • "resize" • "input" • "mousemove" can fire dozens or even hundreds of times per second. Example: If a user types "hello", the input event fires 5 times. Without optimization: h -> API call he -> API call hel -> API call hell -> API call hello -> API call This causes: ❌ Unnecessary API traffic ❌ Increased server load ❌ UI lag ❌ Wasted CPU cycles This is where event rate-control techniques come in. --- 1️⃣ Debouncing (Event Consolidation) Debouncing ensures the function executes only after the event stops firing for a specified delay. Conceptually: Event → Reset Timer → Reset Timer → Reset Timer → Execute Implementation: function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, args); }, delay); }; } Execution flow: User typing → timer resets User stops typing → delay completes Function executes once 📌 Best Use Cases • Search suggestions • Form validation • API calls while typing --- 2️⃣ Throttling (Rate Limiting) Throttle ensures a function runs only once within a fixed time window. Conceptually: Event → Execute → Ignore → Ignore → Execute Implementation: function throttle(fn, limit) { let lastCall = 0; return function (...args) { const now = Date.now(); if (now - lastCall >= limit) { lastCall = now; fn.apply(this, args); } }; } Execution flow: scroll event fires 100 times function runs only every 1000ms 📌 Best Use Cases • Scroll listeners • Infinite scroll • Window resize • Mouse tracking --- 🧠 Engineering Insight The key difference is execution strategy. Technique| Strategy Debounce| Execute after inactivity Throttle| Execute at controlled intervals Another perspective: Debounce → Reduce total executions Throttle → Control execution frequency --- 🚀 Real-World React Insight In React applications: • Debounce prevents unnecessary API calls in search components. • Throttle prevents heavy re-renders during scroll events. This is why libraries like lodash provide built-in implementations. --- 💡 Interview Tip If an interviewer asks: "How do you optimize event-heavy UI interactions?" Mention: ✔ Debouncing ✔ Throttling ✔ requestAnimationFrame (for animation events) --- Small techniques like these dramatically improve performance, scalability, and user experience. #javascript #reactjs #frontend #webperformance #codinginterview
To view or add a comment, sign in
-
🚀 Why the "+" Operator Works Differently in JavaScript In JavaScript, arithmetic operators like "+", "-", "*", "/", and "%" are used to perform mathematical operations. However, the "+" operator is special because it can perform two different tasks: 1️⃣ Arithmetic Addition 2️⃣ String Concatenation Let’s understand why this happens. --- 1️⃣ "+" as an Arithmetic Operator When both values are numbers, the "+" operator performs normal addition. Example let a = 10; let b = 5; console.log(a + b); // 15 Here JavaScript clearly sees two numbers, so it performs arithmetic addition. --- 2️⃣ "+" as a Concatenation Operator When one of the values is a string, JavaScript converts the other value to a string and joins them together. This is called string concatenation. Example let text = "Age: "; let age = 25; console.log(text + age); // Age: 25 Here JavaScript converts "25" into a string and joins it with ""Age: "". --- 3️⃣ Why Other Operators Don’t Concatenate Other arithmetic operators like "-", "*", "/", "%" only perform mathematical operations. They do not support string concatenation. Example: console.log("10" - 5); // 5 JavaScript converts ""10"" into a number and performs subtraction. Another example: console.log("10" * 2); // 20 Here ""10"" is converted into a number before multiplication. --- 4️⃣ When Does This Behavior Happen? This behavior happens because of type coercion in JavaScript. JavaScript automatically converts values depending on the operator being used. - If "+" sees a string, it converts everything to string and concatenates. - Other operators convert values to numbers and perform arithmetic operations. Example: console.log(5 + "5"); // "55" console.log(5 - "5"); // 0 --- ✅ Key Takeaway - "+" → Can perform addition and string concatenation - "-", "*", "/", "%" → Always perform numeric operations 💡 Because of JavaScript’s type coercion, the "+" operator behaves differently compared to other arithmetic operators. Understanding this concept helps you avoid unexpected results in JavaScript. #JavaScript #WebDevelopment #Programming #BackendDevelopment #LearnToCode
To view or add a comment, sign in
-
🚀 JavaScript Event Loop — Explained Through Real Projects Most developers say: “Event loop handles async operations.” But in real frontend projects, understanding the event loop directly impacts: ✅ API handling ✅ UI smoothness ✅ Performance optimization ✅ Debugging tricky state issues. Let me explain how it shows up in real-world applications 👇 1️⃣ API Calls Don’t Block Your UI When we use: • fetch • axios • async/await • Promises async function getEvents() { const res = await axios.get("/api/events"); setEvents(res.data); } What actually happens: • API call goes to Web APIs • JS continues executing • Response callback goes to Microtask Queue • Event Loop pushes it to Call Stack • React re-renders 🔥 That’s why your UI doesn’t freeze while fetching data. 2️⃣ React State Updates Are Async. Have you ever faced this? setData(newData); console.log(data); // old value Why? Because state updates are scheduled — not immediate. Understanding the event loop helps avoid: •Incorrect assumptions •Double renders •Race conditions •Stale state bugs 3️⃣ Interview Favorite Question. setTimeout(() => console.log("Timeout"), 0); Promise.resolve().then(() => console.log("Promise")); Output: Promise Timeout Reason: • Promises → Microtask Queue (higher priority) • setTimeout → Macrotask Queue • Event Loop clears microtasks first. This question alone tests if you really understand JavaScript. 4️⃣ Real Bug I Faced in Production In a dashboard project: • API updated state • Immediately after, filtering logic ran • It used old state value • Result → Incorrect UI data. Fix: •Functional state updates. •Move dependent logic into useEffect. Understanding the event loop saved hours of debugging. 5️⃣ Performance & UI Freezing Heavy synchronous code blocks the call stack: for(let i = 0; i < 1000000000; i++) {} UI freezes ❌ Real-world solutions: •Break tasks using setTimeout. •Use requestAnimationFrame. •Use Web Workers for heavy processing. 🎯 Final Thought : If you: •Work with APIs •Use async/await daily •Build dashboards •Optimize performance. You are already relying on the Event Loop every single day. 👉 “I use JavaScript” from 🔥 “I understand how JavaScript works under the hood”. #JavaScript #FrontendDeveloper #ReactJS #WebDevelopment #EventLoop #AsyncProgramming #SoftwareEngineering #TechInterview
To view or add a comment, sign in
-
🧬 Prototype, Prototype Chain & Prototypical Inheritance — Simplified This is why people say: 💡 “Everything in JavaScript is an object.” Let’s break it down clearly 👇 1️⃣ What is a Prototype? A prototype is an object that other objects inherit from. Every JS object has a hidden link to another object → its prototype. const user = { name: "Ravi" }; user.toString(); // Where did this come from? 👉 From Object.prototype JavaScript automatically links objects to prototypes. 2️⃣ Prototype Chain 🔗 When accessing a property, JS searches like this: Object → Prototype → Prototype’s Prototype → null Example: const arr = [1,2,3]; arr.push(4); push() comes from: 👉 Array.prototype And that inherits from: 👉 Object.prototype Chain: arr → Array.prototype → Object.prototype → null That lookup path = Prototype Chain 3️⃣ Prototypical Inheritance 🧬 When one object accesses another’s properties via the prototype chain, it’s called Prototypical Inheritance. JavaScript uses object-to-object inheritance (not classical like Java/C++). const animal = { eats: true }; const dog = Object.create(animal); dog.eats; // true Chain: dog → animal → Object.prototype → null 4️⃣ proto vs prototype (Most Confusing Part) 🔹 __proto__ • Exists on objects • Points to its prototype 🔹 prototype • Exists on functions • Used when creating objects with new function Person(name) { this.name = name; } const p1 = new Person("Ravi"); p1.__proto__ === Person.prototype 5️⃣ What Happens When We Use new? 🧠 function Car(model) { this.model = model; } const c1 = new Car("BMW"); Behind the scenes: Creates empty object {} Links it to Car.prototype Binds this Returns the object Chain: c1 → Car.prototype → Object.prototype → null 6️⃣ Is Everything Really an Object? ✔ Arrays ✔ Functions ✔ Dates Even functions can have properties: function test() {} test.custom = "Hello"; But 7 primitives are NOT objects: string, number, boolean, null, undefined, symbol, bigint Yet: "hello".toUpperCase(); JS temporarily wraps it in a String object (boxing). That’s why it feels like everything is an object. 7️⃣ Interview Must-Knows 🎯 • Prototype Chain? → Property lookup mechanism • proto vs prototype? → Object link vs function blueprint • How inheritance works? → Prototype linkage • If property not found? → JS climbs up chain until null 🧠 Mental Model Child asks parent for a property. If not found → asks grandparent. Until null. That’s the Prototype Chain. ⚡ One-Line Summary Prototype = Parent Prototype Chain = Lookup path Prototypical Inheritance = Object inheriting from object __proto__ = Link prototype = Blueprint Detailed Article: 👉 https://lnkd.in/gnYVf5t4 If this helped, drop a 💛 or share 🔁 #JavaScript #WebDevelopment #Frontend #Programming #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 JavaScript Event Loop in Action — Why setTimeout(0) Doesn't Run Immediately I recently experimented with a small JavaScript snippet to understand how blocking code interacts with timers and the event loop. Here is the code: console.log("Script start"); // Timer with 0ms setTimeout(() => { console.log("0ms timer executed"); }, 0); // Timer with 100ms setTimeout(() => { console.log("100ms timer executed"); }, 100); // Timer with 500ms setTimeout(() => { console.log("500ms timer executed"); }, 500); console.log("Starting heavy computation..."); // Blocking loop for (let i = 0; i < 100000000; i++) {} console.log("Heavy computation finished"); console.log("Script end"); 🔎 What we might expect Many developers assume that setTimeout(..., 0) will execute immediately. But that’s not how JavaScript works. ⚙️ Actual Execution Process 1️⃣ Script starts The synchronous code begins executing on the Call Stack. Script start 2️⃣ Timers are registered The setTimeout functions are handed over to the Web APIs environment. They start counting their timers in the background. 0ms timer 100ms timer 500ms timer But none of their callbacks execute yet. 3️⃣ Heavy synchronous computation starts The large for loop runs on the main thread and blocks it. Starting heavy computation... During this time: JavaScript cannot process any other tasks The call stack remains busy Even if timers expire, their callbacks must wait 4️⃣ Timers expire while the loop is running While the loop is still executing: 0ms timer expires 100ms timer expires Possibly even the 500ms timer But they cannot run yet because the call stack is still occupied. 5️⃣ Loop finishes Heavy computation finished Script end Now the Call Stack becomes empty. 6️⃣ Event Loop starts processing queued callbacks The Event Loop checks the Callback Queue and begins executing timers in order. 0ms timer executed 100ms timer executed 500ms timer executed 🧠 Key Takeaways ✔ JavaScript is single-threaded ✔ Long synchronous tasks block the event loop ✔ setTimeout(0) does not run immediately ✔ Timers only execute after the call stack is empty Understanding this behavior is essential for writing efficient asynchronous JavaScript and avoiding performance issues caused by blocking code. Next on my learning journey: exploring microtasks vs macrotasks and how Promises interact with the event loop. Sarthak Sharma Devendra Dhote #JavaScript #WebDevelopment #EventLoop #AsyncProgramming #FrontendDevelopment
To view or add a comment, sign in
-
Array in JavaScript – 5 Deep Points (Simple words, but senior-level understanding) 1. Array is actually an object let arr = [10, 20, 30]; console.log(typeof arr); // object Array is not a special primitive structure. It is an object with numeric keys and a length property. JS engines optimize arrays differently from normal objects. If you use them in an unusual way, the engine can de-optimize and performance drops. Senior thinking: Understand how the engine treats arrays internally, not just syntax. 2. Dense vs Sparse Arrays (Performance Impact) let arr = [1, 2, 3]; arr[50] = 100; Now length becomes 51. You created empty slots between indexes. This is called a sparse (holey) array. Dense arrays are optimized and fast. Sparse arrays lose optimization and become slower. Senior mindset: Never randomly jump indexes in performance-critical systems. 3. Shallow Copy Trap (Reference Problem) let arr1 = [{ name: "Ali" }]; let arr2 = [...arr1]; arr2[0].name = "Ahmed"; arr1 also changes. Because spread makes a shallow copy. The object inside still shares the same memory reference. This causes real production bugs in React, Node APIs, and shared state systems. Deep understanding: Copying array does not mean copying nested objects. 4. Mutation vs Predictability let arr = [3, 1, 2]; arr.sort(); sort() mutates the original array. If this array is shared across functions, unexpected behavior happens. Safer approach: let sorted = [...arr].sort((a, b) => a - b); Senior engineers avoid mutating shared data to prevent side effects. 5. Arrays are Reference Types (Memory Behavior) let a = [1, 2, 3]; let b = a; b.push(4); Now a is also changed. Because arrays store reference, not value. Deep concept: Understanding reference vs value is critical in backend systems, state management, and async code. These 5 points are where interviews shift from junior to senior discussion. Syntax is basic. Memory, optimization, mutation, and engine behavior — that’s where depth starts.
To view or add a comment, sign in
-
Day 23/30 – Implement Array.groupBy() in JavaScript Challendge 🗂️ | Build _.groupBy from Scratch 📌 Problem Enhance all arrays so you can call: array.groupBy(fn) Rules: fn(arr[i]) returns a string key Result should be an object Each key maps to an array of items that generated that key Preserve original order inside grouped arrays Do NOT use Lodash 🧠 Example array = [ {"id":"1"}, {"id":"1"}, {"id":"2"} ]; fn = function (item) { return item.id; }; Output: { "1": [{"id":"1"}, {"id":"1"}], "2": [{"id":"2"}] } 💡 JavaScript Solution Array.prototype.groupBy = function(fn) { const result = {}; for (let i = 0; i < this.length; i++) { const key = fn(this[i]); if (!result[key]) { result[key] = []; } result[key].push(this[i]); } return result; }; 🔎 Why This Works We iterate through the array Generate a key using fn If the key doesn’t exist → initialize it as [] Push the item into the corresponding group Time Complexity: O(n) Space Complexity: O(n) ⚠️ Production Note Like Day 22 — modifying Array.prototype is powerful but usually avoided in production environments to prevent conflicts. But for: Interviews Understanding JS internals Building utility libraries This is 🔥 essential knowledge. 🔥 What This Concept Is Used For ⚡ Grouping users by role ⚡ Organizing products by category ⚡ Aggregating logs by date ⚡ Data preprocessing for analytics Demon 😎 — by Day 23 you’re basically building your own mini Lodash. Want Day 24 next?
To view or add a comment, sign in
-
-
🚀 Day 27/30 – Compact Object in JavaScript 🧹 | Remove Falsy Values Recursively Given an object or array obj, return a compact object. ✅ What is a Compact Object? It’s the same structure as the original — but with all keys containing falsy values removed. 🔎 Falsy Values in JavaScript: false 0 "" (empty string) null undefined NaN ⚠️ This removal applies: To the main object To nested objects To nested arrays You may assume: obj is valid JSON (output of JSON.parse) Arrays are treated as objects (indices are keys) 🧠 Example 1 obj = {"a": null, "b": [false, 1]} Output: {"b": [1]} 🧠 Example 2 obj = { "a": 0, "b": { "c": false, "d": 5 } } Output: { "b": { "d": 5 } } 💡 JavaScript Solution (Recursive) var compactObject = function(obj) { if (Array.isArray(obj)) { const result = []; for (let item of obj) { const compacted = compactObject(item); if (Boolean(compacted)) { result.push(compacted); } } return result; } else if (obj !== null && typeof obj === "object") { const result = {}; for (let key in obj) { const compacted = compactObject(obj[key]); if (Boolean(compacted)) { result[key] = compacted; } } return result; } return obj; }; 🔎 Why This Works Recursively traverse structure If array → build new filtered array If object → build new filtered object Only keep values where Boolean(value) === true Preserves structure while removing falsy values Time Complexity: O(n) Space Complexity: O(n) (n = total nested elements) 🧠 What This Teaches ✅ Recursive traversal ✅ Object vs Array handling ✅ Deep data transformation ✅ JSON structure processing ✅ Real-world data cleaning logic ⚡ Real-World Use Cases Cleaning API payloads Removing empty form fields Optimizing database writes Sanitizing user input Preprocessing configuration files #JavaScript #30DaysOfJavaScript #CodingChallenge #Recursion #DataStructures #FrontendDevelopment #WebDevelopment #SoftwareEngineering #CleanCode #LearnToCode #Programming #InterviewPrep #ProblemSolving #JSDeveloper #100DaysOfCode JavaScript remove falsy values Compact object JavaScript Remove null values from object JS Recursive object cleaning JS Deep object traversal JavaScript JSON data cleaning JavaScript JavaScript interview question recursion Remove empty keys from object JS
To view or add a comment, sign in
-
-
𝐌𝐚𝐬𝐭𝐞𝐫𝐢𝐧𝐠 𝐂𝐨𝐦𝐩𝐥𝐞𝐱 𝐀𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐲 𝐢𝐧 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐰𝐢𝐭𝐡 𝐑𝐱𝐉𝐒 𝐚𝐧𝐝 𝐭𝐡𝐞 𝐑𝐞𝐚𝐜𝐭𝐢𝐯𝐞 𝐏𝐚𝐫𝐚𝐝𝐢𝐠𝐦 🔗 Feeling overwhelmed by messy, nested Promise chains, or struggling to manage state across multiple, simultaneous asynchronous events like mouse clicks, HTTP requests, and WebSocket messages? It's time to upgrade your developer toolkit with RxJS (Reactive Extensions for JavaScript). RxJS is more than just a library; it's a doorway into 𝐑𝐞𝐚𝐜𝐭𝐢𝐯𝐞 𝐏𝐫𝐨𝐠𝐫𝐚𝐦𝐦𝐢𝐧𝐠, a powerful paradigm that allows you to handle asynchronous data streams over time in a declarative, readable, and highly efficient way. Think of it as the ultimate power-up for your frontend (Angular, React, Vue) and backend (Node.js) development. 𝐓𝐡𝐞 𝐑𝐞𝐚𝐜𝐭𝐢𝐯𝐞 𝐏𝐢𝐩𝐞𝐥𝐢𝐧𝐞 𝐁𝐫𝐞𝐚𝐤𝐝𝐨𝐰𝐧 To make these abstract concepts tangible, I’ve designed this modern isometric infographic to illustrate how data flows through an RxJS architecture. Let’s break it down: 1️⃣ 𝐈𝐍𝐏𝐔𝐓 𝐒𝐎𝐔𝐑𝐂𝐄𝐒 (𝐎𝐛𝐬𝐞𝐫𝐯𝐚𝐛𝐥𝐞𝐬): The pipeline starts with any event that occurs over time. These are your 'sources' or Observables. • A user clicks a button (User Clicks). • A sensor sends new data (HTTP Request). • A chat message arrives (WebSocket Event). These are all Streams of data that are emitted asynchronously. 2️⃣ 𝐓𝐇𝐄 𝐎𝐏𝐄𝐑𝐀𝐓𝐎𝐑 𝐓𝐎𝐎𝐋𝐁𝐎𝐗 (𝐏𝐢𝐩𝐞𝐚𝐛𝐥𝐞 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬):This is where the true magic of RxJS lies. The pipe() function allows you to compose complex logic easily using powerful operator functions. In the central pipeline, we illustrate: • filter(x => x > 10): Only lets the important data through. • map(x => x * 2): Transforms each piece of data (marbles) into something else. • debounceTime(300ms): Groups rapid bursts of events into a single, clean emission (perfect for search bars!). • switchMap(id => getDetails(id)): The ultimate 'canceling' operator—handy for switching to the newest request and discarding the old, stale ones. 3️⃣ 𝐎𝐔𝐓𝐏𝐔𝐓 & 𝐂𝐎𝐍𝐒𝐔𝐌𝐄𝐑 (𝐓𝐡𝐞 𝐒𝐮𝐛𝐬𝐜𝐫𝐢𝐛𝐞𝐫): The data completes its journey when a Subscriber listens to the finalized, clean stream and reacts to it. The UI updates (Update UI). Data is saved to a database (Save to DB). Errors or status events are logged (Logging). By adopting RxJS, you get: ✅ Clean, declarative code: Describe what should happen, not how to manage state manually. ✅ Powerful composition: Easily combine multiple, competing streams (e.g., combineLatest). - Efficient resource management For those already using RxJS, what's your go-to operator or the most complex async problem you've solved with it? Let's discuss in the comments! 👇 #RxJS #JavaScript #Angular #React #NodeJS #WebDevelopment #ReactiveProgramming #ProgrammingTips #Infographics #AsyncProgramming #CodingSuperpowers
To view or add a comment, sign in
-
-
💡 JavaScript Tip: 3 Advanced NaN Tricks Most Developers Don’t Know NaN stands for "Not-a-Number". It represents the result of an invalid numeric operation in JavaScript. Even though its name suggests otherwise, JavaScript still treats NaN as a number type. Here are 3 advanced NaN behaviors that many developers don’t know: -------------------------------------------------- 1️⃣ Object.is() Can Correctly Compare NaN Normally, NaN is not equal to itself: NaN === NaN // false However, Object.is() can correctly compare it: Object.is(NaN, NaN) // true Example: console.log(Object.is(NaN, NaN)); // true This is useful when you need precise value comparisons. -------------------------------------------------- 2️⃣ NaN Propagates Through Calculations Once NaN appears in a calculation, it spreads through the entire result. Example: let value = NaN; console.log(value + 5); // NaN console.log(value * 10); // NaN console.log(Math.sqrt(value)); // NaN This means a single invalid number can break an entire calculation chain. Best practice: if (Number.isNaN(value)) { console.error("Invalid number detected"); } -------------------------------------------------- 3️⃣ NaN in Arrays: includes() vs indexOf() Arrays treat NaN differently depending on the method used. Example: const arr = [NaN, 1, 2]; console.log(arr.includes(NaN)); // true console.log(arr.indexOf(NaN)); // -1 Why? - indexOf() uses strict equality (===) - includes() uses SameValueZero comparison, which correctly handles NaN. -------------------------------------------------- ✅ Best Ways to Detect NaN Use these methods: Number.isNaN(value) Object.is(value, NaN) Avoid using isNaN() because it converts values to numbers first, which can cause confusing results. -------------------------------------------------- Small JavaScript details like this can help prevent hidden bugs in real-world applications. #JavaScript #WebDevelopment #Frontend #Programming #SoftwareEngineering
To view or add a comment, sign in
-
Explore related topics
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