Nidhi Jagga’s Post

Stop writing `for (let i = 0...)` for everything! 🛑🔄 JavaScript gives us a dozen ways to loop over data. Using the right one makes your code cleaner, more readable, and often less buggy. Here is the cheat sheet for choosing the right tool: 1️⃣𝐓𝐡𝐞 𝐂𝐥𝐚𝐬𝐬𝐢𝐜𝐬 (`for`, `while`) 🏛️ • 𝐔𝐬𝐞 𝐰𝐡𝐞𝐧: You need absolute control (like skipping indexes or breaking early). • 𝐃𝐨𝐰𝐧𝐬𝐢𝐝𝐞: Verbose and easier to mess up the syntax. 2️⃣𝐓𝐡𝐞 𝐌𝐨𝐝𝐞𝐫𝐧 𝐒𝐭𝐚𝐧𝐝𝐚𝐫𝐝 (`for...of`) ✨ • 𝐔𝐬𝐞 𝐰𝐡𝐞𝐧: You just want to read the 𝐯𝐚𝐥𝐮𝐞𝐬 of an array. • 𝐏𝐫𝐨 𝐓𝐢𝐩: Avoid `for...in` for arrays (it gives you indices/keys, not values!). 3️⃣𝐓𝐡𝐞 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐚𝐥 𝐏𝐨𝐰𝐞𝐫𝐡𝐨𝐮𝐬𝐞 (`map`, `filter`) 🛠️ • 𝐔𝐬𝐞 𝐰𝐡𝐞𝐧: You want to 𝑡𝑟𝑎𝑛𝑠𝑓𝑜𝑟𝑚 data or 𝑠𝑒𝑙𝑒𝑐𝑡 specific items without mutating the original array. • 𝐖𝐡𝐲: It's "Declarative"—you tell JS 𝑤ℎ𝑎𝑡 you want, not ℎ𝑜𝑤 to loop. 4️⃣𝐓𝐡𝐞 𝐒𝐰𝐢𝐬𝐬 𝐀𝐫𝐦𝐲 𝐊𝐧𝐢𝐟𝐞 (`reduce`) 🧠 • 𝐔𝐬𝐞 𝐰𝐡𝐞𝐧: You need to boil an array down to a single value (like a sum, an object, or a totally new structure). 5️⃣𝐓𝐡𝐞 𝐀𝐬𝐲𝐧𝐜 𝐇𝐞𝐫𝐨 (`for await...of`) ⏳ • 𝐔𝐬𝐞 𝐰𝐡𝐞𝐧: You are looping over promises and need them to resolve one by one. Check out the visual guide below! 👇 Which array method do you overuse? (I’m guilty of using `map` when I should use `forEach` 😅) #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #Frontend #ES6

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

Great insights, Nidhi! Your breakdown of JavaScript looping methods is incredibly helpful and will definitely encourage better coding practices. Thanks for sharing such a valuable resource!

To view or add a comment, sign in

Explore content categories