Improve JavaScript Code with array.toSorted() and structuredClone()

Read down below for the full Explination : 1. array.sort() → array.toSorted() ❌ array.sort() Mutates (changes) the original array Can cause hidden bugs in React state Not immutable-friendly ✅ array.toSorted() Returns a new sorted array Keeps original array untouched Safer for modern functional patterns 👉 In React, immutability = predictable UI. 2. JSON.parse(JSON.stringify(obj)) → structuredClone(obj) ❌ JSON trick Breaks Dates Breaks Maps/Sets Removes functions Fails with circular references ✅ structuredClone() Deep clones properly Supports complex data types Cleaner and faster 👉 Stop using the “hack”. Use the real API. 3. Promise.all() → Promise.allSettled() ❌ Promise.all() Fails immediately if ONE promise fails You lose other results ✅ Promise.allSettled() Waits for ALL promises Returns success + failure results Perfect for dashboards, multiple API calls 👉 More resilient apps. 4. indexOf() → findIndex() ❌ indexOf(value) Only works for exact matches Doesn’t work well with objects ✅ findIndex(callback) Can search with logic Works with objects More flexible Example: users.findIndex(user => user.id === 10) 👉 Cleaner + more expressive. #JavaScript #ModernJavaScript #WebDevelopment #FrontendDevelopment #CleanCode #ReactJS #SoftwareEngineering

  • graphical user interface, text, application, chat or text message

To view or add a comment, sign in

Explore content categories