Last week, I was asked to build an event notifier in JavaScript during an interview: Requirements were straightforward: - create an on(eventName, handler) method - return a remover (unsubscribe) function from on - create a send(eventName, ...args) method - call all handlers registered for that event with the given arguments My initial approach: - maintained an events object - stored handlers in an array against each event name - used a unique id(leveraging Symbol) inside the remover’s closure to de-register the handler - send() simply looped over the handlers and invoked them with arguments That solved correctness. Follow-up question was about optimization. To improve add/remove performance, I replaced the array with a Map, which made handler registration and removal more efficient. Sharing my implementation here — happy to hear suggestions or alternate ways you’d approach this. Always open to learning. 🙂 #javascript #machinecoding #interviewprep #frontend #learninpublic #codinginterviews
Building an Event Notifier in JavaScript: Optimizing Handler Registration and Removal
More Relevant Posts
-
🧠 JavaScript Quiz Time (Quick & Interesting One!) What will this code log? let a = 1; function test() { console.log(a); let a = 2; } test(); A) 1 B) 2 C) undefined D) ❌ Error 👉 Drop your answer in the comments before running it. This one checks how well you understand hoisting + temporal dead zone, things that actually matter in real world JS, not just interviews. I share these short JS brain-teasers regularly 🚀 Let’s see who gets it right. #JavaScript #JSQuiz #MERN #Devs #Learn #Growth
To view or add a comment, sign in
-
-
Day 4/50 – JavaScript Interview Question? Question: What's the difference between Event Bubbling and Event Capturing? Simple Answer: Event propagation has three phases: capturing (from window down to target), target (the element itself), and bubbling (from target back up to window). Bubbling is the default behavior where events propagate upward through parent elements. 🧠 Why it matters in real projects: Understanding event propagation is essential for implementing event delegation, which dramatically improves performance when handling many similar elements (like list items or table rows). It also helps prevent unintended event triggering. 💡 One common mistake: Not knowing when to use stopPropagation() vs stopImmediatePropagation(). The latter also prevents other listeners on the same element from firing, while the former only stops the event from moving to parent/child elements. 📌 Bonus: // Event delegation example - one listener instead of 1000! document.querySelector('ul').addEventListener('click', (e) => { if (e.target.tagName === 'LI') { console.log('List item clicked:', e.target.textContent); } }); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
🔥 Closure = “private variables” in JavaScript (without classes). This is a very common interview pattern, and it shows you really understand closures. ❓ What’s the output? A) 1,2,1,2,1 B) 1,2,1,2,2 C) 1,2,1,1,1 D) Throws an error ❓Why can’t we access the count directly from outside? 📈 Real-world relevance: This is the core idea behind “instance state”: keep it private without exposing it globally. 💬 Drop your answers + reasoning 👇 #CodeSnatch #javascript #closures #interviewprep #webdevelopment #frontend #codinginterviews
To view or add a comment, sign in
-
-
🔁 JavaScript Module 3: Functions & Scope Writing code is easy. Writing reusable, clean, and scalable code is a skill. In Module 3, we deep-dive into Functions and Scope — two of the most important and most-asked topics in JavaScript interviews. This carousel covers: ✅ Function declaration vs expression ✅ Arrow functions (ES6) ✅ Parameters & return values ✅ Global, local & block scope ✅ Hoisting (interview favorite ⚠️) This module is designed for: 🎓 Students building strong fundamentals 👨💻 Professionals revising core concepts 🎯 Developers preparing for JavaScript interviews 👉 Save this post for revision 👉 Share with someone learning JavaScript 👉 Comment “JS” for full course details 👉 Follow me for the complete JavaScript roadmap #JavaScript #LearnJavaScript #JavaScriptFunctions #ScopeInJavaScript #JavaScriptInterview #WebDevelopment #FrontendDeveloper #ProgrammingBasics #DeveloperRoadmap #CodingLife
To view or add a comment, sign in
-
Day 7/50 – JavaScript Interview Question? Question: What is Event Delegation and why should you use it? Simple Answer: Event Delegation is the technique of attaching a single event listener to a parent element instead of multiple listeners to individual child elements, taking advantage of event bubbling. 🧠 Why it matters in real projects: When you have hundreds or thousands of similar elements (like a large list or table), event delegation drastically reduces memory usage and improves initialization performance. It also automatically handles dynamically added elements without needing to attach new listeners. 💡 One common mistake: Forgetting to check the event target before executing logic, which can cause your handler to fire for unintended elements (like the parent container itself). 📌 Bonus: // ❌ Bad - 10,000 event listeners items.forEach(item => { item.addEventListener('click', handleClick); }); // ✅ Good - Just 1 event listener document.querySelector('.list').addEventListener('click', (e) => { if (e.target.matches('.item')) { handleClick(e); } }); #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
💥 JavaScript Interview Challenge #17 🧠 Can you guess the output? . . . Answer: [1, 2] [1, 2, <3 empty items>] Explanation: Setting arr.length = 2 truncates the array — all elements after index 1 are removed. Setting arr.length = 5 increases the length, but the new slots are empty (undefined holes) — not actual undefined values. So the second log shows [1, 2, <3 empty items>].
To view or add a comment, sign in
-
-
Master JavaScript one step at a time 🚀 In this short video, I explain how to find the index of a character in a string using indexOf() — a simple but important concept for every frontend developer. 🎯 Perfect for beginners & interview prep 🤖 Created using AI tools #JavaScript #WebDevelopment #FrontendDeveloper #CodingTips #LearnToCode
To view or add a comment, sign in
-
JavaScript Notes to Escape Tutorial Hell (10/20) We’ve reached the halfway mark! And today, we are tackling the most famous (and feared) topic in JavaScript interviews: Closures. If you understand this, you understand the true power of the language. This deck explains: - How functions retain access to their lexical environment - Why closures work even after the parent function finishes execution - Why variables are referenced, not copied - How closures enable data hiding - Real use cases: currying, module pattern - Why closures are asked so often in interviews Mastering closures is the bridge between writing scripts and engineering applications. #JavaScript #WebDevelopment #Closures #CodingJourney #SoftwareEngineering #LearningInPublic #FrontendDeveloper
To view or add a comment, sign in
-
So you're prepping for a JavaScript interview. It's tough. You gotta know your stuff, like scoping and hoisting - they're key. Understanding how variables behave in different contexts is crucial, and it's not just about var vs let, it's about how they interact with the rest of your code. For instance, var is hoisted and defaults to undefined, whereas let is hoisted but not initialized - that's a big difference. And then there's the whole loop and setTimeout thing: var is function scoped, let is block scoped - it's like they're playing by different rules. This is another tricky one, especially when it comes to regular vs arrow functions - the behavior is just not the same. Take unary plus and logical NOT, for example: +true converts to a number, and 'Lydia' is truthy - it's all about understanding how JavaScript interprets these values. And let's not forget property access with objects - like mouse[bird.size] resolving to mouse['small'], it's all about the syntax. You can find more info on these topics, and some must-know JavaScript output and MCQ questions with answers and explanations, if you know where to look. It's all about practice, and understanding the nuances of the language. Check out this resource for more info: https://lnkd.in/gNy4MDgD #JavaScriptInterview #CodingChallenges #WebDevelopment
To view or add a comment, sign in
-
I was solving some basic JavaScript interview questions and came across this one. It looks simple, but it actually tests scope and hoisting really well. If you are interested, try to figure out the output in the correct sequence without running the code. I have added the answer in the comments. #JavaScript #InterviewPreparation #FrontendDevelopment #LearningInPublic #CodingPractice #FullStackDeveloper
To view or add a comment, sign in
-
Explore related topics
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
Rajat Mishra insightful 👍