Akshat Uppal’s Post

🔥 JS Loops Demystified: for vs for…in vs for…of If you’ve ever wondered which loop to use in JavaScript, you’re not alone. Choosing the wrong one can cause subtle bugs! Here’s a quick guide: 1️⃣ Classic for loop – The old reliable const arr = [10, 20, 30]; for (let i = 0; i < arr.length; i++) {  console.log(arr[i]); } Use when you need index access, or want full control over iteration. 2️⃣ for…in loop – Iterate over keys (property names) const arr = [10, 20, 30]; for (let key in arr) {  console.log(key); // 0, 1, 2 } Works on objects too. ⚠️ Can be dangerous for arrays — also loops over inherited properties. 3️⃣ for…of loop – Iterate over values const arr = [10, 20, 30]; for (let value of arr) {  console.log(value); // 10, 20, 30 } Perfect for arrays, strings, maps, sets. Safe, clean, and readable. 💡 Pro tip: Use for when you need the index. Use for…of for values (most array iterations). Avoid for…in on arrays — reserve it for objects. Small choice, huge impact on readability and bug prevention. #JavaScript #CodingTips #WebDevelopment #FrontendDev #CleanCode #JSProTips #ForOfVsForIn

To view or add a comment, sign in

Explore content categories