💡 JavaScript Interview Question: Closure & Hoisting Interviewers often ask this question to test understanding of closures and variable scope. for (var i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 0); } 👉 Output 3 3 3 Reason: `var` is **function-scoped**, so all callbacks share the same variable `i`. By the time `setTimeout` executes, the loop has already finished and `i` becomes `3`. --- ### Common Fix Most candidates change `var` to `let`: for (let i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 0); } 👉 Output 0 1 2 This works because `let` is **block-scoped**, creating a new `i` for each iteration. ### The Real Twist Sometimes the interviewer says: **“You cannot use `let`.”** In that case, we can create a new scope using a function. function logger(i) { setTimeout(() => { console.log(i); }, 0); } for (var i = 0; i < 3; i++) { logger(i); } 👉 Output 0 1 2 Each call to `logger(i)` creates a new scope and preserves the value of `i` using **closure**. If you got it, give a thumbs up! #javascript #frontend #elsecoder
JavaScript Closure & Hoisting: Understanding Variable Scope
More Relevant Posts
-
Excited to share my latest blog post: 𝗦𝘁𝗿𝗶𝗻𝗴 𝗣𝗼𝗹𝘆𝗳𝗶𝗹𝗹𝘀 𝗮𝗻𝗱 𝗖𝗼𝗺𝗺𝗼𝗻 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗠𝗲𝘁𝗵𝗼𝗱𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 I’ve broken down the most important string polyfills along with the frequently asked methods that keep showing up in technical interviews. Whether you’re prepping for your next round or just want to strengthen your JS fundamentals, this should help! Read it here: https://lnkd.in/gWkfu766 Hitesh Choudhary Piyush Garg Anirudh J. Akash Kadlag Chai Aur Code Jay Kadlag Nikhil Rathore Suraj Kumar Jha Would love to hear your feedback or any other interview tips you swear by! Drop them in the comments 👇 #JavaScript #WebDevelopment #CodingInterviews #Polyfills #ChaiCode #Cohort
To view or add a comment, sign in
-
💡 JavaScript Interview Question: Promise.all() vs Promise.allSettled() While preparing for frontend interviews, one question that often comes up is: 👉 What is the difference between Promise.all() and Promise.allSettled()? Here is a simple way to explain it in interviews. 🔹 Promise.all() Promise.all() takes multiple promises and runs them in parallel. It resolves only when all promises are successful. If any one promise fails, the entire Promise.all() fails immediately. 📌 Example const p1 = Promise.resolve("API 1 success"); const p2 = Promise.resolve("API 2 success"); const p3 = Promise.reject("API 3 failed"); Promise.all([p1, p2, p3]) .then(res => console.log(res)) .catch(err => console.log("Error:", err)); Output: Error: API 3 failed ✔️ When to use: When all results are required to proceed. Example: Loading multiple dependencies before rendering a page. 🔹 Promise.allSettled() Promise.allSettled() waits for all promises to complete, regardless of success or failure. It returns the status of each promise (fulfilled or rejected). 📌 Example Promise.allSettled([p1, p2, p3]).then(res => console.log(res)); Output: [ { status: "fulfilled", value: "API 1 success" }, { status: "fulfilled", value: "API 2 success" }, { status: "rejected", reason: "API 3 failed" } ] ✔️ When to use: When you want results from all APIs even if some fail. Example: Dashboard widgets where each API is independent. 🎯 How I answer this in interviews Promise.all() → fails fast if any promise fails. Promise.allSettled() → waits for all promises and returns each result. 💬 Follow-up interview question "What if you want successful responses even when some APIs fail?" Answer: Use Promise.allSettled() and filter fulfilled results. const results = await Promise.allSettled(promises); const success = results .filter(r => r.status === "fulfilled") .map(r => r.value); Understanding these small JavaScript concepts deeply can make a big difference in frontend interviews. #javascript #reactjs #frontenddeveloper #webdevelopment #interviewprep #mernstack
To view or add a comment, sign in
-
React.js Interview Preparation Mode : Today, I stepped up the level and practiced a real interview-style problem Build a Search Filter (Debounced Input) — a common pattern asked in product-based companies. Problem Statement Create a search box that filters a list of users efficiently (avoid unnecessary re-renders & API calls). Optimized Solution (Debouncing + useEffect) import React, { useState, useEffect } from "react"; const usersData = ["Alice", "Bob", "Charlie", "David", "Eve"]; function SearchFilter() { const [search, setSearch] = useState(""); const [filtered, setFiltered] = useState(usersData); useEffect(() => { const timer = setTimeout(() => { const result = usersData.filter((user) => user.toLowerCase().includes(search.toLowerCase()) ); setFiltered(result); }, 500); // Debounce delay return () => clearTimeout(timer); }, [search]); return ( <div> <input type="text" placeholder="Search user..." value={search} onChange={(e) => setSearch(e.target.value)} /> <ul> {filtered.map((user, index) => ( <li key={index}>{user}</li> ))} </ul> </div> ); } export default SearchFilter; --- FAANG Interview Concepts Covered: - Debouncing (Performance Optimization) - useEffect Cleanup Function - Controlled Components - Efficient Rendering Follow-up Questions (Asked in Interviews): - How will you handle API-based search instead of static data? - Difference between Debouncing vs Throttling? - How to optimize this for large datasets? - How will you avoid unnecessary re-renders? Key Takeaway: In interviews, optimization matters more than just working code. Think like a product engineer, not just a coder. #ReactJS #FAANGPreparation #FrontendInterview #WebDevelopment #JavaScript #100DaysOfCode
To view or add a comment, sign in
-
⚡ Frontend Interview Cheat Sheet (Last-Minute Revision | Mid-Level) Got an interview in a few hours? This is your high-impact revision guide — not fluff, just what actually gets asked. Save it. Skim it. Walk in sharp. 💪 🧠 JavaScript Essentials (Core Thinking Area) 🔹 Closures → Function retains access to its lexical scope even after execution 👉 Used in: data privacy, currying, memoization 🔹 Event Loop → Handles async execution Call Stack → executes sync code Microtasks → Promises (then, catch) Macrotasks → setTimeout, setInterval 👉 Microtasks run before macrotasks 🔹 this keyword Depends on how function is called Arrow functions → no own this (inherits from parent) 🔹 Prototypes & Inheritance JS uses prototypal inheritance, not classical Objects can inherit properties via __proto__ 🔹 Async Patterns Callbacks → Promises → Async/Await Always handle errors (try/catch or .catch) 🔹 Debounce vs Throttle Debounce → wait for inactivity (search input) Throttle → limit frequency (scroll events) ⚛️ React Deep Recall (Most Asked Section) 🔹 Rendering Flow 👉 State/props change → Virtual DOM → Diffing → Reconciliation → DOM update 🔹 useEffect Mastery Runs after render Dependency array controls execution Cleanup function prevents memory leaks 🔹 Re-renders (CRITICAL) Caused by: State changes Parent re-renders 👉 Optimize using React.memo, useMemo, useCallback 🔹 State Management Thinking Local state vs global state (Context/Redux) Lift state up when multiple components need it 🔹 Controlled vs Uncontrolled Controlled → React manages form state Uncontrolled → DOM manages state (refs) 🔹 Common Pitfall 👉 Updating state is async — don’t rely on immediate value 🌐 Browser & Performance (Where You Stand Out) 🔹 What happens when you type a URL? DNS → TCP handshake → HTTP request → Server → Response → Rendering 🔹 Rendering Optimization Minimize reflows & repaints Avoid large DOM trees Use requestAnimationFrame for animations 🔹 Storage localStorage → persistent sessionStorage → per tab Cookies → sent with every request 🔹 CORS Browser security policy Controlled via server headers 🔹 Performance Techniques Lazy loading (images/components) Code splitting (dynamic import) Tree shaking CDN usage 🎨 HTML & CSS (Don’t Underestimate) 🔹 Box Model → content + padding + border + margin 🔹 Flexbox vs Grid Flexbox → 1D layouts (row/column) Grid → 2D layouts (rows + columns) 🔹 Positioning relative, absolute, fixed, sticky → know differences 🔹 Specificity Order Inline > ID > Class > Element 🔹 Display Differences display: none → removes from layout visibility: hidden → keeps space 🔹 Accessibility (A11y) 👉 Semantic tags, alt text, keyboard navigation #FrontendDevelopment #JavaScript #ReactJS #InterviewPrep #WebDevelopment #SoftwareEngineering #Developers #TechCareers #CodingInterview #CareerGrowth #FrontendEngineer
To view or add a comment, sign in
-
⚡ Frontend Interview Cheat Sheet (Last-Minute Revision | Mid-Level) Got an interview in a few hours? This is your high-impact revision guide — not fluff, just what actually gets asked. Save it. Skim it. Walk in sharp. 💪 🧠 JavaScript Essentials (Core Thinking Area) 🔹 Closures → Function retains access to its lexical scope even after execution 👉 Used in: data privacy, currying, memoization 🔹 Event Loop → Handles async execution Call Stack → executes sync code Microtasks → Promises (then, catch) Macrotasks → setTimeout, setInterval 👉 Microtasks run before macrotasks 🔹 this keyword Depends on how function is called Arrow functions → no own this (inherits from parent) 🔹 Prototypes & Inheritance JS uses prototypal inheritance, not classical Objects can inherit properties via __proto__ 🔹 Async Patterns Callbacks → Promises → Async/Await Always handle errors (try/catch or .catch) 🔹 Debounce vs Throttle Debounce → wait for inactivity (search input) Throttle → limit frequency (scroll events) ⚛️ React Deep Recall (Most Asked Section) 🔹 Rendering Flow 👉 State/props change → Virtual DOM → Diffing → Reconciliation → DOM update 🔹 useEffect Mastery Runs after render Dependency array controls execution Cleanup function prevents memory leaks 🔹 Re-renders (CRITICAL) Caused by: State changes Parent re-renders 👉 Optimize using React.memo, useMemo, useCallback 🔹 State Management Thinking Local state vs global state (Context/Redux) Lift state up when multiple components need it 🔹 Controlled vs Uncontrolled Controlled → React manages form state Uncontrolled → DOM manages state (refs) 🔹 Common Pitfall 👉 Updating state is async — don’t rely on immediate value 🌐 Browser & Performance (Where You Stand Out) 🔹 What happens when you type a URL? DNS → TCP handshake → HTTP request → Server → Response → Rendering 🔹 Rendering Optimization Minimize reflows & repaints Avoid large DOM trees Use requestAnimationFrame for animations 🔹 Storage localStorage → persistent sessionStorage → per tab Cookies → sent with every request 🔹 CORS Browser security policy Controlled via server headers 🔹 Performance Techniques Lazy loading (images/components) Code splitting (dynamic import) Tree shaking CDN usage 🎨 HTML & CSS (Don’t Underestimate) 🔹 Box Model → content + padding + border + margin 🔹 Flexbox vs Grid Flexbox → 1D layouts (row/column) Grid → 2D layouts (rows + columns) 🔹 Positioning relative, absolute, fixed, sticky → know differences 🔹 Specificity Order Inline > ID > Class > Element 🔹 Display Differences display: none → removes from layout visibility: hidden → keeps space 🔹 Accessibility (A11y) 👉 Semantic tags, alt text, keyboard navigation #FrontendDevelopment #JavaScript #ReactJS #InterviewPrep #WebDevelopment #SoftwareEngineering #Developers #TechCareers #CodingInterview #CareerGrowth #FrontendEngineer
To view or add a comment, sign in
-
🚀 10 JavaScript Interview Questions Every Developer Should Know While preparing for frontend interviews, I noticed one thing: Most companies don’t ask very advanced JavaScript. They ask simple-looking questions that test how well you understand the basics. Here are some of the most common JavaScript interview questions: 1️⃣ What is the difference between var, let, and const? 2️⃣ What is the difference between == and === ? 3️⃣ What is a closure in JavaScript? 4️⃣ What is hoisting? 5️⃣ What is the difference between null and undefined? 6️⃣ What is the difference between synchronous and asynchronous code? 7️⃣ What is the event loop in JavaScript? 8️⃣ What is the difference between map(), filter(), and reduce()? 9️⃣ What is the difference between function declaration and arrow function? 🔟 What is the difference between call(), apply(), and bind()? The interesting thing is: These questions look simple. But in interviews, companies usually ask deeper follow-up questions after them. Because they want to know: > Do you only know the answer… > Or do you really understand JavaScript? 💬 Which JavaScript question do you find the most difficult? #JavaScript #webdevelopment #frontend #developers #interviewquestions #coding #learning
To view or add a comment, sign in
-
Top 20 JavaScript Interview Questions in 2026 If you’re preparing for frontend or full-stack roles, this is what you should focus on. No outdated theory only what interviewers are actually asking. 1. What is the difference between var, let, and const → Scope, hoisting, reassignment 2. What is closure in JavaScript → Function + its lexical scope → Used in data hiding and callbacks 3. What is event delegation → Handling events at parent level instead of multiple children → Improves performance 4. What is the difference between == and === → == checks value → === checks value + type 5. What is hoisting → Variables and functions are moved to the top of their scope 6. What is the event loop → Handles async operations in JavaScript → Works with call stack and callback queue 7. What are promises → Handle asynchronous operations → States: pending, fulfilled, rejected 8. What is async/await → Cleaner way to handle promises → Makes async code look synchronous 9. What is the difference between null and undefined → undefined = variable declared but not assigned → null = intentionally empty value 10. What is this keyword → Refers to the current object context → Changes based on how function is called 11. What is arrow function → Short syntax → Does not have its own this 12. What is destructuring → Extract values from arrays or objects 13. What is spread and rest operator → Spread expands values → Rest collects values 14. What is callback function → Function passed as argument to another function 15. What is debouncing and throttling → Used to control function execution → Improves performance in events 16. What is localStorage and sessionStorage → Store data in browser → localStorage = permanent → sessionStorage = per session 17. What is DOM → Document Object Model → Represents HTML as objects 18. What is prototype in JavaScript → Mechanism for inheritance 19. What is module in JavaScript → Used to split code into reusable files 20. What is fetch API → Used to make HTTP requests Pro Tip → Don’t just memorize answers → Practice explaining with examples → Interviewers test clarity, not definitions If you want Comment JS → I’ll share detailed answers → Real interview questions → Mini preparation roadmap
To view or add a comment, sign in
-
💡 JavaScript Interview Question: What is a Closure? Closures are one of the most powerful concepts in JavaScript, but many developers struggle to explain them clearly in interviews. Let’s simplify it. 🔹 Definition A closure happens when a function remembers variables from its outer scope, even after the outer function has finished executing. In simple words: A function keeps access to the variables where it was created. 🔹 Example function outer() { let counter = 0; return function inner() { counter++; console.log(counter); }; } const increment = outer(); increment(); // 1 increment(); // 2 increment(); // 3 ✔ inner() still accesses counter ✔ Even though outer() has already finished That’s Closure. 🔹 Why Closures are Useful Closures help in: ✔ Data privacy (private variables) ✔ Creating function factories ✔ Callbacks and event handlers ✔ State management 📌 Interview Tip If asked in an interview, you can answer like this: A closure is a function that remembers variables from its lexical scope even when the outer function has already executed. #JavaScript #FrontendDevelopment #WebDevelopment #Angular #CodingInterview #Developers
To view or add a comment, sign in
-
-
🚀 React Interview Series | Day 8: Lazy Initializer ❓ What is a Lazy Initializer in React? 👉 In React, a lazy initializer is a way to initialize state using a function, so that the computation runs only once during the initial render. ❓ How do you normally initialize state? const [count, setCount] = useState(expensiveFunction()); 👉 Problem: expensiveFunction() runs on every render, even though state is set only once. ❓ What is the optimized (lazy) way? const [count, setCount] = useState(() => expensiveFunction()); 👉 React will: Call the function only once (initial render) Store the result as state Skip execution on re-renders ❓ Why should we use Lazy Initialization? 👉 To avoid unnecessary computations and improve performance. ✔ Prevents repeated execution ✔ Reduces render cost ✔ Useful for heavy logic ❓ Can you give a real-world example? const [data, setData] = useState(() => { return JSON.parse(localStorage.getItem("data")) || []; }); 👉 Without lazy initializer: localStorage is accessed on every render ❌ 👉 With lazy initializer: Runs only once ✅ ❓ What mistake do developers commonly make? useState(expensiveFunction); // ❌ 👉 This stores the function itself, not the result. ❓ When should you use it? 👉 Use lazy initialization when: Working with localStorage/sessionStorage Doing heavy calculations Creating large data structures Transforming initial data ❓ One-line interview answer? 👉 “Lazy initialization in React ensures that expensive state computations run only once during the initial render by passing a function to useState.” 💬 This is a small concept, but a big signal to interviewers that you understand performance optimization. #ReactJS #FrontendDevelopment #WebDevelopment #ReactHooks #JavaScript #CodingInterview
To view or add a comment, sign in
-
-
🎯 JavaScript Interview Prep — Let’s See Where You Stand If you’re preparing for a JS interview… Don’t just read. Answer these without Googling. Let’s test real understanding 👇 🧠 𝟭. 𝗪𝗵𝗮𝘁 𝘄𝗶𝗹𝗹 𝘁𝗵𝗶𝘀 𝗹𝗼𝗴 — 𝗮𝗻𝗱 𝘄𝗵𝘆? 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘢); 𝘷𝘢𝘳 𝘢 = 10; Bonus: Would the answer change with `let`? ⚡ 𝟮. 𝗪𝗵𝗮𝘁’𝘀 𝘁𝗵𝗲 𝗼𝘂𝘁𝗽𝘂𝘁 𝗼𝗿𝗱𝗲𝗿? 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨("𝘚𝘵𝘢𝘳𝘵"); 𝘴𝘦𝘵𝘛𝘪𝘮𝘦𝘰𝘶𝘵(() => 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨("𝘛𝘪𝘮𝘦𝘰𝘶𝘵"), 0); 𝘗𝘳𝘰𝘮𝘪𝘴𝘦.𝘳𝘦𝘴𝘰𝘭𝘷𝘦().𝘵𝘩𝘦𝘯(() => 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨("𝘗𝘳𝘰𝘮𝘪𝘴𝘦")); 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨("𝘌𝘯𝘥"); If you can’t confidently explain this, revise the Event Loop. 🔥 𝟯. 𝗪𝗵𝗮𝘁’𝘀 𝘄𝗿𝗼𝗻𝗴 𝗵𝗲𝗿𝗲? 𝘧𝘰𝘳 (𝘷𝘢𝘳 𝘪 = 0; 𝘪 < 3; 𝘪++) { 𝘴𝘦𝘵𝘛𝘪𝘮𝘦𝘰𝘶𝘵(() => 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘪), 100); } Why does it print what it prints? How would you fix it? 🧩 𝟰. 𝗘𝘅𝗽𝗹𝗮𝗶𝗻 𝘁𝗵𝗶𝘀 𝗶𝗻 𝘆𝗼𝘂𝗿 𝗼𝘄𝗻 𝘄𝗼𝗿𝗱𝘀: What’s the difference between: 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘵𝘦𝘴𝘵() {} 𝘤𝘰𝘯𝘴𝘵 𝘵𝘦𝘴𝘵 = () => {}; Not syntax. Think: `this`, hoisting, constructors. 🚀 𝟱. 𝗪𝗵𝗮𝘁 𝗵𝗮𝗽𝗽𝗲𝗻𝘀 𝗵𝗲𝗿𝗲? 𝘤𝘰𝘯𝘴𝘵 𝘰𝘣𝘫 = { 𝘯𝘢𝘮𝘦: "𝘑𝘚" }; 𝘤𝘰𝘯𝘴𝘵 𝘯𝘦𝘸𝘖𝘣𝘫 = 𝘰𝘣𝘫; 𝘯𝘦𝘸𝘖𝘣𝘫.𝘯𝘢𝘮𝘦 = "𝘑𝘢𝘷𝘢𝘚𝘤𝘳𝘪𝘱𝘵"; 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘰𝘣𝘫.𝘯𝘢𝘮𝘦); 📌 Be honest — how many did you answer confidently without guessing? Drop your answers in the comments 👇 Let’s see who actually understands JavaScript… and who just uses it. #javascript #frontend #techinterview #webdevelopment #codingchallenge #DAY72
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
Other ways - for (var i = 0; i < 3; i++) { let j= i; setTimeout(()=> console.log(j)); } // Output: 0, 1, 2 for (var i = 0; i < 3; i++) { setTimeout(console.log, 0, i); } // Output: 0, 1, 2 for (var i = 0; i < 3; i++) { setTimeout(console.log.bind(null, i), 0); } // Output: 0, 1, 2