Day 49/50 – JavaScript Interview Question? Question: What is the difference between stopPropagation(), stopImmediatePropagation(), and preventDefault()? Simple Answer: stopPropagation() prevents event from bubbling/capturing to other elements. stopImmediatePropagation() also prevents other handlers on current element. preventDefault() cancels default browser action but doesn't stop propagation. 🧠 Why it matters in real projects: These control event behavior in complex UIs with nested elements. Misusing them causes bugs like forms not submitting, clicks triggering parent handlers, or custom behavior failing. Critical for proper event handling. 💡 One common mistake: Using stopPropagation() everywhere "to be safe" breaks event delegation patterns. Also confusing preventDefault() with stopping propagation—they serve different purposes. 📌 Bonus: // HTML: <div id="outer"><button id="inner">Click</button></div> const outer = document.getElementById('outer'); const inner = document.getElementById('inner'); // stopPropagation() - stops event flow inner.addEventListener('click', (e) => { console.log('Inner'); e.stopPropagation(); // Stops here! }); outer.addEventListener('click', () => { console.log('Outer'); // Won't fire }); // stopImmediatePropagation() - stops all handlers inner.addEventListener('click', (e) => { console.log('Handler 1'); e.stopImmediatePropagation(); }); inner.addEventListener('click', () => { console.log('Handler 2'); // Won't fire! }); // preventDefault() - cancels default action const link = document.querySelector('a'); link.addEventListener('click', (e) => { e.preventDefault(); // Link won't navigate // Event still propagates to parent! }); const form = document.querySelector('form'); form.addEventListener('submit', (e) => { e.preventDefault(); // Form won't submit handleAjaxSubmit(new FormData(form)); }); // Practical: Modal overlay modal.addEventListener('click', (e) => { e.stopPropagation(); // Clicks on modal don't close it }); overlay.addEventListener('click', () => { closeModal(); // Clicks on overlay close it }); // Best practice: Don't break delegation document.querySelector('.list').addEventListener('click', (e) => { if (e.target.matches('.item')) { // Don't use stopPropagation here! handleItemClick(e.target); } }); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #Events #EventPropagation #WebDev #DOM
JavaScript Event Propagation: stopPropagation(), stopImmediatePropagation(), preventDefault()
More Relevant Posts
-
*🚀 JavaScript Closures 🔥* Closures are a fundamental concept in JavaScript, often asked in interviews. A closure is when a function remembers variables from its outer scope, even after the outer function has finished executing. *🔹 1. Basic Example of Closure* function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 The inner function remembers the `count` variable even after the outer function has finished executing. *🔹 2. Why Closures Work* Because of lexical scope, inner functions can access their own variables, parent function variables, and global variables, even after the parent function ends. *🔹 3. Closures for Data Privacy (Very Important)* Closures help protect data. function createBankAccount() { let balance = 1000; return function(amount) { balance += amount; console.log(balance); } } const account = createBankAccount(); account(500); // 1500 account(200); // 1700 The `balance` variable is private and cannot be accessed directly. *🔹 4. Real-World Use Cases* Closures are used in: ✅ Data hiding / encapsulation ✅ Callbacks ✅ Event handlers ✅ setTimeout / async code ✅ Functional programming *Double Tap ❤️ For More*
To view or add a comment, sign in
-
*🚀 JavaScript Closures 🔥* Closures are a fundamental concept in JavaScript, often asked in interviews. A closure is when a function remembers variables from its outer scope, even after the outer function has finished executing. *🔹 1. Basic Example of Closure* function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const counter = outer(); counter(); // 1 counter(); // 2 counter(); // 3 The inner function remembers the `count` variable even after the outer function has finished executing. *🔹 2. Why Closures Work* Because of lexical scope, inner functions can access their own variables, parent function variables, and global variables, even after the parent function ends. *🔹 3. Closures for Data Privacy (Very Important)* Closures help protect data. function createBankAccount() { let balance = 1000; return function(amount) { balance += amount; console.log(balance); } } const account = createBankAccount(); account(500); // 1500 account(200); // 1700 The `balance` variable is private and cannot be accessed directly. *🔹 4. Real-World Use Cases* Closures are used in: ✅ Data hiding / encapsulation ✅ Callbacks ✅ Event handlers ✅ setTimeout / async code ✅ Functional programming
To view or add a comment, sign in
-
Day 50/50 – JavaScript Interview Question? Question: What is the difference between setTimeout(), setImmediate(), and process.nextTick() in Node.js? Simple Answer: setTimeout() schedules callback in macrotask queue after delay. setImmediate() executes in next event loop iteration. process.nextTick() executes before next phase (microtask, highest priority). Order: nextTick() → Promises → setImmediate() → setTimeout(). 🧠 Why it matters in real projects: Understanding these is crucial for Node.js performance, avoiding event loop starvation, and controlling async execution order. Misusing them causes performance bottlenecks or unexpected behavior. 💡 One common mistake: Overusing process.nextTick() starves the event loop since it runs before I/O. Also assuming setImmediate() runs immediately—it's actually next iteration, and order with setTimeout(0) can vary. 📌 Bonus: console.log('1: Start'); setTimeout(() => console.log('2: setTimeout'), 0); setImmediate(() => console.log('3: setImmediate')); process.nextTick(() => console.log('4: nextTick')); Promise.resolve().then(() => console.log('5: Promise')); console.log('6: End'); // Output: // 1: Start // 6: End // 4: nextTick (highest priority) // 5: Promise (microtask) // 3: setImmediate (next loop) // 2: setTimeout (timer phase) // Use cases: // nextTick - let constructor complete class AsyncResource { constructor() { process.nextTick(() => this.init()); } } // setImmediate - break up long operations function processLargeArray(arr) { const chunk = arr.splice(0, 100); processChunk(chunk); if (arr.length > 0) { setImmediate(() => processLargeArray(arr)); // ✓ Yields } } // Danger: Recursive nextTick starves I/O! function dangerous() { process.nextTick(dangerous); // ✗ Infinite, blocks I/O } // Better: use setImmediate for recursion function better() { setImmediate(better); // ✓ Allows I/O } // Modern alternative to nextTick Promise.resolve().then(() => { // Microtask like nextTick, less aggressive }); 🎉 Series Complete! 50/50 JavaScript Interview Questions #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #NodeJS #EventLoop #AsyncProgramming #WebDev #SeriesComplete
To view or add a comment, sign in
-
🚨 JavaScript Interview Trap: Shallow Copy vs Deep Copy Many developers think they understand object copying… Until this bug appears in production. 😅 You copy an object. You modify the copy. And suddenly… 💥 The original object also changes. Why does this happen? Because in JavaScript, objects are stored by reference. 🧠 Example JavaScript const user = { name: "Sajid", skills: ["JavaScript", "React"] }; const copy = { ...user }; copy.skills.push("Node.js"); console.log(user.skills); // ["JavaScript", "React", "Node.js"] Even though we copied the object… the original data changed. ⚠️ What Happened? This was a Shallow Copy. A shallow copy only duplicates the first level of an object. Nested objects or arrays still share the same memory reference. Think of it like: 📦 New box 📦 Same items inside Common Shallow Copy Methods These do NOT create deep copies: • Spread Operator { ...obj } • Object.assign() • Array.slice() • Array.from() They work great for flat objects. But for nested data, they can cause hidden bugs. 💡 Solution: Deep Copy To fully duplicate nested data: JavaScript const deepCopy = structuredClone(user); or JavaScript const deepCopy = JSON.parse(JSON.stringify(user)); Now changes won't affect the original object. ⚡ Small JavaScript concepts like this cause huge production bugs. Most developers learn syntax. Great developers understand how memory actually works. 💬 Quick question for you: Have you ever faced a Shallow Copy bug in a project? Comment "YES" or "NEVER AGAIN" 😄
To view or add a comment, sign in
-
✅ *Top JavaScript Coding Interview Questions* 🧠💻 *1️⃣ What is the difference between `==` and `===` in JavaScript?* *Answer:* - `==` compares values with type coercion. - `===` compares both value *and* type (strict equality). ```js 5 == "5" // true 5 === "5" // false ``` *2️⃣ How to check if a variable is an array?* *Answer:* ```js Array.isArray(myVar); // returns true if myVar is an array ``` *3️⃣ What is a closure in JavaScript?* *Answer:* A closure is when an inner function has access to variables from an outer function even after the outer function has returned. ```js function outer() { let count = 0; return function inner() { return ++count; } } const counter = outer(); counter(); // 1 ``` *4️⃣ Explain event delegation.* *Answer:* Event delegation is a technique of handling events at a higher-level element rather than on individual elements by using event bubbling. ```js document.getElementById("parent").addEventListener("click", (e) => { if (e.target.tagName === "BUTTON") { console.log("Button clicked:", e.target.textContent); } }); ``` *5️⃣ What is the difference between `let`, `const`, and `var`?* *Answer:* - `var`: function-scoped, hoisted - `let`: block-scoped, reassignable - `const`: block-scoped, cannot be reassigned *6️⃣ How does `this` keyword behave?* *Answer:* - In global scope: `this` refers to the global object (e.g., `window` in browsers). - In object methods: `this` refers to the object. - In arrow functions: `this` is lexically bound (takes value from surrounding context). *7️⃣ Write a function to reverse a string.* ```js function reverseStr(str) { return str.split("").reverse().join(""); } reverseStr("hello"); // "olleh" ``` *8️⃣ What is the output?* ```js console.log(typeof null); // "object" ``` *Explanation:* This is a historical bug in JavaScript and remains for backward compatibility. 💬 *React ❤️ for more!*
To view or add a comment, sign in
-
🚨 I recently went through a JavaScript interview and they asked some very tricky questions. Honestly, these were not the usual “What is closure?” or “What is hoisting?” questions. They were designed to test how deeply you understand JavaScript execution, async behavior, and edge cases. If you’re preparing for Frontend / React interviews, don’t miss these questions. 👇 🧠 1️⃣ Predict the Output console.log([] + []); console.log([] + {}); console.log({} + []); console.log({} + {}); What exactly gets printed and why does JavaScript behave like this? ⚡ 2️⃣ Event Loop Deep Dive console.log("start"); setTimeout(() => console.log("timeout")); Promise.resolve().then(() => console.log("promise")); queueMicrotask(() => console.log("microtask")); console.log("end"); 👉 What is the exact output order? 🔥 3️⃣ Closures + Loop Trap for (var i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 100); } What will be printed and why does this happen? 🧩 4️⃣ this Binding Confusion const obj = { value: 10, getValue() { return this.value; } }; const getValue = obj.getValue; console.log(getValue()); What will this print? ⚠️ 5️⃣ Object Reference Trap const a = { name: "JS" }; const b = a; b.name = "React"; console.log(a.name); Why does this happen? 🧪 6️⃣ Array Mutation Trick const arr = [1,2,3]; arr[10] = 99; console.log(arr.length); console.log(arr); What does the array actually look like? 🧠 7️⃣ Destructuring Edge Case const obj = { a: 1, b: 2 }; const { a, ...rest } = obj; rest.b = 5; console.log(obj.b); Does the original object change? ⚡ 8️⃣ Promise Chain Trap Promise.resolve(1) .then(x => x + 1) .then(x => { throw new Error("boom"); }) .catch(() => 10) .then(x => console.log(x)); What is the final output? 🔥 9️⃣ typeof Weirdness console.log(typeof NaN); console.log(typeof null); console.log(typeof []); Why do these results exist in JavaScript? 🧨 🔟 Implicit Type Coercion console.log("5" - 3); console.log("5" + 3); console.log(true + false); console.log([] == false); Explain how JavaScript converts the types internally. 💡 Principal Engineer Advice In interviews, they’re not testing if you memorized JavaScript. They are testing if you understand: ⚡ Execution Context ⚡ Event Loop ⚡ Closures ⚡ Type Coercion ⚡ Object References Master these and JavaScript interviews become much easier. 🔥 I’ll keep posting tricky Frontend / React interview questions daily to help juniors crack interviews. #javascript #frontend #reactjs #webdevelopment #frontendengineer #codinginterview
To view or add a comment, sign in
-
-
JavaScript Hoisting: The Interview Question That Tricks Everyone 🚀 Most developers think they know hoisting. Then the interviewer shows them tricky code. Here's your complete guide to mastering it. --- 🎯 The Definition Hoisting is JavaScript's behavior of moving declarations to the top of their scope during compilation. Key rule: Only declarations are hoisted, NOT initializations. --- 📊 The 3 Types (With Examples) 1. var – Hoisted & Initialized as undefined ```javascript console.log(name); // undefined (not error!) var name = "John"; // JS reads it as: // var name; → console.log(name); → name = "John"; ``` 2. let/const – Hoisted but NOT Initialized (TDZ) ```javascript console.log(age); // ❌ ReferenceError let age = 25; // Temporal Dead Zone – exists but inaccessible ``` 3. Function Declarations – Fully Hoisted ```javascript greet(); // ✅ "Hello" – works! function greet() { console.log("Hello"); } // Function expressions? NOT hoisted! ``` --- 🌍 Real-World Example The Bug That Wastes Hours: ```javascript function processOrders(orders) { for (var i = 0; i < orders.length; i++) { setTimeout(() => { console.log(orders[i]); // undefined × 3 }, 1000); } } // Why? var is function-scoped, hoisted to top. // Fix: Use let (block-scoped) or closure ``` The Solution: ```javascript function processOrders(orders) { for (let i = 0; i < orders.length; i++) { setTimeout(() => { console.log(orders[i]); // ✅ Works! }, 1000); } } ``` --- 💡 Senior-Level Insight "Hoisting explains why: · var causes unexpected bugs (always use let/const) · TDZ prevents accessing variables before declaration · Function hoisting enables clean code organization Modern JS best practice: Declare variables at the top. Use const by default, let when reassignment needed." --- 🎤 Interview Answer Structure Q: "Explain hoisting." "Hoisting is JavaScript's compilation-phase behavior where declarations are moved to the top. Function declarations are fully hoisted, var variables hoisted as undefined, while let/const are hoisted but stay in Temporal Dead Zone until execution. This is why we get undefined with var but ReferenceError with let when accessed early." --- 📝 Quick Cheat Sheet Type Hoisted Initial Value Access Before Declaration var ✅ undefined Returns undefined let ✅ Uninitialized ❌ ReferenceError (TDZ) const ✅ Uninitialized ❌ ReferenceError (TDZ) Function Dec ✅ Function itself ✅ Works fine --- 🚨 Common Interview Twist: ```javascript var a = 1; function test() { console.log(a); // undefined (not 1!) var a = 2; } test(); // Why? Inner var a is hoisted to top of function scope ``` --- Master hoisting = Master JavaScript execution. Found this helpful? ♻️ Share with your network. Follow me for more interview prep content! #JavaScript #CodingInterview #WebDevelopment #TechInterview #JSHoisting
To view or add a comment, sign in
-
🚨 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗿𝗮𝗽 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 (𝗢𝘂𝘁𝗽𝘂𝘁 𝗕𝗮𝘀𝗲𝗱) Many JavaScript interviews don’t test how much you know… They test how deeply you understand the language. Here are 3 small JavaScript snippets that often confuse developers in interviews 👇 🧠 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟭: 𝘃𝗮𝗿 𝘃𝘀 𝗹𝗲𝘁 𝗶𝗻 𝗹𝗼𝗼𝗽𝘀 𝑓𝑜𝑟 (𝑣𝑎𝑟 𝑖 = 0; 𝑖 < 3; 𝑖++) { 𝑠𝑒𝑡𝑇𝑖𝑚𝑒𝑜𝑢𝑡(() => 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑖), 1000); } 𝗢𝘂𝘁𝗽𝘂𝘁: 3, 3, 3 💡 𝗪𝗵𝘆? var is 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝘀𝗰𝗼𝗽𝗲𝗱, not block scoped. All callbacks share the same i variable. By the time setTimeout runs, the loop has finished and i = 3. ✔️ 𝗙𝗶𝘅 𝘂𝘀𝗶𝗻𝗴 𝗹𝗲𝘁 for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } Output: 0, 1 ,2 Because let creates a new binding for each iteration. 🧠 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟮: 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗧𝘆𝗽𝗲 𝗖𝗼𝗲𝗿𝗰𝗶𝗼𝗻 console.log("5" - 3); console.log("5" + 3); console.log(true + true); Output: 2, 53, 2 💡 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 JavaScript performs 𝗶𝗺𝗽𝗹𝗶𝗰𝗶𝘁 𝘁𝘆𝗽𝗲 𝗰𝗼𝗲𝗿𝗰𝗶𝗼𝗻. "5" - 3 → number conversion → 5 - 3 = 2 "5" + 3 → string concatenation → "53" true + true → 1 + 1 = 2 👉 The + operator prefers string concatenation, while other operators trigger numeric conversion. 🧠 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟯: 𝘁𝗵𝗶𝘀 𝗶𝗻𝘀𝗶𝗱𝗲 𝗮𝗿𝗿𝗼𝘄 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 const obj = { name: "Shubham", greet: function() { setTimeout(() => { console.log(this.name); }, 1000); } }; obj.greet(); Output: Shubham 💡 𝗪𝗵𝘆? Arrow functions do not have their own this. They inherit this from the surrounding scope. Here, this refers to obj. 💬 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗶𝗽 Most JavaScript interview questions revolve around: • Scope • Closures • this keyword • Type coercion • Event loop Mastering these concepts makes 𝗝𝗦 𝗶𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗾𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 𝗺𝘂𝗰𝗵 𝗲𝗮𝘀𝗶𝗲𝗿. 🔥 𝗤𝘂𝗶𝗰𝗸 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 What will be the output of this? console.log([] + []); console.log([] + {}); console.log({} + []); Write your answers in the comments 👇 ♻️ If you found this helpful, repost to help other developers preparing for JavaScript interviews. 📌 Follow Shubham Kumar Raj for more such content😊 #javascript #webdevelopment #frontenddeveloper #codinginterview #softwaredevelopment #learnjavascript #100daysofcode #hiring
To view or add a comment, sign in
-
🚀 Day 23 of My Angular Journey – JavaScript Interview Problems (Code + Deep Dive) Today, I focused not just on solving problems, but on understanding the logic, edge cases, and performance considerations behind them. 🔹 1. Deep Clone (Object & Array) Problem: Copy nested objects without sharing references Core Logic: - Primitive → return directly - Array → recursively clone each item - Object → recursively copy keys function deepClone(obj) { if (obj === null || typeof obj !== 'object') return obj; if (Array.isArray(obj)) { return obj.map(item => deepClone(item)); } let result = {}; for (let key in obj) { result[key] = deepClone(obj[key]); } return result; } Edge Cases: - "null" (typeof null = object) - Nested arrays/objects - Circular references (needs WeakMap – advanced) Complexity: O(n) 🔹 2. Flatten Array (Recursive + Thinking) Logic: Break problem into smaller parts using recursion function flattenArray(arr) { let result = []; for (let item of arr) { if (Array.isArray(item)) { result = result.concat(flattenArray(item)); } else { result.push(item); } } return result; } Interview Twist: 👉 Can be solved using stack (iterative) instead of recursion Complexity: O(n) 🔹 3. Remove Duplicates (Optimization) Logic: Use Set for O(1) lookup function removeDuplicates(arr) { return [...new Set(arr)]; } Why better than loops? - No nested iteration - Cleaner & faster Complexity: O(n) Without Set function removeDuplicates(str) { let seen = {}; let result = ''; for (let char of str) { if (!seen[char]) { seen[char] = true; result += char; } } return result; } 🔹 4. First Non-Repeating Character Logic: - Step 1 → Count frequency - Step 2 → Find first unique function firstNonRepeating(str) { let count = {}; for (let char of str) { count[char] = (count[char] || 0) + 1; } for (let char of str) { if (count[char] === 1) return char; } return null; } Advanced Insight: 👉 Optimized using Map + Queue for real-time processing 🔹 5. Flatten Object (Real-world Application) Use Case: APIs, form data, payload transformation function flattenObject(obj, parent = '', res = {}) { for (let key in obj) { let newKey = parent ? `${parent}.${key}` : key; if (typeof obj[key] === 'object' && obj[key] !== null) { flattenObject(obj[key], newKey, res); } else { res[newKey] = obj[key]; } } return res; } Example Output: "{ user: { name: "A" } } → { "user.name": "A" }" Key Learnings from Today: ✔ Recursion to solve nested problems ✔ Stack vs recursion thinking ✔ Hashing (Map/Object) for efficient lookup ✔ Choosing right data structure (Set vs Array) ✔ Handling real-world edge cases #JavaScript #Angular #FrontendDevelopment #CodingInterview #LearningJourney
To view or add a comment, sign in
-
JavaScript Interview Question #2 ------------------------------------ Problem: Convert an array of key-value objects into a single object. Input: [{"key": "a", "value":1}, {"key": "b", "value": 2}] Output: {"a" : 1, "b" : 2} Solution: The input is an array of objects, and the goal is to transform it into a single object. There are multiple ways to solve this: 1. using for...of loop const arr = [{"key": "a", "value":1}, {"key": "b", "value": 2}]; let newObj = {}; for(let e of arr){ newObj[e.key] = e.value; } console.log(newObj); 2. using Object.fromEntries const arr = [{"key": "a", "value":1}, {"key": "b", "value": 2}]; const newObj = Object.fromEntries( arr.map(item => [item.key, item.value]) ); console.log(newObj); 3. using reduce() const arr = [{"key": "a", "value":1}, {"key": "b", "value": 2}]; const newObj = arr.reduce((acc, curr) => { acc[curr.key] = curr.value; return acc; }, {}); console.log(newObj); ------------------------------------------------------------------------------------- Different approaches help to build flexibility in problem-solving. I used the for...of loop in my interview. Which one do you prefer ?
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