💡 JavaScript IIFE (Immediately Invoked Function Expression) and Interview Classic: The setTimeout + var Trap Ever seen this weird-looking function? 👇 (function() { console.log("Hello World"); })(); 🤔 Looks different, right? 🧠 What is an IIFE? 👉 An IIFE (Immediately Invoked Function Expression) is a function that: ✔️ Is defined ✔️ And executed immediately No need to call it separately! 🔍 How does it work? (function(name) { console.log("Hello " + name); })("Javascript"); 👉 Output: Hello Javascript 🚀 Why do we use IIFE? 🔒 1. Creates a private scope Variables inside it cannot be accessed outside (function() { var secret = "hidden"; })(); ❌ secret is not accessible outside 🌍 2. Avoids global scope pollution Keeps your code clean and prevents conflicts. ⚡ 3. Helps with closures (classic interview use-case) This is one of the most famous questions asked in interviews 👇 for (var i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } 🤔 What will be the output? 👉 Most people expect: 0 1 2 3 4 ❌ But the actual output is: 5 5 5 5 5 🧠 What’s happening here? 🔹 var is function-scoped, not block-scoped 🔹 The loop finishes execution first → i becomes 5 🔹 setTimeout runs later (asynchronously) 🔹 All callbacks share the same reference of i 👉 So every console.log prints 5 ✅ How to fix it? 🔹a) Using let (block scope): for (let i = 0; i < 5; i++) { setTimeout(() => { console.log(i); }, 1000); } ✔️ Output: 0 1 2 3 4 🔹b) Using Closure (if you must use var): for (var i = 0; i < 5; i++) { (function(i) { setTimeout(() => { console.log(i); }, 1000); })(i); } What is this (function(i) { ... })(i)? 👉 This is an Immediately Invoked Function Expression (IIFE) (It runs immediately after being defined) So for each loop iteration: 🔹A new function is created 🔹It gets its own copy of i as a parameter 👉How closure helps here Inside the loop: First iteration → i = 0 → function runs with i = 0 → setTimeout remembers this i Second iteration → i = 1 → new function with i = 1 → new closure created 👉 This happens for all iterations So instead of sharing one i, we now have 5 different i values stored separately Final result After 1 second: 0 1 2 3 4 ✅ Each setTimeout prints its own preserved value 🔥 Simple analogy Think of it like: ❌ Without closure → 5 people sharing one notebook ✅ With closure → each person gets their own notebook 🚀 Key takeaway 👉 Closures allow functions to remember the variables from their scope 👉 IIFE creates a new scope for each iteration 👉 That’s why this fixes the var problem #JavaScript #CodingInterview #FrontendDevelopment #WebDevelopment #LearnInPublic
JavaScript IIFE and Interview Classic: setTimeout + var Trap
More Relevant Posts
-
🚀 Add Two Numbers WITHOUT Using + in JavaScript 😳 Here’s a classic trick that interviewers LOVE 👇 Instead of using +, we use bitwise operators: 👉 XOR (^) → gives sum without carry 👉 AND (&) → gives carry 👉 << 1 → shifts carry to correct position 💡 Logic: Keep adding the partial sum and carry until carry becomes 0 Why this matters? Because this is exactly how computers perform addition internally at the binary level. 🧠 It’s not just a trick — it’s understanding how systems really work. 🔥 Example: 5 (0101) + 3 (0011) → Result = 8 (1000) 🎯 Where this helps: ✔️ Coding interviews ✔️ Bit manipulation problems ✔️ Deep understanding of low-level operations ✅ Using Bitwise Operators: function sum(a, b) { while (b !== 0) { let carry = a & b; // common bits (carry) a = a ^ b; // sum without carry b = carry << 1; // shift carry } return a; } 🔢 Example: sum(5, 3) First convert numbers to binary: 5 = 0101 3 = 0011 🧠 Core Idea This function mimics how addition works at the bit level: XOR (^) → adds bits without carry AND (&) → finds the carry << 1 → moves carry to the next position 🔁 Step-by-Step Execution 👉 Iteration 1 a = 0101 (5) b = 0011 (3) Step 1: carry carry = a & b = 0101 & 0011 = 0001 Step 2: sum without carry a = a ^ b = 0101 ^ 0011 = 0110 (6) Step 3: shift carry b = carry << 1 = 0001 << 1 = 0010 (2) 👉 Iteration 2 a = 0110 (6) b = 0010 (2) Step 1: carry carry = 0110 & 0010 = 0010 Step 2: sum without carry a = 0110 ^ 0010 = 0100 (4) Step 3: shift carry b = 0010 << 1 = 0100 (4) 👉 Iteration 3 a = 0100 (4) b = 0100 (4) Step 1: carry carry = 0100 & 0100 = 0100 Step 2: sum without carry a = 0100 ^ 0100 = 0000 (0) Step 3: shift carry b = 0100 << 1 = 1000 (8) 👉 Iteration 4 a = 0000 (0) b = 1000 (8) Step 1: carry carry = 0000 & 1000 = 0000 Step 2: sum without carry a = 0000 ^ 1000 = 1000 (8) Step 3: shift carry b = 0000 << 1 = 0000 ✅ Loop Ends Now b = 0, so loop stops. 👉 Final Answer: a = 1000 (8) 🎯 Final Understanding (Important for Interviews) We keep adding partial sum (a ^ b) And carry separately ((a & b) << 1) Repeat until no carry left 🔥 One-Line Intuition 👉 “This is binary addition where we separate sum and carry, then combine them until carry becomes zero.” Follow for more real-world coding insights 🚀 #javascript #coding #webdevelopment #programming #100daysofcode #developer #tech #interviewprep #bitwise #learncoding #dsa #ai
To view or add a comment, sign in
-
-
🔥 From JavaScript Interview Questions Challenge: Refactor a function to use lazy evaluation, processing only what’s necessary. Problem Statement The following function calculates the squares of all numbers in a large array and sums them. However, it computes all squares upfront, wasting resources. function sumOfSquares(arr) { const squares = arr.map((num) => num ** 2); return squares.reduce((sum, square) => sum + square, 0); } console.log(sumOfSquares([1, 2, 3, 4, 5])); Solution Use a generator function to calculate squares lazily, avoiding upfront computation. Optimized Code function* lazySquares(arr) { for (const num of arr) { yield num ** 2; // Compute squares lazily } } function sumOfSquares(arr) { let sum = 0; for (const square of lazySquares(arr)) { sum += square; } return sum; } console.log(sumOfSquares([1, 2, 3, 4, 5])); // 55 Explanation 1. Lazy Evaluation: Squares are computed only when required, saving memory for large arrays. 2. Efficiency: Eliminates intermediate storage, reducing space complexity. #javascript #lazyevaluation #generators #interviewprep
To view or add a comment, sign in
-
-
🚀 Most commonly asked JavaScript Interview Questions (with Code Snippets) Tired of the same old JS questions? Here are some real-world, scenario-based questions that actually test problem-solving 👇 🔹 1. Debounce vs Throttle (UI Performance) 👉 Scenario: Search input hitting API on every keystroke — how do you optimize? function debounce(fn, delay) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; } 🔹 2. Flatten Deeply Nested Array 👉 Scenario: API returns unpredictable nested data function flatten(arr) { return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val) , []); } 🔹 3. Memoization (Performance Optimization) 👉 Scenario: Expensive calculations running repeatedly function memoize(fn) { const cache = {}; return (n) => { if (cache[n]) return cache[n]; return cache[n] = fn(n); }; } 🔹 4. Event Delegation 👉 Scenario: Handling clicks on dynamically added elements document.getElementById("parent").addEventListener("click", (e) => { if (e.target.tagName === "BUTTON") { console.log("Button clicked:", e.target.innerText); } }); 🔹 5. Prevent Multiple API Calls 👉 Scenario: User clicks “Submit” multiple times let isProcessing = false; async function handleSubmit() { if (isProcessing) return; isProcessing = true; await apiCall(); isProcessing = false; } 🔹 6. Deep Clone Object 👉 Scenario: Avoid mutation bugs const clone = structuredClone(obj); 🔹 7. Custom Promise.all 👉 Scenario: Understand async control deeply function myPromiseAll(promises) { return new Promise((resolve, reject) => { let results = []; let count = 0; promises.forEach((p, i) => { Promise.resolve(p) .then(res => { results[i] = res; count++; if (count === promises.length) resolve(results); }) .catch(reject); }); }); } 💡 Pro Tip: Interviewers today focus on real-world scenarios, async handling, and performance optimization — not just syntax. 🔥 If you can explain why and when to use these patterns, you're already ahead of 80% of candidates. #javascript #frontend #webdevelopment #interviewprep #codinginterview #reactjs #nodejs #softwareengineering #careergrowth
To view or add a comment, sign in
-
Most developers use JavaScript string methods daily. But very few understand how they actually work under the hood. So I decided to go deeper. In this blog, I break down: • What string methods really are • Why polyfills exist and when they matter • How to implement methods like includes, indexOf, and trim from scratch • Common string problems asked in interviews • The core logic behind string manipulation once you understand the logic, you don’t rely on memorization anymore. https://lnkd.in/gpAPF2_7 #javascript #webdevelopment #frontend #coding #programming #learninpublic #developers #softwareengineering #interviewprep
To view or add a comment, sign in
-
✅ Top 50 Most Asked JavaScript Interview Questions 📌 Save this list — it’s a goldmine for your prep! 1. What is Debouncing in JavaScript? 2. Understanding Promise.all() 3. What is Deep Equal? 4. Understanding Event Emitters 5. What is Array.prototype.reduce()? 6. Simplifying arrays – Flattening 7. Merging data structures 8. Selecting DOM Elements – getElementsByClassName 9. Avoiding redundant computations with memoization? 10. Safer nested property access: get (or optional chaining)? 11. Hoisting in JavaScript? 12. Differences between let, var, and const? 13. Explain the difference between == and === ? 14. Understanding the Event Loop in JavaScript? 15. What is Event Delegation in JavaScript? 16. How does this work in JavaScript? 17. What sets Cookies, sessionStorage, and localStorage apart? 18. How do <script>, <script async>, and <script defer> differ? 19. What's the difference between null, undefined, and undeclared? 20. What's the difference between .call() vs .apply()? 21. How does Function.prototype.bind work? 22. Why use arrow functions in constructors? 23. How does prototypal inheritance work? 24. Differences between: function Person(){}, const person = Person(), and const person = new Person() 25. Function declarations vs. function expressions? 26. What are the different ways to create objects in JavaScript? 27. What is a higher-order function? 28. How do ES2015 classes differ from ES5 constructor functions? 29. What is event bubbling? 30. What is event capturing? 31. How do mouseenter and mouseover differ? 32. What's the difference between synchronous and asynchronous functions? 33. What is AJAX? 34. What are the pros and cons of using AJAX? 35. What are the differences between XMLHttpRequest and fetch()? 36. What are the various data types in JavaScript? 37. How do you iterate over object properties and array items? 38. Benefits of spread syntax vs. rest syntax? 39. Differences between Map vs. plain objects? 40. Differences between Map/Set and WeakMap/WeakSet 41. Practical use cases for arrow functions? 42. What are callback functions in asynchronous operations? 43. What is debouncing and throttling? 44. How does destructuring assignment work? 45. What is function hoisting? 46. How does inheritance work in ES2015 classes? 47. What is lexical scoping? 48. What are scopes in JavaScript? 49. What is the spread operator? 50. How does this work in event handlers? ✅ Go through these, practice, and you’ll be ready for almost any JS interview! Follow Hrithik Garg 🚀 for more. #frontend #interview #opportunity #react #javascript #angular #backend #nodejs
To view or add a comment, sign in
-
🤫While revising JavaScript for interviews, I was going through one of the most confusing (and interesting) topics: Type Coercion. Especially the rules behind Abstract Equality ("==") from the ECMAScript specification. Honestly, questions like these can easily make you doubt your JavaScript fundamentals if you don’t understand how coercion actually works. If you’re not able to solve them or explain them clearly, it’s a good sign to revise the core concepts again.😌 😜Here are some classic interview questions: console.log([] == ![]); // true console.log(![] == false); // true console.log([] == []); // false console.log([] == 0); // true console.log([0] == 0); // true console.log([1] == true); // true console.log([] == ''); // true These are not just “tricky JS puzzles” — they test your understanding of: • Type conversion rules😏 • Truthy vs Falsy values • Primitive conversion ("ToPrimitive") • Number conversion ("ToNumber") • Boolean conversion ("ToBoolean") • Object reference comparison • Abstract Equality Algorithm ("==") Most developers memorize the answers. Better developers understand why.🤔 That’s where real interview confidence comes from.😎 Currently revising this deeply, and honestly, every time I study it, I find something new. JavaScript looks simple… until "==" enters the chat 😬 #JavaScript #FrontendDevelopment #InterviewPreparation #FrontendInterview #CodingInterview
To view or add a comment, sign in
-
💡 JavaScript Shallow Copy vs Deep Copy 1. Shallow Copy: 📌 Copies only top-level properties (primitives). 📌 Nested objects (arrays, objects) share the same reference. 🎙️ Modifying a top-level primitive in the copy does not affect the original, but modifying a nested object will affect the original, because both share the same reference. 💡 Example: const original= { a: 1, b: { c: 2 } }; const copy= { ...original }; copy.a =100; copy.b.c =200; console.log(original.a); // 1 top-level primitive unaffected console.log(original.b.c); // 200 nested object changed 2. Deep Copy: 📌 Creates a completely independent copy of the object, including all nested objects or arrays. 📌 Modifying any part of the deep copy, including deeply nested properties, has no affect on the original object ⚙️ Methods: Simple objects: JSON.parse(JSON.stringify(obj)) Complex objects: structuredClone(obj) or lodash.cloneDeep(obj) 💡 Example: const original = { name: "Vijay", hobbies: ["Acting", "Dancing"], address: { city: "Ramnad", country: "India" } }; const copy = structuredClone(original); copy.name = "Ajith"; copy.hobbies.push("Racing"); copy.address.city = "Chennai"; console.log(original); /* { name: "Vijay", hobbies: ["Acting", "Dancing"], address: { city: "Ramnad", country: "India" } } */ console.log(copy); /* { name: "Ajith", hobbies: ["Acting", "Dancing", "Racing"], address: { city: "Chennai", country: "India" } } */ #JavaScript #Coding #Programming #TechPost #ShallowCopy #DeepCopy
To view or add a comment, sign in
-
⚡15 JavaScript Senior level questions about objects: 1) How do property descriptors work, and how do get/set interact with writable/configurable/enumerable? 2) Walk through the [[Get]] and [[Set]] algorithm (prototype chain, shadowing, strict mode) 3) What’s the difference between in, hasOwnProperty, and Object.hasOwn? When is Object.hasOwn preferable? 4) Explain Object.create(null) and when you’d use it over {}. 5) this binding in object methods, method extraction, and arrow pitfalls 6) Enumerability, reflection, and key order: for…in vs Object.keys vs Object.getOwnPropertyNames vs Reflect.ownKeys 7) Deep copy strategies: structuredClone, JSON, spread, and Object.assign 8) Freezing, sealing, and extensibility: semantics and pitfalls 9) Proxies, invariants, and why Reflect is your friend 10) Symbols and well-known symbols: make plain objects iterable & controllable 11) Class fields and private fields: what are they actually? 12) super, [[HomeObject]], and why copying methods can break super 13) JSON serialization edge cases: toJSON, replacers, and lost values 14) Property definition vs assignment: descriptors, accessors, and side effects 15) Objects vs Map/WeakMap: key types, iteration, GC, and performance #JavaScript #TechInterview
To view or add a comment, sign in
-
🚀 JavaScript Hoisting — Explained with Tricky Examples + Interview Points Ever wondered how JavaScript runs your code before it even reaches certain lines? That’s where hoisting comes in 👇 🔹 What is Hoisting? Hoisting is JavaScript's default behavior of moving declarations (not initializations) to the top of their scope during the compilation phase. 🔹 Simple Example console.log(a); // undefined var a = 10; 👉 Behind the scenes: var a; console.log(a); a = 10; 🔹 Tricky Cases (Very Important!) 1️⃣ var vs let vs const console.log(a); // undefined var a = 5; console.log(b); // ❌ ReferenceError let b = 10; 👉 let and const are hoisted BUT not initialized → they stay in Temporal Dead Zone (TDZ) 2️⃣ Function Declaration vs Function Expression greet(); // ✅ Works function greet() { console.log("Hello"); } greet(); // ❌ Error var greet = function() { console.log("Hello"); }; 👉 Function declarations are fully hoisted 👉 Function expressions behave like variables 3️⃣ Variable + Function Same Name var x = 10; function x() { console.log("Hello"); } console.log(x); // 10 👉 Function is hoisted first, but variable assignment overrides it 4️⃣ Inside Scope var x = 1; function test() { console.log(x); // undefined var x = 2; } test(); 👉 Local x is hoisted → shadows global x 🔹 Where & When Do We Use Hoisting? ✔ Helps understand execution flow ✔ Useful in debugging unexpected undefined values ✔ Important when working with functions before declaration ✔ Critical in interviews & writing clean code 👉 Best Practice: Always declare variables at the top Prefer let and const to avoid confusion Avoid relying on hoisting in production code 🔹 Interview Points 💡 ✔ What is hoisting? ✔ Difference between var, let, and const hoisting ✔ What is Temporal Dead Zone? ✔ Function declaration vs expression hoisting ✔ Why does undefined occur instead of error? ✔ Hoisting inside function scope ✔ Real-time debugging scenarios 🔹 Quick Tip 👉 Hoisting ≠ moving code physically 👉 It’s just how JavaScript executes code internally 💬 Mastering hoisting = Strong foundation in JavaScript 📌 Save this for interviews & teaching sessions! #JavaScript #Frontend #WebDevelopment #CodingInterview #LearnToCode
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