🚀 JavaScript Interview Prep Series — Day 10 Topic: Building Custom Array Methods in JavaScript Continuing my JavaScript interview revision series, today I practiced an important concept: 👉 How built-in array methods like map, filter, and reduce work internally In interviews, you are often asked: “Can you implement map/filter/reduce yourself?” Understanding this shows strong JavaScript fundamentals. 🍳 Real-World Example: Kitchen Workflow Imagine a professional kitchen: 1️⃣ Transform Station (like map) Chef takes ingredients and modifies each item — chopping, cooking, seasoning. Input ingredients → transformed ingredients. 2️⃣ Quality Check Station (like filter) Inspector selects only good ingredients and rejects bad ones. Only items meeting criteria continue. 3️⃣ Mixing Station (like reduce) Chef combines all prepared ingredients into one final dish. Many items → single result. 💻 Custom Array Method Example Custom map implementation Array.prototype.myMap = function(callback) { const result = []; for (let i = 0; i < this.length; i++) { result.push(callback(this[i], i, this)); } return result; }; const arr = [1, 2, 3]; const doubled = arr.myMap(x => x * 2); console.log(doubled); // [2, 4, 6] Custom filter implementation Array.prototype.myFilter = function(callback) { const result = []; for (let i = 0; i < this.length; i++) { if (callback(this[i], i, this)) { result.push(this[i]); } } return result; }; Custom reduce implementation Array.prototype.myReduce = function(callback, initial) { let accumulator = initial; for (let i = 0; i < this.length; i++) { accumulator = callback(accumulator, this[i]); } return accumulator; }; ✅ Why Interviewers Ask This Because it tests: • Understanding of loops • Callback usage • Array iteration logic • Internal behavior of JS methods Once you understand this, map/filter/reduce become much clearer. 📌 Goal: Share daily JavaScript interview topics while revising fundamentals and learning in public. Next topics: debouncing, throttling, event delegation, deep cloning, and more. Let’s keep improving step by step 🚀 #JavaScript #InterviewPreparation #ArrayMethods #WebDevelopment #LearningInPublic #Developers #CodingJourney #Frontend
Rajashekar Gunaganti’s Post
More Relevant Posts
-
🚀 JavaScript Interview Prep Series — Day 27 Topic: Web APIs in JavaScript (Browser Superpowers) Continuing my JavaScript interview journey, today I revised an important concept that many developers misunderstand: 👉 Web APIs Web APIs are NOT part of JavaScript itself — they are provided by the browser environment to help JavaScript interact with the real world. 🏨 Real-World Example: Hotel Concierge Think of JavaScript as a hotel guest. When the guest needs something, they don’t do it themselves — they ask the concierge (browser). The concierge provides services like: 🧭 Where am I? → Geolocation 💾 Save my info → Storage 📦 Get data → Fetch ⏰ Run later → Timer JavaScript simply requests, and the browser handles the heavy work. 💻 1️⃣ Geolocation API navigator.geolocation.getCurrentPosition((pos) => { console.log(pos.coords.latitude); console.log(pos.coords.longitude); }); 📍 Gets user location from the browser. 💻 2️⃣ LocalStorage API localStorage.setItem("user", "Alice"); localStorage.getItem("user"); // "Alice" 💾 Stores data in the browser. 💻 3️⃣ Fetch API fetch("https://lnkd.in/gHTr-faK") .then(response => response.json()) .then(data => console.log(data)); 📦 Makes network requests. 💻 4️⃣ Timer API setTimeout(() => { console.log("This runs after 2 seconds"); }, 2000); ⏰ Runs code after a delay. 🧠 Key Interview Point 👉 JavaScript = single-threaded language 👉 Web APIs = browser-provided async helpers 👉 Event loop coordinates everything This is a very common interview trap. 🎯 Why Interviewers Ask This Because it tests: • Understanding of JS runtime • Async architecture knowledge • Event loop clarity • Browser vs JS distinction ⚠️ Pro Tips ✅ Web APIs come from the browser (or Node runtime) ✅ They enable asynchronous behavior ✅ They work with the event loop ✅ They are essential for real-world apps 📌 Goal: Share daily JavaScript concepts while preparing for interviews and learning in public. Next topics: Event Loop deep dive (advanced), Microtasks vs Macrotasks, and more. Let’s keep the streak strong 🚀 #JavaScript #InterviewPreparation #WebAPIs #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
🚀 JavaScript Interview Prep Series — Day 11 Topic: Debounce, Throttle & Memoization in JavaScript Continuing my JavaScript interview revision journey, today I focused on performance optimization techniques often asked in frontend interviews: 👉 Debounce, Throttle, and Memoization These techniques help improve performance when functions are called frequently. Let’s simplify them with real-world examples. ⏱ Debounce — Wait Until User Stops Imagine an elevator door. If people keep entering, the door keeps reopening and only closes once no one enters anymore. In JavaScript: The function runs only after calls stop for a certain time. Example — Search Input function debounce(fn, delay) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } Used when typing in search bars to avoid firing API calls on every keystroke. 🚗 Throttle — Limit Execution Rate Think of a toll booth allowing one car every few seconds, even if many cars are waiting. In JavaScript: The function runs at fixed intervals, no matter how often triggered. Example — Scroll Event function throttle(fn, limit) { let lastCall = 0; return function (...args) { const now = Date.now(); if (now - lastCall >= limit) { lastCall = now; fn.apply(this, args); } }; } Useful for scroll or resize events. 🧠 Memoization — Cache Results Imagine a librarian remembering your previous book request instead of searching again. In JavaScript: Results are stored and reused for the same inputs. Example function memoize(fn) { const cache = {}; return function (arg) { if (cache[arg]) return cache[arg]; const result = fn(arg); cache[arg] = result; return result; }; } Great for heavy calculations. ✅ Why Interviewers Ask This Because it tests: • Performance optimization knowledge • Event handling understanding • Real-world frontend scenarios • Efficient function execution 📌 Goal: Share JavaScript concepts daily while revising interview topics and learning in public. Next topics: Event Delegation, Hoisting Deep Dive, Execution Context, and more. Let’s keep improving step by step 🚀 #JavaScript #InterviewPreparation #Debounce #Throttle #Memoization #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
JavaScript Scenario-Based Interview Questions That Actually Matter Modern JavaScript interviews are no longer about memorizing definitions. They’re about how you reason when real applications break. Below are high-impact, scenario-driven JavaScript questions that repeatedly appear in frontend interviews, especially for mid → senior roles. 1️⃣ Closures in Real Applications You need a button that remembers how many times it was clicked, even after re-renders What interviewers want to know: • Do you understand closures beyond theory • Can you preserve state without globals 👉 How would you use a closure to retain the count safely 2️⃣ Dependent vs Parallel API Calls API-2 depends on API-1’s response API-3 can run independently What interviewers want to know: • Can you optimize async flows • Do you avoid unnecessary blocking 👉 How would you structure this using async/await efficiently 3️⃣ Preventing Multiple Submissions A user clicks the Submit button multiple times, triggering duplicate API calls What interviewers want to know: • Do you think about real user behavior • Can you protect backend systems 👉 How would you prevent this (disable button, debounce, promise locking) 4️⃣ Hidden Memory Leaks Your SPA slows down after navigation. You discover a setInterval that was never cleared What interviewers want to know: • Do you understand the JS memory lifecycle • Can you debug performance issues 👉 Why does this cause a memory leak, and how do you clean it up correctly 5️⃣ Event Delegation at Scale A list contains 1,000+ clickable items What interviewers want to know: • Do you understand DOM performance • Can you design scalable event handling 👉 Why is event delegation better than attaching individual listeners 6️⃣ Hoisting Confusion console.log(a); var a = 10; What interviewers want to know: • Do you understand execution context • Can you explain behavior, not just output 👉 Why does this log undefined instead of 10 7️⃣ Shallow vs Deep Copy Bugs Updating a copied object unexpectedly mutates the original object What interviewers want to know: • Do you understand reference vs value • Can you avoid subtle production bugs 👉 Why does this happen, and how do you prevent it 8️⃣ Debounce or Throttle A search input triggers an API call on every keystroke What interviewers want to know: • Can you balance UX and performance • Do you choose the right optimization technique 👉 Should you use debounce or throttle and why 9️⃣ The this Keyword Trap setTimeout(function () { console.log(this.name); }, 1000); What interviewers want to know: • Do you understand function context • Can you fix these common bugs 👉 Why is this undefined here, and how would you fix it 🔟 Promises vs Async Error Handling An API fails, but .then() still executes What interviewers want to know: • Do you handle failures correctly • Can you write resilient async code 👉 How should errors be handled properly with Promises or async/await
To view or add a comment, sign in
-
🚀 JavaScript Interview Prep Series — Day 24 Topic: JavaScript Design Patterns (Must-Know for Interviews) Continuing my JavaScript interview preparation journey, today I revised a high-value concept: 👉 Design Patterns Design patterns are reusable solutions to common problems in software design. Interviewers love them because they show your code architecture thinking, not just syntax knowledge. Today I focused on 4 important patterns: ✅ Singleton ✅ Factory ✅ Observer ✅ Module 🧠 Real-World Understanding 🔵 Singleton — Only One CEO A company has only one CEO, and everyone must go through that same person. 👉 Ensures only one instance exists 👉 Shared across the application 🟢 Factory — Car Manufacturing Plant You tell the factory what you want: Car Truck Bike The factory decides how to create it. 👉 Creates objects based on input 👉 Hides creation complexity 🟠 Observer — YouTube Notifications When a YouTuber uploads a video: 📢 All subscribers get notified automatically. 👉 One-to-many relationship 👉 Used in event systems 🟣 Module — Organized Toolbox A toolbox exposes only the tools you need while keeping internal tools hidden. 👉 Encapsulation 👉 Public vs Private separation 💻 Practical Examples Singleton Example class Database { constructor() { if (Database.instance) { return Database.instance; } Database.instance = this; } } const db1 = new Database(); const db2 = new Database(); console.log(db1 === db2); // true Factory Example class VehicleFactory { create(type) { if (type === "car") return { wheels: 4 }; if (type === "bike") return { wheels: 2 }; } } const factory = new VehicleFactory(); console.log(factory.create("car")); Observer Example class Subject { constructor() { this.observers = []; } subscribe(fn) { this.observers.push(fn); } notify(data) { this.observers.forEach(fn => fn(data)); } } const channel = new Subject(); channel.subscribe(msg => console.log("User1:", msg)); channel.subscribe(msg => console.log("User2:", msg)); channel.notify("New video uploaded!"); Module Pattern Example const Counter = (() => { let count = 0; // private return { increment() { return ++count; }, getCount() { return count; } }; })(); Counter.increment(); 🎯 Why Interviewers Ask This Because design patterns show: • System design thinking • Code reusability skills • Clean architecture mindset • Real-world engineering maturity 🧠 When to Use ✔ Singleton → configs, DB connections ✔ Factory → object creation logic ✔ Observer → events, subscriptions ✔ Module → encapsulation 📌 Goal: Share daily JavaScript concepts while preparing for interviews and learning in public. Next topics: Event Delegation deep dive, Performance patterns, Advanced async flows. Let’s keep building strong fundamentals 🚀 #JavaScript #InterviewPreparation #DesignPatterns #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
Day 47/50 – JavaScript Interview Question? Question: What is the difference between prototype and __proto__? Simple Answer: prototype is a property on constructor functions containing the object used as prototype for new instances. __proto__ is the actual internal link on every object pointing to its prototype. Use Object.getPrototypeOf() instead of __proto__. 🧠 Why it matters in real projects: Understanding the prototype chain explains how JavaScript inheritance works, how methods like .map() are available on arrays, and how classes work under the hood. Essential for creating efficient object hierarchies. 💡 One common mistake: Confusing prototype with __proto__, or modifying Object.prototype which affects all objects globally. Also using deprecated __proto__ instead of standard Object.getPrototypeOf(). 📌 Bonus: // Constructor function function Person(name) { this.name = name; } Person.prototype.greet = function() { return `Hello, I'm ${this.name}`; }; const alice = new Person('Alice'); // Key difference: console.log(Person.prototype); // Object with greet method console.log(alice.__proto__ === Person.prototype); // true console.log(Object.getPrototypeOf(alice) === Person.prototype); // true // Prototype chain: // alice → Person.prototype → Object.prototype → null // Inheritance example function Employee(name, title) { Person.call(this, name); this.title = title; } Employee.prototype = Object.create(Person.prototype); Employee.prototype.constructor = Employee; const bob = new Employee('Bob', 'Developer'); console.log(bob.greet()); // Inherited from Person // Modern ES6 equivalent class ModernEmployee extends Person { constructor(name, title) { super(name); this.title = title; } } // Best practices: // ✓ Use Object.getPrototypeOf() const proto = Object.getPrototypeOf(alice); // ✗ Don't modify Object.prototype Object.prototype.myMethod = function() {}; // BAD! // ✗ Don't use __proto__ directly (deprecated) // ✓ Use Object.setPrototypeOf() instead #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews
To view or add a comment, sign in
-
🚀 JavaScript Interview Prep Series — Day 22 Topic: Proxy & Reflect in JavaScript Continuing my JS deep-dive, today I explored a powerful metaprogramming concept: 👉 Proxy & Reflect This is a favorite advanced interview topic because it shows how well you understand object behavior control in JavaScript. 🛡️ Real-World Analogy: VIP Security Checkpoint Think of a celebrity entering a hotel. 🔵 Proxy = Bodyguard (Interceptor) The bodyguard stands between the public and the celebrity. Every action goes through the bodyguard: Someone tries to read info → bodyguard checks Someone tries to change data → bodyguard validates Someone tries to delete → bodyguard can block ✅ Controls access ✅ Adds validation ✅ Logs activity In JavaScript, Proxy wraps an object and intercepts operations. 🟢 Reflect = Official Rulebook Now imagine the bodyguard has a standard protocol manual. When no special rule is needed, he simply follows the manual. 👉 That manual is Reflect Reflect provides default object operations and is commonly used inside Proxy traps to safely forward behavior. 💻 Basic Proxy Example const user = { name: "Raja" }; const proxy = new Proxy(user, { get(target, prop) { console.log(`Reading ${prop}`); return target[prop]; } }); console.log(proxy.name); ✅ Intercepts property access ✅ Adds custom behavior 💻 Proxy + Reflect (Best Practice) const user = { age: 25 }; const proxy = new Proxy(user, { set(target, prop, value) { if (prop === "age" && value < 0) { throw new Error("Invalid age"); } return Reflect.set(target, prop, value); } }); proxy.age = 30; 👉 Proxy handles logic 👉 Reflect performs the default operation Perfect combo 🔥 ⚡ Common Use Cases ✔ Validation layers ✔ Logging & debugging ✔ Access control ✔ Reactive frameworks (like Vue) ✔ Data binding ✔ API observability Proxies are widely used to intercept fundamental operations like get/set/delete. 🧠 Interview Quick Summary FeatureProxyReflectPurposeIntercept operationsPerform default operationsRoleControllerHelperUsed forCustom behaviorSafe forwardingWorks withhandler trapsstandard methods ⚠️ Pro Tips ✅ Always return true in set trap ✅ Prefer Reflect inside traps ✅ Avoid heavy proxies in hot paths (performance) ✅ Remember: Proxy wraps the target 📌 Goal: Share daily JavaScript concepts while preparing for interviews and learning in public. Next topics: Event Delegation deep dive, Web Workers, Advanced closures. Let’s keep growing consistently 🚀 #JavaScript #InterviewPreparation #Proxy #Reflect #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
here's some important JavaScript questions to crack interviews 𝟭. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗶𝘀 𝗸𝗲𝘆𝘄𝗼𝗿𝗱? - Refers to the object that is currently executing the function - In global scope, this is the window object (in browsers) - Arrow functions do not have their own this 𝟮. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗣𝗿𝗼𝘁𝗼𝘁𝘆𝗽𝗮𝗹 𝗜𝗻𝗵𝗲𝗿𝗶𝘁𝗮𝗻𝗰𝗲? - JS objects inherit properties and methods from other objects via a prototype chain - Every object has a hidden __proto__ property pointing to its prototype - ES6 class syntax is just cleaner syntax over prototypal inheritance 𝟯. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗦𝗽𝗿𝗲𝗮𝗱 𝗮𝗻𝗱 𝗥𝗲𝘀𝘁 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿 (...)? - Spread expands an array or object: const newArr = [...arr, 4, 5] - Rest collects remaining arguments into an array: function fn(a, ...rest) {} - Same syntax, different context position determines behavior - Great for copying arrays/objects without mutation 𝟰. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗗𝗲𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗶𝗻𝗴? - Extract values from arrays or objects into variables cleanly - Array: const [first, second] = [1, 2] - Object: const { name, age } = user - Supports default values: const { name = 'Guest' } = user 𝟱. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗘𝘃𝗲𝗻𝘁 𝗗𝗲𝗹𝗲𝗴𝗮𝘁𝗶𝗼𝗻? - Instead of adding listeners to each child element, add one listener to the parent - Uses event bubbling events travel up the DOM tree - More memory efficient for large lists or dynamic content - Check event.target inside the handler to identify which child was clicked 𝟲. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝗰𝗮𝗹𝗹(), 𝗮𝗽𝗽𝗹𝘆()? - All three explicitly set the value of this - call() invokes immediately, passes args one by one - apply() invokes immediately, passes args as an array 𝟳. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗠𝗲𝗺𝗼𝗶𝘇𝗮𝘁𝗶𝗼𝗻? - Caching the result of a function call so it doesn't recompute for the same input - Improves performance for expensive or repeated operations - Commonly implemented using closures and objects/Maps 𝟴. 𝗪𝗵𝗮𝘁 𝗮𝗿𝗲 𝗛𝗶𝗴𝗵𝗲𝗿-𝗢𝗿𝗱𝗲𝗿 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀? - Functions that take other functions as arguments or return them - Examples: .map(), .filter(), .reduce(), .forEach() - Core concept in functional programming with JavaScript 𝟵. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝘁𝗵𝗲 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗯𝗲𝘁𝘄𝗲𝗲𝗻 𝗗𝗲𝗲𝗽 𝗖𝗼𝗽𝘆 𝗮𝗻𝗱 𝗦𝗵𝗮𝗹𝗹𝗼𝘄 𝗖𝗼𝗽𝘆? - Shallow copy copies only the top level nested objects are still referenced - Object.assign() and spread {...obj} create shallow copies - Deep copy duplicates everything including nested levels 𝟭𝟬. 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗼𝗽𝘁𝗶𝗼𝗻𝗮𝗹 𝗰𝗵𝗮𝗶𝗻𝗶𝗻𝗴 (?.) 𝗮𝗻𝗱 𝗻𝘂𝗹𝗹𝗶𝘀𝗵 𝗰𝗼𝗮𝗹𝗲𝘀𝗰𝗶𝗻𝗴 (??)? - ?. safely accesses nested properties without throwing if something is null/undefined - user?.address?.city returns undefined instead of crashing - ?? returns the right side only if the left is null or undefined Follow the Frontend Circle By Sakshi channel on WhatsApp: https://lnkd.in/gj5dp3fm 𝗙𝗼𝗹𝗹𝗼𝘄𝘀 𝘂𝘀 𝗵𝗲𝗿𝗲 → https://lnkd.in/geqez4re
To view or add a comment, sign in
-
🚀 JavaScript Interview Prep Series — Day 18 Topic: Type Coercion in JavaScript (Implicit vs Explicit) Continuing my JavaScript interview revision journey, today I revisited one of the most confusing but commonly asked topics: 👉 Type Coercion JavaScript is loosely typed, which means it sometimes automatically converts types — and that can surprise you in interviews. ✈️ Real-World Example: Currency Converter Imagine you’re at an airport currency exchange. 🟡 Implicit Coercion (Automatic) You insert dollars into an automatic machine, and it silently converts to euros. You didn’t ask — it just happened. JavaScript sometimes does the same. 🔵 Explicit Coercion (Manual) You go to the teller and say: “Please convert this to euros.” Now the conversion is intentional and clear. 🔴 Unexpected Behavior Sometimes a weird converter gives a strange result 😅 That’s how JavaScript coercion bugs happen. 💻 Implicit Coercion Examples 5 + "5" // "55" (number → string) "10" - 5 // 5 (string → number) "5" * "2" // 10 (both → number) true + true // 2 👉 Rule of thumb: + prefers strings, other math operators prefer numbers 💻 Explicit Coercion Examples String(123) // "123" Number("456") // 456 Boolean(1) // true parseInt("42") // 42 This is the safe and recommended approach. ⚠️ Tricky Interview Questions [] + [] // "" [] + {} // "[object Object]" "5" + 3 + 2 // "532" 3 + 2 + "5" // "55" "2" == 2 // true "2" === 2 // false ✅ Golden Rules ✔ JavaScript may convert types automatically ✔ == allows coercion ✔ === prevents coercion (recommended) ✔ Be careful with + operator ✔ Prefer explicit conversion in production code ✅ Why Interviewers Ask This Because it tests: • Deep JS understanding • Edge case awareness • Debugging ability • Clean coding habits 📌 Goal: Share daily JavaScript concepts while preparing for interviews and learning in public. Next topics: Closures deep dive, Event Delegation, Memory leaks, and more. Let’s keep sharpening fundamentals 🚀 #JavaScript #InterviewPreparation #TypeCoercion #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
🚀 45 Important JavaScript Interview Questions Every Frontend Developer Should Know Preparing for JavaScript interviews? Instead of memorizing random topics, it helps to revise core concepts, async behavior, modern JavaScript features, and browser fundamentals together. Here’s a structured list of important JavaScript interview questions that frequently appear in frontend interviews 👇 🔹 Core JavaScript Fundamentals • Difference between var, let, and const • What are closures and how do they work? • Explain the this keyword in different execution contexts • What is a Promise in JavaScript? • How does the Event Loop work? • What is hoisting? • Explain different JavaScript data types • Difference between null and undefined • What is a callback function? • How do you handle errors in JavaScript? 🔹 Asynchronous JavaScript • Difference between setTimeout() and setInterval() • How do Promises manage async operations? • What do then(), catch(), and finally() do? • What is async / await and how does it simplify async code? • Advantages of async/await over callbacks • Handling multiple promises with Promise.all() • When should you use Promise.allSettled()? 🔹 Modern JavaScript (ES6+) • What are higher-order functions? • How does destructuring work? • What are template literals? • Explain the spread operator • What is the rest parameter? • Difference between arrow functions and regular functions 🔹 Objects & Arrays • Difference between objects and arrays • How do you clone an object or array? • What do Object.keys(), Object.values(), Object.entries() return? • How does Array.map() work? • Difference between map() and forEach() • Difference between filter() and reduce() 🔹 Advanced JavaScript Concepts • What is event delegation and why is it useful? • What are JavaScript modules? • Explain the prototype chain • Difference between bind(), call(), and apply() • Difference between == and === • What is currying in JavaScript? 🔹 Browser & Frontend Concepts • What is the DOM (Document Object Model)? • How does JavaScript interact with the DOM? • Difference between preventDefault() and stopPropagation() • What is an event object? • What are custom events? • How do you optimize JavaScript performance? • What is debouncing? • What is throttling? • What causes memory leaks in JavaScript? • How can you avoid memory leaks in applications? 📌 Quick Interview Tip Interviewers don’t just expect definitions. They usually look for: ✔ Clear understanding of concepts ✔ Real-world examples ✔ Ability to explain why and when to use something If you can explain these topics confidently, you already cover a large portion of JavaScript interview preparation. 💡 Save this list for quick revision before interviews. #JavaScript #FrontendDevelopment #WebDevelopment #AsyncJavaScript #FrontendInterview #Developers #InterviewPreparation 👉 Follow Rahul R Jain for more real interview insights, React fundamentals, and practical frontend engineering content.
To view or add a comment, sign in
-
Day 38/50 – JavaScript Interview Question? Question: What are JavaScript Generators and the yield keyword? Simple Answer: Generators are special functions that can pause and resume execution. They're defined with function* and use yield to return values one at a time. Each call to .next() resumes execution until the next yield or return statement. 🧠 Why it matters in real projects: Generators enable lazy evaluation (processing large datasets without loading everything into memory), implementing custom iterators, managing async flow (Redux-Saga uses generators), and creating infinite sequences efficiently. 💡 One common mistake: Forgetting that calling a generator function doesn't execute it immediately—it returns an iterator object. You must call .next() to start execution. Also, not understanding that yield can both send and receive values. 📌 Bonus: // Basic generator function* numberGenerator() { console.log('Start'); yield 1; console.log('After 1'); yield 2; console.log('After 2'); yield 3; return 'Done'; } const gen = numberGenerator(); // Doesn't execute yet! console.log(gen.next()); // { value: 1, done: false } console.log(gen.next()); // { value: 2, done: false } console.log(gen.next()); // { value: 3, done: false } console.log(gen.next()); // { value: 'Done', done: true } // Practical use cases: // 1. Infinite sequences function* fibonacci() { let [a, b] = [0, 1]; while (true) { yield a; [a, b] = [b, a + b]; } } const fib = fibonacci(); console.log(fib.next().value); // 0 console.log(fib.next().value); // 1 console.log(fib.next().value); // 1 console.log(fib.next().value); // 2 // 2. Lazy evaluation (memory efficient) function* readLargeFile(file) { for (let line of file) { yield processLine(line); // Process one line at a time } } // 3. Custom iterators function* range(start, end) { for (let i = start; i <= end; i++) { yield i; } } for (let num of range(1, 5)) { console.log(num); // 1, 2, 3, 4, 5 } // 4. Two-way communication function* twoWay() { const a = yield 'First'; console.log('Received:', a); const b = yield 'Second'; console.log('Received:', b); } const gen2 = twoWay(); gen2.next(); // { value: 'First', done: false } gen2.next('Hello'); // Logs: Received: Hello gen2.next('World'); // Logs: Received: World #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #Generators #ES6 #WebDev #InterviewPrep #AdvancedJS
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