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
JavaScript Loops: for...in vs for...of
More Relevant Posts
-
Day 28/50 – JavaScript Interview Question? Question: What is destructuring in JavaScript? Simple Answer: Destructuring is a syntax that unpacks values from arrays or properties from objects into distinct variables. It provides a concise way to extract multiple values in a single statement. 🧠 Why it matters in real projects: Destructuring makes code cleaner and more readable, especially with React props, API responses, and function parameters. It's ubiquitous in modern JavaScript and reduces boilerplate code significantly. 💡 One common mistake: Trying to destructure null or undefined, which throws an error. Always provide default values or check for existence when destructuring data from APIs or external sources. 📌 Bonus: // Array destructuring const [first, second, ...rest] = [1, 2, 3, 4, 5]; console.log(first); // 1 console.log(second); // 2 console.log(rest); // [3, 4, 5] // Object destructuring const user = { name: 'Alice', age: 30, city: 'NYC' }; const { name, age } = user; console.log(name); // "Alice" // Renaming variables const { name: userName, age: userAge } = user; // Default values (prevents undefined) const { country = 'USA' } = user; console.log(country); // "USA" // Nested destructuring const data = { user: { profile: { email: 'a@b.com' } } }; const { user: { profile: { email } } } = data; // React props destructuring function UserCard({ name, age, onDelete }) { return <div>{name}, {age}</div>; } // Function parameters function displayUser({ name, age = 18 }) { console.log(`${name} is ${age}`); } // Common mistake - destructuring undefined const { x } = null; // ✗ TypeError! const { x } = null || {}; // ✓ Safe with fallback #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #ES6 #Destructuring #WebDev #InterviewPrep
To view or add a comment, sign in
-
🤔 Ever had two libraries both add a property called "id" to the same object… and one silently overwrites the other? That’s exactly the kind of “name collision” Symbol was made to avoid. 🧠 JavaScript interview question What is a Symbol in JavaScript, and why would you use it? ✅ Short answer A Symbol is a primitive used as an object property key that’s guaranteed to be unique. It helps you create collision-free / “hidden-ish” properties without worrying about string keys clashing. 🔍 Key things to remember Unique by default: every Symbol() call returns a different value Not auto-enumerated: symbol keys don’t show up in for...in or Object.keys() Global registry exists: Symbol.for("key") lets you reuse the same symbol across files/modules Well-known symbols: built-ins like Symbol.iterator can change how objects behave 💻 Example 1: Symbols are always unique const s1 = Symbol("id"); const s2 = Symbol("id"); console.log(s1 === s2); // false 💻 Example 2: “Hidden-ish” object property (not in normal enumeration) const secret = Symbol("secretId"); const user = { name: "Alice", [secret]: 12345, // Symbol as property key }; console.log(user.name); // "Alice" console.log(user[secret]); // 12345 💻 Example 3: Global registry (shared symbol) const uid1 = Symbol.for("uid"); const uid2 = Symbol.for("uid"); console.log(uid1 === uid2); // true console.log(Symbol.keyFor(uid1)); // "uid" ⚠️ Common misconception Symbols are NOT “private fields.” They’re just harder to access by accident, if someone has the symbol reference (or calls Object.getOwnPropertySymbols(obj)), they can still read it. #JavaScript #Frontend #WebDevelopment #InterviewPrep #Programming #ReactJS #TypeScript
To view or add a comment, sign in
-
⚡ Top 14 JavaScript Array Methods Every Developer Should Know If you’re learning JavaScript or preparing for frontend interviews, array methods are used everywhere. Understanding them well can make your code cleaner, shorter, and more efficient. Here are 14 essential JavaScript array methods worth mastering 👇 📌 Core Array Operations .push() ↳ Adds one or more elements to the end of an array. .pop() ↳ Removes the last element from an array. .shift() ↳ Removes the first element from an array. .unshift() ↳ Adds one or more elements to the beginning of an array. 📌 Array Modification & Extraction .slice() ↳ Extracts a portion of an array into a new array. .splice() ↳ Adds, removes, or replaces elements inside an array. 📌 Transformation & Iteration .map() ↳ Creates a new array by transforming each element. .filter() ↳ Creates a new array with elements that match a condition. .reduce() ↳ Reduces the array to a single value using a function. .forEach() ↳ Executes a function on each element (no return value). 📌 Searching & Checking .find() ↳ Returns the first element that matches a condition. .findIndex() ↳ Returns the index of the first matching element. .includes() ↳ Checks if an array contains a specific value. 📌 Sorting .sort() ↳ Sorts the elements of an array in place. 💡 Pro tip: In real-world frontend development, methods like map, filter, and reduce are used heavily in frameworks like React. If this helped, save it for quick revision. #JavaScript #FrontendDevelopment #WebDevelopment #Coding #Programming #ReactJS #TechLearning
To view or add a comment, sign in
-
⚡ JavaScript Interview Question Day 1: What is the difference between: null vs undefined ? Quick explanation 👇 undefined ------------- • Variable declared but not assigned Example: let a; console.log(a) // undefined null ------ • Intentional absence of value Example: let user = null 💡 Tip: undefined → system assigned null → developer assigned #javascript #frontend #codinginterview #programming #interview #react #angular #performance #UI
To view or add a comment, sign in
-
🚀 Understanding Closures in JavaScript Closures are one of the most powerful concepts in JavaScript, and they often appear in interviews for frontend or full-stack developer roles. 📌 What is a Closure? A closure happens when a function remembers the variables from its outer scope even after the outer function has finished executing. In simple words: A function can access variables from its parent function even after the parent function is done running. 💻 Example: function outerFunction() { let count = 0; function innerFunction() { count++; console.log(count); } return innerFunction; } const counter = outerFunction(); counter(); // 1 counter(); // 2 counter(); // 3 Here, innerFunction forms a closure because it remembers the count variable from outerFunction. ⚡ Why Closures are Useful Closures are commonly used for: • Data privacy • Creating private variables • Function factories • Event handlers • Callbacks and asynchronous code 📦 Real-world example: Closures are used in many libraries and frameworks like React for handling state and callbacks. 🧠 Key Takeaway A closure allows a function to retain access to its lexical scope, even when the function is executed outside that scope. If you’re learning JavaScript deeply, understanding closures will unlock many advanced patterns. 💬 What JavaScript concept confused you the most when you first learned it? #javascript #webdevelopment #frontenddevelopment #coding #programming #reactjs #100DaysOfCode
To view or add a comment, sign in
-
-
🧠 Understanding JavaScript Closures Many developers get confused about Closures in JavaScript. Let’s understand it in a simple way 👇 👉 What is Closure? A closure happens when an inner function remembers variables from its outer function — even after the outer function has finished executing. 💡 Simple Line: A function remembers where it was created. 🔎 Example: function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 Even though outer() finished, inner() still remembers count. That memory is called Closure 🔐 🎯 Why Closures are Important? ✅ Data hiding (private variables) ✅ Counters ✅ setTimeout & async logic ✅ Used in React Hooks ✅ Functional programming pattern 🏆 Interview Definition: A closure happens when an inner function remembers variables from its outer function — even after the outer function has finished executing. If you're preparing for frontend interviews, Closures is a MUST-know concept 💪 💬 Question for you: Where have you used closures in real projects? #JavaScript #FrontendDevelopment #ReactJS #WebDevelopment #InterviewPreparation
To view or add a comment, sign in
-
-
5 JavaScript Array methods every developer must know 👇 1️⃣ map() Transform every element in an array const doubled = [1,2,3].map(x => x * 2) // [2, 4, 6] ✅ 2️⃣ filter() Remove elements you don't need const evens = [1,2,3,4].filter(x => x % 2 === 0) // [2, 4] ✅ 3️⃣ reduce() Combine all elements into one value const sum = [1,2,3].reduce((acc, x) => acc + x, 0) // 6 ✅ 4️⃣ find() Get first matching element const user = users.find(u => u.id === 1) // { id: 1, name: "Shivesh" } ✅ 5️⃣ some() & every() Check if condition is true [1,2,3].some(x => x > 2) // true [1,2,3].every(x => x > 0) // true ✅ Save this for your next interview! 🔖 Which one do you use the most? Comment below! 👇 #JavaScript #Frontend #ReactJS #WebDevelopment #Programming #100DaysOfCode
To view or add a comment, sign in
-
-
𝐂𝐨𝐦𝐩𝐥𝐞𝐭𝐞 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐐𝐮𝐞𝐬𝐭𝐢𝐨𝐧𝐬 (𝟐𝟎𝟐𝟔 𝐔𝐩𝐝𝐚𝐭𝐞𝐝 𝐆𝐮𝐢𝐝𝐞) 🔥 Preparing for JavaScript interviews in 2026? I’ve compiled a practical guide covering beginner to advanced concepts with examples and explanations. This guide includes key topics like: ✔ JavaScript fundamentals ✔ var vs let vs const ✔ Hoisting and scope ✔ Closures and lexical scope ✔ Event loop and asynchronous behavior ✔ Promises and async/await ✔ Debouncing and throttling ✔ Memory management and performance optimization ✔ Node.js related interview concepts JavaScript remains one of the most important languages for modern web development, powering interactive applications in browsers and server environments like Node.js. If you're preparing for interviews or strengthening your fundamentals, this resource will help you revise core concepts with real examples. 🔗 Read the full guide: https://lnkd.in/g7GnWuYE 🔁 Repost to support the community 👉 Follow Tapas Sahoo for more related content 🙏 What’s the most challenging JavaScript interview question you’ve faced? 👇 #JavaScript #WebDevelopment #NodeJS #FrontendDevelopment #CodingInterview #SoftwareEngineering #DeveloperLife #TechCareers #Programming #FullStackDeveloper
To view or add a comment, sign in
-
🚨 Most Developers Get These JavaScript Questions Wrong! JavaScript looks easy… until interviewers ask these. Let’s test your fundamentals 👇 🧠 Question 1 console.log(a); var a = 10; A) 10 B) undefined C) ReferenceError --- ⚡ Question 2 console.log(a); let a = 10; A) undefined B) 10 C) ReferenceError --- 🔥 Question 3 hello(); var hello = function(){ console.log("Hi"); } A) Hi B) undefined C) TypeError --- 💡 Question 4 function test(){ console.log(a); var a = 10; } test(); A) 10 B) undefined C) ReferenceError --- 🚀 Question 5 var a = 5; (function(){ console.log(a); var a = 10; })(); A) 5 B) 10 C) undefined --- These questions test your understanding of: ✨ Hoisting ✨ Scope ✨ Function Expressions ✨ Temporal Dead Zone ✨ IIFE 💬 Drop your answers (1–5) in the comments. Let’s see how many developers get all of them right! #javascript #webdevelopment #frontenddeveloper #webdeveloper #programming #softwaredeveloper #coding #developercommunity #devcommunity #learninpublic #100daysofcode #tech #codinginterview #softwareengineering
To view or add a comment, sign in
-
🚀 **JavaScript: var vs let vs const (Explained Clearly)** If you're learning JavaScript or preparing for interviews, this is a concept you MUST understand 👇 --- ## 🔹 var ```js var name = "Ali"; var name = "Ahmed"; // ✅ Allowed name = "John"; // ✅ Allowed ``` ✔ Function scoped ✔ Can be redeclared ✔ Can be updated ⚠ Problem: Can cause unexpected bugs due to scope issues. --- ## 🔹 let ```js let name = "Ali"; let name = "Ahmed"; // ❌ Error name = "John"; // ✅ Allowed ``` ✔ Block scoped ❌ Cannot be redeclared in same scope ✔ Can be updated ✅ Use when the value needs to change. --- ## 🔹 const ```js const name = "Ali"; name = "Ahmed"; // ❌ Error ``` ✔ Block scoped ❌ Cannot be redeclared ❌ Cannot be reassigned ✅ Use by default in modern JavaScript. --- ## 💡 Best Practice (Modern JS Rule) 👉 Use **const** by default 👉 Use **let** when value needs to change 👉 Avoid **var** --- ### 🎯 Interview Tip Most scope-related bugs happen because of `var`. Understanding block scope vs function scope makes you a stronger developer. --- https://lnkd.in/gzGAbU8A 💬 Quick question: Do you still use `var` in your projects? #JavaScript #FrontendDevelopment #WebDevelopment #Programming #CodingInterview #JSConcepts #SoftwareEngineering #FullStackDeveloper #LearnToCode #DeveloperTips #100DaysOfCode #TechCommunity
To view or add a comment, sign in
-
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