JavaScript Loops: for...in vs for...of

Day 27/50 – JavaScript Interview Question? Question: What is the difference between for...in and for...of loops? Simple Answer: for...in iterates over enumerable property keys (strings) of an object, including inherited properties. for...of iterates over iterable values (like arrays, strings, Maps, Sets) and doesn't work with plain objects. 🧠 Why it matters in real projects: Using the wrong loop causes bugs. for...in on arrays gives you indices as strings (not ideal), while for...of gives values directly. For objects, use Object.keys/values/entries with for...of instead of for...in. 💡 One common mistake: Using for...in on arrays and expecting numeric indices or values, but getting string keys. Also, for...in can iterate over inherited properties from the prototype chain. 📌 Bonus: const arr = ['a', 'b', 'c']; // for...in - keys (indices as strings) for (let key in arr) { console.log(key); // "0", "1", "2" (strings!) console.log(typeof key); // "string" } // for...of - values for (let value of arr) { console.log(value); // "a", "b", "c" } // Object iteration const person = { name: 'Alice', age: 30 }; // for...in works on objects for (let key in person) { console.log(key, person[key]); // "name Alice", "age 30" } // for...of doesn't work on plain objects for (let value of person) {} // ✗ TypeError! // Better object iteration: for (let [key, value] of Object.entries(person)) { console.log(key, value); // ✓ Best practice } // Prototype pollution issue with for...in Array.prototype.custom = 'surprise'; for (let key in arr) { console.log(key); // "0", "1", "2", "custom" - Oops! } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #Loops #ES6

To view or add a comment, sign in

Explore content categories