Interview Question: What is a Closure in JavaScript? - A closure is created when a function remembers and accesses variables from its outer (lexical) scope, even after the outer function has finished executing. In simple words: A function + its outer scope = Closure ● Example of Closure : function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } const fn = outer(); fn(); // 1 fn(); // 2 -> inner() remembers count even after outer() is done. ● Why Closures are Useful? - Data hiding / encapsulation - Maintaining state - Callback functions - Event handlers • Interview Tip: Closures are possible because JavaScript uses lexical scoping, not dynamic scoping. #JavaScript #InterviewPrep #Closures #WebDevelopment #Frontend #MERN #LearnInPublic #CodingJourney #Backend #30DaysOfJavaScript #Backend #BDRM #BackendDevWithRahulMaheshwari
JavaScript Closure Definition and Use Cases
More Relevant Posts
-
#javascript Array.map() feels obvious when you use it. It doesn’t feel obvious when you try to write it. While implementing it from scratch, a few things became very clear: • map() always creates a new array Touching the original one means it’s wrong. • You can’t assume all indexes exist Sparse arrays force you to check before reading values. • The loop is not the important part The callback is what shapes the result. • thisArg affects real behavior Ignoring it breaks how map() is expected to work. • The callback gets more than just the value Index and array access enable many real-world use cases. The implementation is small. The thinking behind it isn’t. This is exactly why Array.map() is asked in JavaScript interviews. 📺 I’ve broken this down step-by-step in my JavaScript Interview Series on YouTube Link is in the first comment If you’ve never written map() yourself, it’s worth doing once. #JavaScript #JavaScriptInterview #FrontendDevelopment #ArrayMethods
To view or add a comment, sign in
-
🤔JavaScript behaves differently with values depending on what you’re working with and this trips up a lot of interview answers. 🧠 JavaScript interview question What is the difference between primitive and reference types? ✅ Short answer • Primitives are copied by value • Objects are copied by reference • Equality checks references, not structure 🔍 A bit more detail • Primitive types number, string, boolean, null, undefined, symbol, bigint Stored as values Assigning or passing them creates a copy • Reference types objects, arrays, functions Variables store a reference to the same object Mutating through one reference affects all others • Equality {} === {} is false Same shape does not mean same reference 💻 Example // primitive copy let a = 5 let b = a b = 7 console.log(a) // 5 // reference copy const p = { n: 1 } const q = p q.n = 2 console.log(p.n) // 2 ⚠️ Small but important detail JavaScript always passes arguments by value. For objects, that value is the reference. Reassigning a parameter does nothing. Mutating the object does. I’m sharing one JavaScript interview-style question per day to build calm, solid fundamentals step by step. #javascript #frontend #interviewprep #webdevelopment
To view or add a comment, sign in
-
Controlling `this` in JavaScript: Call vs. Apply vs. Bind. 🎮 One of the most common interview questions for mid-level developers is: "𝑊ℎ𝑎𝑡 𝑖𝑠 𝑡ℎ𝑒 𝑑𝑖𝑓𝑓𝑒𝑟𝑒𝑛𝑐𝑒 𝑏𝑒𝑡𝑤𝑒𝑒𝑛 𝐶𝑎𝑙𝑙, 𝐵𝑖𝑛𝑑, 𝑎𝑛𝑑 𝐴𝑝𝑝𝑙𝑦?" They all do the same core job: They allow you to manually set what `this` refers to inside a function. But they do it in slightly different ways. 𝐇𝐞𝐫𝐞 𝐢𝐬 𝐭𝐡𝐞 𝟏𝟎-𝐬𝐞𝐜𝐨𝐧𝐝 𝐛𝐫𝐞𝐚𝐤𝐝𝐨𝐰𝐧: 1️⃣ 𝐂𝐚𝐥𝐥 & 𝐀𝐩𝐩𝐥𝐲 (𝐓𝐡𝐞 𝐈𝐦𝐦𝐞𝐝𝐢𝐚𝐭𝐞 𝐈𝐧𝐯𝐨𝐤𝐞𝐫𝐬) Both of these execute the function 𝑖𝑚𝑚𝑒𝑑𝑖𝑎𝑡𝑒𝑙𝑦. The only difference is how they handle arguments. • 𝐂𝐚𝐥𝐥: Passes arguments individually (comma-separated). • 𝑀𝑛𝑒𝑚𝑜𝑛𝑖𝑐: 𝐂all = 𝐂ommas. • 𝐀𝐩𝐩𝐥𝐲: Passes arguments as a single Array. • 𝑀𝑛𝑒𝑚𝑜𝑛𝑖𝑐: 𝐀pply = 𝐀rray. 2️⃣ 𝐁𝐢𝐧𝐝 (𝐓𝐡𝐞 𝐏𝐥𝐚𝐧𝐧𝐞𝐫) • 𝐁𝐢𝐧𝐝: Does NOT execute the function immediately. • Instead, it returns a 𝐧𝐞𝐰 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐜𝐨𝐩𝐲 with the `this` context permanently locked (bound) to the object you specified. You can then call this new function whenever you want later. 𝐖𝐡𝐲 𝐢𝐬 𝐭𝐡𝐢𝐬 𝐮𝐬𝐞𝐟𝐮𝐥? It allows "Method Borrowing." You can use a method from one object (like a helper function) and use it on a completely different object, just by changing the `this` context! Check out the syntax comparison below! 👇 Which one do you use most often? I find `bind` essential for passing methods into React components or event listeners! #JavaScript #WebDevelopment #CodingInterviews #SoftwareEngineering #Frontend #JSConcepts
To view or add a comment, sign in
-
-
● Interview Question: What are Promises in JavaScript? - A Promise is an object that represents the eventual completion or failure of an asynchronous operation. - It helps handle async code without callback hell. ● Promise States A Promise can be in one of three states: - Pending – Initial state - Fulfilled – Operation completed successfully - Rejected – Operation failed ● Creating Promise const promise = new Promise((resolve, reject) => { let success = true; if (success) { resolve("Task completed"); } else { reject("Task failed"); } }); ● Consuming Promise promise .then(result => console.log(result)) .catch(error => console.log(error)) .finally(() => console.log("Done")); where :- .then() -> handles success .catch() -> handles errors .finally() -> always executes Promises make async code readable and manageable #JavaScript #Promises #AsyncJavaScript #InterviewPrep #WebDevelopment #Frontend #MERN #LearnInPublic #CodingJourney #30DaysOfJavaScript #Backend #BDRM #BackendDevWithRahulMaheshwari
To view or add a comment, sign in
-
-
🚀 Js Interview Trap Most Developers Fall Into ❌ “JavaScript is single-threaded, so it runs one thing at a time.” Sounds correct… but it’s incomplete. Let’s fix that 👇 🧠 How JavaScript ACTUALLY works: JavaScript runs on a single thread, but it can still handle async tasks efficiently using: ✅ Call Stack ✅ Web APIs (setTimeout, fetch, DOM events) ✅ Callback Queue / Microtask Queue ✅ Event Loop ⚡ Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); 📝 Output: Start End Promise Timeout ❓ Why? Promise.then → Microtask Queue (higher priority) setTimeout → Callback Queue Event Loop executes microtasks first 🎯 Interview takeaway: JavaScript is single-threaded, but non-blocking because of the event loop + async architecture. If this explanation helped you, 👍 #JavaScript #Frontend #WebDevelopment #ReactJS #InterviewPrep #100DaysOfCode
To view or add a comment, sign in
-
𝗜𝗳 𝗬𝗼𝘂 𝗞𝗻𝗼𝘄 𝗧𝗵𝗲𝘀𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗖𝗼𝗻𝗰𝗲𝗽𝘁𝘀, 𝗬𝗼𝘂’𝗿𝗲 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄-𝗥𝗲𝗮𝗱𝘆 JavaScript interviews don’t test frameworks — they test fundamentals. If you truly understand these important JavaScript concepts, you can: • Write cleaner, predictable code • Debug faster • Perform better in frontend & full-stack interviews This guide focuses on real interview-relevant JavaScript topics that every developer should master before aiming for product-based companies. Concepts Covered (Optional Add-On) • Execution Context & Call Stack • Hoisting & Scope • this, call, apply, bind • Closures & Lexical Environment • Event Loop & Async JavaScript • Promises, async/await • Debouncing & Throttling • Prototypal Inheritance • Deep vs Shallow Copy • Memory Management & Garbage Collection #JavaScript #FrontendDevelopment #JavaScriptConcepts #WebDevelopment #FrontendInterviews
To view or add a comment, sign in
-
🔹 JavaScript Interview Classic: var vs let inside setTimeout At first glance, both loops look identical. But the output tells a completely different story. 🔸 Output var: 5 var: 5 var: 5 var: 5 var: 5 let: 0 let: 1 let: 2 let: 3 let: 4 🔹 Why does this happen? 👉 var is function-scoped, not block-scoped. 💠 There is only one i variable shared across all iterations. 💠 By the time setTimeout executes (after 1 second), the loop has already completed. 💠 Final value of i is 5, so every callback logs 5. 👉 let is block-scoped. 💠 Each loop iteration gets its own copy of i. 💠 setTimeout remembers the correct value for each iteration. 💠 Result: 0 → 4, as expected. 🔹 Key Takeaways (Interview Gold) ✅ var → shared memory, unexpected async behavior ✅ let → block scope, predictable results ✅ Closures capture variables, not values ✅ Prefer let in loops, especially with async code If you ever see repeated values in async JavaScript logs, check variable scope first — not the logic. #JavaScript #WebDevelopment #Closures #AsyncJS #Frontend #InterviewPrep
To view or add a comment, sign in
-
-
🤔 Closures exist because JavaScript remembers where a function was created, not just where it’s called. That single rule explains a lot of “magic” behavior in JS. 🧠 JavaScript interview question What is a closure? ✅ Short answer • A closure is a function plus its lexical environment (function and it's "backpack" or COVE -> Closed Over Variable Environment) • It remembers variables from its outer scope • Those variables stay alive even after the outer function finishes 🔍 A bit more detail • JavaScript uses lexical scope • Inner functions can access variables from where they were defined • Closures keep references to variables, not copies • That’s why values can change over time 💻 Example function makeCounter() { let count = 0; return function () { count++; return count; }; } const counter = makeCounter(); counter(); // 1 counter(); // 2 counter(); // 3 ⚠️ Small but important detail Closures don’t freeze values. They hold live links to variables. That’s why let works correctly in loops with async code, and var often surprises people. 👋 I’m sharing one JavaScript interview-style concept every day to build intuition, not just memorize rules. #javascript #frontend #webdevelopment #interviewprep #learning
To view or add a comment, sign in
-
Day 1/50 – JavaScript Interview Question? Question: What is the Temporal Dead Zone (TDZ) in JavaScript? Simple Answer: The Temporal Dead Zone is the period between entering a scope and the actual declaration of a let or const variable, during which the variable cannot be accessed. 🧠 Why it matters in real projects: Understanding TDZ helps you avoid ReferenceError bugs in your applications. Unlike var which returns undefined when accessed before declaration, let and const throw errors, making your code more predictable and easier to debug. 💡 One common mistake: Assuming that because let and const are "hoisted" like var, they can be accessed before their declaration. They are hoisted, but remain uninitialized in the TDZ. 📌 Bonus: console.log(myVar); // undefined console.log(myLet); // ReferenceError: Cannot access before initialization var myVar = 1; let myLet = 2; #JavaScript #WebDevelopment #Frontend #LearnInPublic
To view or add a comment, sign in
-
Your JavaScript code might be leaking memory… and you don’t even know it ⚠️ Closures are powerful, but they come with a hidden cost. When a closure captures its scope, the garbage collector can’t free anything in that scope, even variables the closure never touches. One tiny function can accidentally keep huge objects alive forever. That’s how silent memory leaks are born. If you want to write efficient JavaScript and sound confident in front end interviews, this is non-negotiable knowledge. 👉 Level up your memory management, and learn the patterns interviewers love. Check out GFE to master advanced JavaScript concepts that actually matter. https://lnkd.in/gY-cAPfx #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #greatfrontend
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