🚀 JavaScript Interview Preparation Checklist (Frontend Developers) I’ve compiled this structured JavaScript topic list for interviews. Sharing it here so it can help others who are preparing for frontend roles. 📌 Core JavaScript Concepts • Scope (global, function, block) • Execution context • this keyword (different contexts) • Hoisting • Closures • Prototype chain • Type coercion • == vs === • Primitive vs non-primitive data types 📌 ES6 & Modules • let, const • Arrow functions • Template literals • Rest parameters • Spread operator • Object & array destructuring • Classes • Default parameters • Map, Set • for…of loop • import / export • Default exports 📌 Asynchronous JavaScript • Callbacks • Promises • Async/Await • Event Loop (call stack, microtask, macrotask) • Promise.all() • Promise.allSettled() • Promise.any() • Promise.race() 📌 Advanced Concepts • Function currying • Debouncing & throttling • Shallow copy vs deep copy • Call by value vs call by reference • Polyfills • Higher Order functions • IIFE 📌 DOM Manipulation & Events • getElementById • getElementsByClassName • getElementsByTagName • querySelector • querySelectorAll • addEventListener • removeEventListener • Event propagation • Event bubbling • Event capturing • Event delegation 📌 API Calls • fetch • axios • fetch vs axios 📌 Error Handling • try • catch • finally 📌 Web Storages • sessionStorage • localStorage • cookies • IndexedDb 📌 OOP in JavaScript • Constructor functions • Prototypes • __proto__ • this • call, apply, bind • ES6 classes • Inheritance • Polyfills 📌 Functions • Function expressions • Arrow functions • Named functions • Callback functions 📌 Loops • for • for…of • for…in • forEach • while • do…while 📌 Array Methods • map • filter • reduce • join • slice • splice • push • pop • shift • unshift • find 📌 String Methods • length • charAt • split • slice • substring 📌 Object Methods • Object.keys() • Object.values() • Object.entries() 📌 Browser APIs • JSON.parse() • JSON.stringify() • setTimeout() • setInterval() • clearTimeout() • clearInterval() • fetch() If you’re preparing for frontend or React interviews, covering these topics with practical examples will give you a strong JavaScript foundation 💡. #JavaScript #FrontendDevelopment #ReactJS #WebDevelopment #InterviewPreparation #SoftwareEngineering
JavaScript Frontend Interview Prep Checklist
More Relevant Posts
-
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 Objects – Interview Q&A (Frontend Focused) 1️⃣ What is an object in JavaScript? An object is a collection of key–value pairs used to store structured data. Keys are strings (or symbols), and values can be any data type. 2️⃣ How do you create an object in JavaScript? // Object literal const obj = { name: "JS" }; // Using constructor const obj2 = new Object(); // Using Object.create const obj3 = Object.create(null); 3️⃣ How do you access object properties? obj.name; // Dot notation obj["name"]; // Bracket notation 👉 Bracket notation is useful for dynamic keys. 4️⃣ Difference between dot notation and bracket notation? DotBracketStatic keysDynamic keysFaster & cleanerRequired for special characters 5️⃣ How do you loop through an object? for (let key in obj) { console.log(key, obj[key]); } Object.keys(obj).forEach(key => console.log(key)); 6️⃣ What are Object.keys(), Object.values(), and Object.entries()? Object.keys() → array of keys Object.values() → array of values Object.entries() → array of [key, value] 7️⃣ Are objects mutable in JavaScript? ✅ Yes. Objects are mutable and passed by reference. const a = { x: 1 }; const b = a; b.x = 2; // a.x is also 2 8️⃣ How do you clone an object? // Shallow copy const copy = { ...obj }; const copy2 = Object.assign({}, obj); ⚠️ Nested objects still share references. 9️⃣ Difference between shallow copy and deep copy? Shallow copy → Copies only first level Deep copy → Copies all nested levels const deep = JSON.parse(JSON.stringify(obj)); 🔟 What is this inside an object? this refers to the current object calling the method. const user = { name: "Sweta", greet() { return this.name; } }; 1️⃣1️⃣ What is object destructuring? const { name, role } = user; Used for cleaner code and readability. 1️⃣2️⃣ What is the difference between Object.freeze() and Object.seal()? freeze() → Cannot add, remove, or update properties seal() → Can update existing properties only 1️⃣3️⃣ How do you check if a property exists? "name" in user; user.hasOwnProperty("name"); 1️⃣4️⃣ Real-world use of objects? ✅ API responses ✅ Component props & state ✅ Configuration files ✅ Form handling ✅ State management (Redux / Pinia) 💡 Interview Tip: Strong understanding of objects helps you master immutability, state management, and performance optimization in React & Vue. 👍 Like • 💬 Comment • 🔁 Share if this helped #JavaScript #FrontendInterview #WebDevelopment #React #Vue #CodingInterview #LinkedInLearning
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
-
-
Day 35/50 – JavaScript Interview Question? Question: What is the new keyword and what happens when you use it? Simple Answer: The new keyword creates an instance of a constructor function or class. It performs four steps: creates an empty object, sets the prototype, binds this to the new object, and returns the object (unless the constructor explicitly returns another object). 🧠 Why it matters in real projects: Understanding new is fundamental to JavaScript's prototypal inheritance and OOP patterns. It's crucial when working with classes, custom data structures, and understanding how frameworks like React create component instances. 💡 One common mistake: Forgetting new when calling a constructor, causing this to refer to the global object (or undefined in strict mode) instead of creating a new instance. Also, not knowing that arrow functions can't be used as constructors. 📌 Bonus: // Constructor function function Person(name, age) { this.name = name; this.age = age; } Person.prototype.greet = function() { return `Hello, I'm ${this.name}`; }; // Using new keyword const alice = new Person('Alice', 30); // What happens behind the scenes: function Person(name, age) { // 1. const this = Object.create(Person.prototype); // 2. this.__proto__ = Person.prototype; this.name = name; // 3. Bind properties to this this.age = age; // 4. return this; (implicit) } // Common mistakes: // ✗ Forgetting new const bob = Person('Bob', 25); // undefined, this = window! console.log(window.name); // "Bob" - polluted global! // ✓ With new const charlie = new Person('Charlie', 35); // ✓ // Arrow functions can't be constructors const PersonArrow = (name) => { this.name = name; }; const dave = new PersonArrow('Dave'); // ✗ TypeError! // ES6 Classes (syntactic sugar over prototypes) class Employee extends Person { constructor(name, age, title) { super(name, age); // Must call before using this this.title = title; } } // Custom return value overrides function Custom() { this.name = 'Test'; return { custom: true }; // This is returned instead } const obj = new Custom(); console.log(obj); // { custom: true } #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews #OOP #Constructors
To view or add a comment, sign in
-
Last week, I shared 20 essential JavaScript interview questions. No textbook definitions. Just clarity. 1️⃣ Higher-Order Functions Functions that take another function as an argument or return one. Examples: map(), filter(), reduce() 👉 Shows strong functional programming fundamentals. 2️⃣ Destructuring Extract values from objects/arrays into variables. Cleaner, shorter, more readable code. 3️⃣ Template Literals Backticks ` ` allow embedding variables using ${}. Used for dynamic strings. 4️⃣ Spread vs Rest Operator Spread → Expands values Rest → Collects values Same syntax (...), different purpose. 5️⃣ Rest vs arguments Rest parameter is a real array. arguments is array-like and outdated. 👉 Prefer rest. 6️⃣ Object vs Array Object → Key-value structure Array → Ordered list Use arrays for lists, objects for structured data. 7️⃣ Cloning Objects/Arrays Use spread (...) for shallow copy. Use structuredClone() for deep copy. 8️⃣ Object.keys / values / entries Used to extract keys, values, or key-value pairs for iteration. 9️⃣ map() Transforms each element and returns a new array. 🔟 map() vs forEach() map() returns a new array. forEach() does not return anything. 👉 Use map() when transforming data. 1️⃣1️⃣ Event Delegation Attach one event listener to a parent instead of multiple children. Improves performance and scalability. 1️⃣2️⃣ JavaScript Modules Split code using export and import. Keeps projects clean and maintainable. 1️⃣3️⃣ Prototype Chain JavaScript uses prototypes for inheritance. Objects inherit properties from other objects. 1️⃣4️⃣ bind vs call vs apply All control this: • call() → arguments individually • apply() → arguments as array • bind() → returns a new function 1️⃣5️⃣ == vs === == allows type coercion. === is strict comparison. 👉 Always prefer ===. 1️⃣6️⃣ DOM The bridge between JavaScript and HTML. Used to read and manipulate webpage elements. 1️⃣7️⃣ preventDefault() & stopPropagation() Control event behavior and event bubbling. 1️⃣8️⃣ Sync vs Async Sync → Runs line by line. Async → Uses callbacks, promises, async/await. 1️⃣9️⃣ Event Object vs Custom Event Event object → Default event data. Custom event → Created manually for specific use cases. 2️⃣0️⃣ Performance Optimization • Debouncing / Throttling • Reduce unnecessary DOM updates • Lazy loading • Efficient loops Candidates don’t fail because they don’t know React. They fail because they can’t clearly explain JavaScript fundamentals. If you can explain these confidently with examples — you're interview ready. Save this. Share with someone preparing for frontend roles. Comment “Advanced JS” if you want the next level questions. #JavaScript #FrontendDeveloper #WebDevelopment #TechCareers #CodingInterview #Mentorship #SoftwareDevelopment
To view or add a comment, sign in
-
🚀 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
-
-
🤔 Preparing for your next JavaScript interview? Today, we're tackling one of the most crucial and misunderstood concepts in JavaScript: The Event Loop. JavaScript is single-threaded, meaning it has only one "Call Stack" and can only do one thing at a time. So, how does it handle time-consuming operations like API calls (fetch) or timers (setTimeout) without freezing the entire browser? The answer is that the JavaScript engine doesn't work alone. It gets help from the browser environment and a manager called the Event Loop. Here’s the complete system in a nutshell: 1. The Call Stack: This is where your JavaScript code is executed, one line at a time. 2. Web APIs: These are features provided by the browser (not the JS engine). When your code calls a slow operation like setTimeout, the JS engine hands it off to the Web API to handle in the background. The engine then immediately moves on to the next line of code, keeping the Call Stack free. 3.The Callback Queue (or Task Queue): Once the Web API finishes its job (the timer completes, the data arrives), it doesn't interrupt your code. Instead, it places the function you provided (the "callback") into this waiting line. This brings us to the final, critical piece. How does the function get from the waiting line back into the main code to be run? ✅ Enter the Event Loop: The Event Loop is a simple, constantly running process with one golden rule: "If the Call Stack is empty, take the first item from the Callback Queue and push it onto the Call Stack to be executed." ``` console.log('First'); setTimeout(() => { console.log('Second'); }, 0); console.log('Third'); // Output: First, Third, Second ``` Why this order? 1. `console.log('First')` goes to the Call Stack and runs. 2. `setTimeout` is handed to a Web API. JavaScript immediately continues. 3. `console.log('Third')` goes to the Call Stack and runs. 4. The `Call Stack` is now empty. 5. In the background, the timer finishes instantly (0ms) and places its callback `() => console.log('Second')` into the Callback Queue. 6. The Event Loop sees the Call Stack is empty, takes the callback from the queue, and pushes it onto the stack to run. This system is what makes JavaScript "non-blocking." The Event Loop ensures that slow tasks wait their turn without ever freezing the user interface. #javascript #eventloop #asynchronousjavascript #webdevelopment #frontenddevelopment #backenddevelopment #nodejs #v8engine #callstack #microtasks
To view or add a comment, sign in
-
-
🚀 JavaScript Interview Questions & Real-World System Design Insights Recently, I was preparing for backend/full-stack interviews and thought of sharing some commonly asked JavaScript + system design questions with practical answers 👇 🟢 1️⃣ Function to Capitalize Each Word in a Sentence Question: Write a function to capitalize every word in a sentence. Answer: function capitalizeSentence(sentence) { return sentence .split(" ") .map(word => word.charAt(0).toUpperCase() + word.slice(1)) .join(" "); } console.log(capitalizeSentence("hello world from javascript")); // Output: Hello World From Javascript 💡 Interview Tip: Ask about edge cases (multiple spaces, empty string, special characters). Mention immutability and time complexity → O(n) 🟢 2️⃣ Function to Find Missing Number Question: Find the missing number in an array from 1 to n. Example: [1,2,3,5] → Missing number = 4 Answer (Using Sum Formula - Optimized O(n)): function findMissingNumber(arr, n) { const expectedSum = (n * (n + 1)) / 2; const actualSum = arr.reduce((sum, num) => sum + num, 0); return expectedSum - actualSum; } console.log(findMissingNumber([1,2,3,5], 5)); // Output: 4 💡 Follow-up they might ask: What if array is unsorted? What if there are duplicates? Can you solve using XOR? 🌍 Real-World Backend/System Design Questions 🟠 3️⃣ What About Security If Anyone (Even Bots) Can Hit Your Website? This is a very practical production question. ✅ Solutions you should mention: Rate Limiting (e.g., Redis-based limiter) CAPTCHA for public forms WAF (Web Application Firewall) Input validation & sanitization JWT authentication & role-based authorization API throttling DDoS protection (Cloudflare/AWS Shield) 💡 Bonus Point: Explain difference between Authentication vs Authorization. 🟠 4️⃣ How Do We Scale If We Don’t Know How Traffic Will Increase? This tests architecture thinking. ✅ Smart answer: Horizontal scaling (multiple instances) Load balancer (Nginx / cloud LB) Stateless servers Caching layer (Redis) Database indexing + read replicas Auto-scaling groups (cloud-based scaling) Queue systems for heavy jobs (Kafka/RabbitMQ) 💡 Golden Line for Interview: “Design for scalability from day one, even if traffic is low.” 🔥 Interviews today are not just about syntax. They test: Problem-solving System thinking Production mindset Edge cases awareness If you're preparing for JavaScript / Node.js / Full Stack interviews, focus on both coding + architecture. Let me know if you want more real interview Q&A posts 👇 #JavaScript #NodeJS #FullStackDeveloper #FrontendDeveloper #BackendDeveloper #WebDevelopment #CodingInterview #TechInterview #SystemDesign #Scalability #WebSecurity #SoftwareEngineering #DeveloperLife
To view or add a comment, sign in
-
🚀 JavaScript Interview Prep Series — Day 16 Topic: Map, Set & WeakMap in JavaScript Continuing my JavaScript interview revision journey, today I focused on modern JavaScript data structures: 👉 Map, Set, and WeakMap These are powerful alternatives to traditional objects and arrays for managing data efficiently. 🏨 Real-World Example 1️⃣ Map — Hotel Reception System At a hotel reception: Room number acts as a key Guest information is the value Receptionist can quickly fetch guest info using the room number. Similarly, Map stores key-value pairs, and keys can be any data type. 2️⃣ Set — VIP Guest List At a club entrance: Each guest name can appear only once Duplicate entries are rejected Set works the same way — it stores only unique values. 3️⃣ WeakMap — Temporary Visitor Badges Visitors receive temporary badges: Once they leave, badges become invalid automatically System cleans up unused badges WeakMap automatically removes entries when keys (objects) are no longer referenced. 💻 Practical JavaScript Examples Map Example const guestMap = new Map(); guestMap.set("room101", "John"); guestMap.set("room102", "Alice"); console.log(guestMap.get("room101")); console.log(guestMap.size); Set Example const guests = new Set(); guests.add("John"); guests.add("Alice"); guests.add("John"); // ignored console.log(guests); WeakMap Example const cache = new WeakMap(); let user = { name: "Raja" }; cache.set(user, "Session data"); user = null; // automatically cleanes ✅ Why Interviewers Ask This Because it tests: • Knowledge of modern JS features • Efficient data handling • Memory management concepts • Choosing correct data structure 📌 Goal: Share daily JavaScript concepts while revising fundamentals and learning in public. Next topics: WeakSet, Event Delegation, Deep Copy vs Shallow Copy, and more. Let’s keep learning consistently 🚀 #JavaScript #InterviewPreparation #Map #Set #WeakMap #Frontend #WebDevelopment #LearningInPublic #Developers #CodingJourney
To view or add a comment, sign in
-
-
Day 43/50 – JavaScript Interview Question? Question: What is Event Loop, Call Stack, and Task Queue in JavaScript? Simple Answer: The Call Stack tracks function execution (LIFO). The Task Queue (Callback Queue) holds callbacks from async operations. The Event Loop continuously checks if the Call Stack is empty, then moves tasks from the queue to the stack. Microtasks (Promises) have priority over Macrotasks (setTimeout). 🧠 Why it matters in real projects: Understanding the Event Loop is crucial for debugging async behavior, preventing UI blocking, and optimizing performance. It explains why promises execute before setTimeout(0), and helps you write non-blocking code in a single-threaded environment. 💡 One common mistake: Not understanding microtask vs macrotask priority, leading to unexpected execution order. Also, creating infinite microtask loops that starve the macrotask queue and freeze the UI. 📌 Bonus: // Example demonstrating execution order console.log('1: Sync Start'); setTimeout(() => { console.log('2: setTimeout (Macrotask)'); }, 0); Promise.resolve().then(() => { console.log('3: Promise 1 (Microtask)'); }).then(() => { console.log('4: Promise 2 (Microtask)'); }); console.log('5: Sync End'); // Output: // 1: Sync Start // 5: Sync End // 3: Promise 1 (Microtask) // 4: Promise 2 (Microtask) // 2: setTimeout (Macrotask) // Event Loop phases: // 1. Execute all synchronous code // 2. Execute all microtasks (Promises, queueMicrotask) // 3. Execute one macrotask (setTimeout, setInterval, I/O) // 4. Repeat // Call Stack visualization function first() { console.log('First'); second(); console.log('First again'); } function second() { console.log('Second'); third(); } function third() { console.log('Third'); } first(); // Stack: [first] → [first, second] → [first, second, third] // Output: First, Second, Third, First again // Microtask vs Macrotask setTimeout(() => console.log('Macro 1'), 0); Promise.resolve() .then(() => { console.log('Micro 1'); Promise.resolve().then(() => console.log('Micro 2')); }) .then(() => console.log('Micro 3')); setTimeout(() => console.log('Macro 2'), 0); // Output: Micro 1, Micro 2, Micro 3, Macro 1, Macro 2 // All microtasks complete before next macrotask! // Blocking the Event Loop (BAD!) function blockingOperation() { const start = Date.now(); while (Date.now() - start < 3000) { // Blocks for 3 seconds - UI freezes! } } // Better: Break into chunks async function nonBlockingOperation() { for (let i = 0; i < 1000; i++) { // Do work... if (i % 100 === 0) { await new Promise(resolve => setTimeout(resolve, 0)); // Yields to Event Loop every 100 iterations } } } // Microtask starvation (infinite loop) function starveEventLoop() { Promise.resolve().then(() => { starveEventLoop(); // Creates endless microtasks! // Macrotasks never run - UI freezes }); }
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