🚨 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗿𝗮𝗽 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 – 𝗣𝗮𝗿𝘁 𝟮 If you think you understand JavaScript… Try predicting these outputs 𝘄𝗶𝘁𝗵𝗼𝘂𝘁 𝗿𝘂𝗻𝗻𝗶𝗻𝗴 𝘁𝗵𝗲 𝗰𝗼𝗱𝗲 😏 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟭: 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 𝗠𝘆𝘀𝘁𝗲𝗿𝘆 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑎); 𝑣𝑎𝑟 𝑎 = 10; 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑏); 𝑙𝑒𝑡 𝑏 = 20; 𝗢𝘂𝘁𝗽𝘂𝘁: undefined ReferenceError 💡 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 • var is hoisted and initialized with undefined • let is hoisted but stays in 𝗧𝗲𝗺𝗽𝗼𝗿𝗮𝗹 𝗗𝗲𝗮𝗱 𝗭𝗼𝗻𝗲 (𝗧𝗗𝗭) 👉 Accessing b before initialization throws an error. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟮: 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 𝗶𝗻 𝗔𝗰𝘁𝗶𝗼𝗻 𝑓𝑢𝑛𝑐𝑡𝑖𝑜𝑛 𝑜𝑢𝑡𝑒𝑟() { 𝑙𝑒𝑡 𝑐𝑜𝑢𝑛𝑡 = 0; 𝑟𝑒𝑡𝑢𝑟𝑛 𝑓𝑢𝑛𝑐𝑡𝑖𝑜𝑛 𝑖𝑛𝑛𝑒𝑟() { 𝑐𝑜𝑢𝑛𝑡++; 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑐𝑜𝑢𝑛𝑡); }; } 𝑐𝑜𝑛𝑠𝑡 𝑓𝑛 = 𝑜𝑢𝑡𝑒𝑟(); 𝑓𝑛(); 𝑓𝑛(); 𝑓𝑛(); 𝗢𝘂𝘁𝗽𝘂𝘁: 1 2 3 💡 𝗪𝗵𝘆? The inner function forms a 𝗰𝗹𝗼𝘀𝘂𝗿𝗲, remembering count even after outer() has finished execution. 👉 This is heavily used in 𝗥𝗲𝗮𝗰𝘁 𝗵𝗼𝗼𝗸𝘀 & 𝗿𝗲𝗮𝗹-𝘄𝗼𝗿𝗹𝗱 𝗮𝗽𝗽𝘀. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟯: 𝗣𝗿𝗼𝗺𝗶𝘀𝗲 𝘃𝘀 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁 (𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽) 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔("𝑆𝑡𝑎𝑟𝑡"); 𝑠𝑒𝑡𝑇𝑖𝑚𝑒𝑜𝑢𝑡(() => { 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔("𝑇𝑖𝑚𝑒𝑜𝑢𝑡"); }, 0); 𝑃𝑟𝑜𝑚𝑖𝑠𝑒.𝑟𝑒𝑠𝑜𝑙𝑣𝑒().𝑡ℎ𝑒𝑛(() => { 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔("𝑃𝑟𝑜𝑚𝑖𝑠𝑒"); }); 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔("𝐸𝑛𝑑"); 𝗢𝘂𝘁𝗽𝘂𝘁: Start End Promise Timeout 💡 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 • Promise callbacks go to Microtask Queue • setTimeout goes to Macrotask Queue 👉 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀 are executed before 𝗺𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟰: 𝗧𝗿𝗶𝗰𝗸𝘆 𝗘𝗾𝘂𝗮𝗹𝗶𝘁𝘆 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔([] == 𝑓𝑎𝑙𝑠𝑒); 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔([] === 𝑓𝑎𝑙𝑠𝑒); 𝗢𝘂𝘁𝗽𝘂𝘁: true false 💡 𝗪𝗵𝘆? • == allows 𝘁𝘆𝗽𝗲 𝗰𝗼𝗲𝗿𝗰𝗶𝗼𝗻 • [] → "" → 0 and false → 0 → ✅ true • === checks strict equality (no coercion) → ❌ false 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟱: 𝗢𝗯𝗷𝗲𝗰𝘁 𝗥𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗧𝗿𝗮𝗽 𝑐𝑜𝑛𝑠𝑡 𝑎 = { 𝑛𝑎𝑚𝑒: "𝐽𝑆" }; 𝑐𝑜𝑛𝑠𝑡 𝑏 = 𝑎; 𝑏.𝑛𝑎𝑚𝑒 = "𝑅𝑒𝑎𝑐𝑡"; 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑎.𝑛𝑎𝑚𝑒); 𝗢𝘂𝘁𝗽𝘂𝘁: React 💡 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 Objects are stored by reference, not value. Both a and b point to the 𝘀𝗮𝗺𝗲 𝗺𝗲𝗺𝗼𝗿𝘆 𝗹𝗼𝗰𝗮𝘁𝗶𝗼𝗻. 💬 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗜𝗻𝘀𝗶𝗴𝗵𝘁 If you can confidently answer these, you're ahead of 𝟴𝟬% 𝗼𝗳 𝗰𝗮𝗻𝗱𝗶𝗱𝗮𝘁𝗲𝘀. Most developers fail not because they don’t know JavaScript… But because they don’t understand its 𝗰𝗼𝗿𝗲 𝗯𝗲𝗵𝗮𝘃𝗶𝗼𝗿 𝗱𝗲𝗲𝗽𝗹𝘆. 🔥 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 𝗳𝗼𝗿 𝗬𝗼𝘂 console.log(typeof null); console.log(typeof NaN); Drop your answers in the comments 👇 ♻️ Follow Shubham Kumar Raj for more such high-value interview content #javascript #frontenddeveloper #codinginterview #webdevelopment #programming #learnjavascript #100daysofcode #hiring
JavaScript Interview Questions and Answers
More Relevant Posts
-
❓ What actually happens when you call fetch('/api')? So I sat down and figured it out. Here's what blew my mind 👇 💡 The JS engine itself is TINY. Just two things inside it: 📦 Memory Heap — where your objects live 📚 Call Stack — tracks what function is running That's it. It can't do timers. It can't make network requests. It can't even listen for a click. 🤯 🎭 So who does all the async work? The BROWSER does. Not JavaScript. ⚙️ Web APIs (written in C++) handle the heavy lifting on separate threads: 🌐 fetch — network requests ⏱️ setTimeout — timers 🖥️ DOM — page manipulation 🖱️ Events — clicks, scrolls, keypresses 💾 LocalStorage, Geolocation, WebSockets… When they finish, they drop callbacks into two queues: 🟢 Microtask Queue (HIGH priority) → Promises, await, queueMicrotask 🔴 Callback Queue (LOW priority) → setTimeout, click, fetch response 🔄 Then the Event Loop steps in: 1️⃣ Is the Call Stack empty? 2️⃣ Drain ALL microtasks first 3️⃣ Run ONE macrotask 4️⃣ Let the browser paint 5️⃣ Repeat forever 🎯 This explains SO much: ✅ Why a heavy loop freezes your page (stack never empties) ✅ Why Promise.then() ALWAYS beats setTimeout(fn, 0) ✅ Why async/await isn't magic — it's just microtask syntax ✅ Why single-threaded doesn't mean single-tasking 👨🍳 My favorite mental model: The JS engine is a single chef. Web APIs are robot assistants running errands in the background. The Microtask Queue is the VIP line. The Callback Queue is the regular line. The Event Loop is the maître d' — but only seats people when the chef is free. 💥 The biggest realization: "JavaScript" the language and "JavaScript" the thing running in your browser are two VERY different things. ✨ The language is small. 🌊 The runtime around it is massive. I mapped the whole thing out with diagrams — call stack traces, V8's Ignition/TurboFan pipeline, the full click-to-fetch-to-DOM lifecycle. Dropping it in the comments 👇 👋 What's something you use every day but never really looked under the hood of? #JavaScript #WebDevelopment #Frontend #V8 #EventLoop #CodeNewbie
To view or add a comment, sign in
-
#SoftwareEngineer_Not_Code_Monkey I was recently revisiting some concepts that used to trip me up in JavaScript: Array Manipulation. Sometimes, the best way to master a concept is to lay them all out, look them in the eye, and have a little "chat" with the code. Yes, I talk to my code—and you should too! Let’s break down the "Internal Dialogue" of a Senior Developer when handling arrays: .map() — The Transformer The Conversation: "Take this array, visit every single element, and give me a new array with the modifications I asked for. Same length, fresh look." Use Case: Formatting currency or wrapping data in UI components. JavaScript const prices = [10, 20, 30]; const formattedPrices = prices.map(price => `$${price}.00`); // Result: ["$10.00", "$20.00", "$30.00"] .filter() — The Gatekeeper The Conversation: "I’ve got a condition. Check every item; if they pass, they join the new array. If they fail? They’re out." Use Case: Removing "Out of Stock" items or finding "Admin" users. .reduce() — The Grinder The Conversation: "Take the whole list, start with this 'bag' (Accumulator) set to 0, and squash everything down into one single value." Use Case: Calculating a shopping cart total or flattening nested data. JavaScript const cart = [100, 200, 300]; const total = cart.reduce((acc, price) => acc + price, 0); // Result: 600 .find() — The Scout The Conversation: "Go find me the first person named 'Ashraf'. Once you find him, stop looking and bring him back to me—not a list, just the man himself." const students = ["Ahmed", "Ashraf", "Sara"]; const winner = students.find(s => s === "Ashraf"); // Result: "Ashraf" .forEach() — The Blue-Collar Worker The Conversation: "Don't give me a new array. Just loop through and do something—log it, send it to an API, or trigger an alert." const tasks = ["Task 1", "Task 2"]; tasks.forEach(task => console.log(`Processing: ${task}`)); .some() & .every() — The Inspectors .some(): "Is there at least one rebel in this list? If yes, give me a true." .every(): "Is everyone following the rules? If even one person fails, give me a false." The Engineer's Takeaway: Immutability Except for forEach and sort, these methods respect the Immutability principle. We don't touch the original array—it’s a "Red Line." We create new versions. This keeps your state predictable and your bugs minimal, especially as your project scales from a simple script to a full-blown freelance system. Stop just "writing code." Start engineering solutions. Which Array method was your "final boss" when you started? #Programming #SoftwareEngineering #JavaScript #CleanCode #WebDevelopment #Frontend #TechCommunity #ReactJS #NodeJS #Freelancing
To view or add a comment, sign in
-
In JavaScript, we often use if...else if...else chain to handle conditions. But, there is a cleaner way to write this code, objects. For example, look at the following code: for (tab in issueElems) { if (tab === "open") { openIssues.innerHTML = ""; openCount.className = "loading loading-spinner loading-xs text-info"; showSpinner(searchSpinner, searchSpinnerText, openIssuesSpinner); } else if (tab === "closed") { closedIssues.innerHTML = ""; closedCount.className = "loading loading-spinner loading-xs text-info"; showSpinner(searchSpinner, searchSpinnerText, closedIssuesSpinner); } else { allIssues.innerHTML = ""; allCount.className = "loading loading-spinner loading-xs text-info"; showSpinner(searchSpinner, searchSpinnerText, allIssuesSpinner); } } Now, if we define an object like the following beforehand: let issueElems = { all: { count: allIssuesCount, issues: allIssues, spinner: allIssuesSpinner, }, open: { count: openIssuesCount, issues: openIssues, spinner: openIssuesSpinner, tab: openTab, }, closed: { count: closedIssuesCount, issues: closedIssues, spinner: closedIssuesSpinner, tab: closedTab, }, }; The code becomes as simple as this: for (tab in issueElems) { let c = issueElems[tab]; c.issues.innerHTML = ""; c.count.className = "loading loading-spinner loading-xs text-info"; showSpinner(searchSpinner, searchSpinnerText, c.spinner); } There is also switch...case, but it works in a very absurd way. If you don't add break to case clauses, it keeps going to the next case clause. It starts with the first matching case clause and continues until the break statement is encountered. That's why objects are the best way to handle this matter. What do you use? Share your ideas!
To view or add a comment, sign in
-
🚀 30 Days of JavaScript – Day 20 Today I upgraded my To-Do App with more advanced features. 💡 Project: Advanced To-Do App New features added: • Mark tasks as completed • Edit existing tasks • Delete tasks • Store data using localStorage 🧠 Concepts Used: • DOM manipulation • CRUD operations • local Storage • dynamic UI updates 📌 This project helped me understand how real applications manage and update data. 🎥 Demo below 👇 👉 Source code in (only JS Code). #JavaScript #FrontendDevelopment #WebDevelopment #LearningJavaScript #CodingJourney <script> let tasks = JSON.parse(localStorage.getItem("tasks")) || []; function showTasks() { let list = document.getElementById("taskList"); list.innerHTML = ""; tasks.forEach((task, index) => { let li = document.createElement("li"); let text = document.createElement("span"); text.innerText = task.name; if (task.completed) { text.classList.add("completed"); } // actions let actions = document.createElement("div"); actions.className = "actions"; // complete button let completeBtn = document.createElement("button"); completeBtn.innerText = "✔"; completeBtn.onclick = function() { toggleComplete(index); }; // edit button let editBtn = document.createElement("button"); editBtn.innerText = "Edit"; editBtn.onclick = function() { editTask(index); }; // delete button let deleteBtn = document.createElement("button"); deleteBtn.innerText = "X"; deleteBtn.onclick = function() { deleteTask(index); }; actions.appendChild(completeBtn); actions.appendChild(editBtn); actions.appendChild(deleteBtn); li.appendChild(text); li.appendChild(actions); list.appendChild(li); }); } function addTask() { let input = document.getElementById("taskInput"); if (input.value === "") { alert("Enter task"); return; } tasks.push({ name: input.value, completed: false }); localStorage.setItem("tasks", JSON.stringify(tasks)); input.value = ""; showTasks(); } function deleteTask(index) { tasks.splice(index, 1); localStorage.setItem("tasks", JSON.stringify(tasks)); showTasks(); } function toggleComplete(index) { tasks[index].completed = !tasks[index].completed; localStorage.setItem("tasks", JSON.stringify(tasks)); showTasks(); } function editTask(index) { let newTask = prompt("Edit your task:", tasks[index].name); if (newTask !== null && newTask !== "") { tasks[index].name = newTask; localStorage.setItem("tasks", JSON.stringify(tasks)); showTasks(); } } showTasks(); </script>
To view or add a comment, sign in
-
#day2 of #javascript 1. Operators in JavaScript 🔹 A. Arithmetic Operators Math operations ke liye use hote hain: let a = 10; let b = 5; console.log(a + b); // 15 (Addition) console.log(a - b); // 5 (Subtraction) console.log(a * b); // 50 (Multiplication) console.log(a / b); // 2 (Division) console.log(a % b); // 0 (Modulus / remainder) 🔹 B. Comparison Operators Compare karte hain (true/false return karte hain): let x = 10; let y = "10"; console.log(x == y); // true (value check) console.log(x === y); // false (value + type check) console.log(x != y); // false console.log(x > 5); // true console.log(x < 5); // false 🔹 C. Logical Operators let age = 20; console.log(age > 18 && age < 25); // true (AND) console.log(age > 18 || age < 10); // true (OR) console.log(!(age > 18)); // false (NOT) 🔀 2. if, else, else if Condition check karne ke liye use hota hai: let marks = 75; if (marks > 90) { console.log("A Grade"); } else if (marks > 60) { console.log("B Grade"); } else { console.log("Fail"); } 🔁 3. switch Statement Multiple conditions ke liye use hota hai: let day = 2; switch (day) { case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; case 3: console.log("Wednesday"); break; default: console.log("Invalid Day"); } 👉 break important hai warna next cases bhi run ho jayenge ⚡ 4. Even / Odd Checker let num = 7; if (num % 2 === 0) { console.log("Even Number"); } else { console.log("Odd Number"); } 🎓 5. Grade Calculator let marks = 85; if (marks >= 90) { console.log("Grade A"); } else if (marks >= 75) { console.log("Grade B"); } else if (marks >= 50) { console.log("Grade C"); } else { console.log("Fail"); } #hardwork #consistency #coding #programming
To view or add a comment, sign in
-
What are the differences between var, let, and const in JavaScript? 1. var: Traditional and Globalized Scope: Function-level scope. Variables declared with var are scoped to the function they are declared in, or globally if declared outside of a function. Hoisting: var declarations are hoisted, meaning they are moved to the top of their scope, but their values are not initialized until the code reaches the declaration line. Re-declaration: You can redeclare variables declared with var within the same scope. Example: var x = 5; if (true) { var x = 10; // same variable, overwrites the previous value } console.log(x); // 10 2. let: Modern and Block-scoped Scope: Block-level scope. let is limited to the block (inside loops, conditionals, etc.) where it is declared, offering more predictable behavior. Hoisting: Variables declared with let are also hoisted, but they cannot be accessed until the execution reaches the line where they are declared, leading to a "temporal dead zone." Re-declaration: You cannot redeclare a variable declared with let in the same scope. Example: let y = 5; if (true) { let y = 10; // different variable, does not affect the outer one } console.log(y); // 5 3. const: Immutable and Block-scoped Scope: Block-level scope, just like let. Immutability: Variables declared with const cannot be reassigned after their initial assignment. However, this does not make the value immutable if it's an object or array. You can still change properties or elements within them. Re-declaration: You cannot redeclare a const variable in the same scope, just like let. Example: const z = 5; // z = 10; // Error: Assignment to constant variable. const obj = { name: "John" }; obj.name = "Jane"; // Allowed console.log(obj); // { name: "Jane" } Key Differences at a Glance: var: Function-scoped, hoisted, can be redeclared. let: Block-scoped, hoisted with TDZ (Temporal Dead Zone), cannot be redeclared in the same scope. const: Block-scoped, cannot be reassigned, cannot be redeclared, but objects/arrays declared with const can have mutable properties/elements. When to Use: Use var if you're working with legacy code or need to support older JavaScript versions (not recommended for modern JS). Use let for mutable variables that need to change their values within a block or loop. Use const for immutable values or when you want to prevent accidental reassignment, especially for constants and objects/arrays that you want to maintain structure but modify their contents. 🔧 Mastering var, let, and const will make you a more efficient JavaScript developer and help you avoid tricky bugs! 💻 #JavaScript #WebDevelopment #CodingTips #JavaScriptBestPractices #TechTips #JavaScriptForDevelopers #WebDev #Programming
To view or add a comment, sign in
-
-
🔄 The Event Loop: How JavaScript Really Works 80% of candidates fail this. Don't be one of them. The Classic Test: ```js console.log('1'); setTimeout(() => console.log('2'), 0); Promise.resolve().then(() => console.log('3')); console.log('4'); ``` Output: 1, 4, 3, 2 --- ⚙️ How It Works Step 1: Call Stack runs sync code → 1 and 4 log. Step 2: Web APIs handle async operations while stack clears. Step 3: Event Loop checks queues in priority: ``` 1. Run ALL sync code 2. Clear ENTIRE Microtask Queue (Promises) 3. Run ONE Macrotask (setTimeout) 4. Repeat ``` Queue Examples Priority Microtasks Promises, queueMicrotask 🔥 Highest Macrotasks setTimeout, events, I/O ⬇️ Lower Why output is 1, 4, 3, 2: · Sync: 1, 4 log immediately · Microtask queue: 3 logs (all microtasks run) · Macrotask queue: 2 logs (one runs next) --- 🚨 Critical Rules ✅ Microtasks ALWAYS run before next macrotask — even with 0ms delay. ✅ Microtasks queuing microtasks? They ALL run in same cycle. ✅ Too many microtasks = UI freeze (macrotasks never run). --- 🔥 Common Questions Q: Will this log "DONE"? ```js while (true) { Promise.resolve().then(() => {}); } console.log('DONE'); ``` A: No — microtasks starve the loop forever. Q: Async/await order? ```js async function test() { console.log('A'); await Promise.resolve(); console.log('B'); } test(); console.log('C'); ``` A: A, C, B — await schedules rest as microtask. Q: 10,000 microtasks + 1 macrotask? A: All microtasks run first → page freezes. Fix: Use Web Workers or chunk work. --- 💡 Senior Takeaway Event loop knowledge = better performance: · Batch DOM updates in microtasks · Break heavy loops with setTimeout · Understand React effect scheduling --- 👇 Your turn: Write code with sync + microtask + macrotask. Post output below. #JavaScript #EventLoop #AsyncJS #FrontendInterview #WebPerformance
To view or add a comment, sign in
-
🧠 Memory Management in JavaScript — What Every Developer Should Know Memory management is something many JavaScript developers ignore… until performance issues start appearing 🚨 Let’s break it down 👇 🔹 How JavaScript Stores Data JavaScript uses two types of memory: 👉 Stack (Primitive Data Types) Stored directly in memory (fast & simple) Examples: • number • string • boolean • null • undefined • bigint • symbol Example: let a = 10; let b = a; // copy of value 👉 Each variable gets its own copy ✅ 👉 Heap (Reference Data Types) Stored as references (complex structures) Examples: • objects • arrays • functions Example: let obj1 = { name: "Kiran" }; let obj2 = obj1; obj2.name = "JS"; console.log(obj1.name); // "JS" 👉 Both variables point to the same memory location ❗ 🔹 Garbage Collection (GC) JavaScript uses “Mark and Sweep”: Marks reachable data Removes unreachable data 💡 If something is still referenced, it won’t be cleaned 🔹 Common Memory Leak Scenarios ⚠️ Even with GC, leaks can happen: • Global variables • Closures holding large data • Unstopped setInterval / setTimeout • Detached DOM elements 🔹 How to Avoid Memory Issues ✅ Use let/const ✅ Clear timers (clearInterval / clearTimeout) ✅ Remove unused event listeners ✅ Avoid unnecessary references ✅ Use Chrome DevTools → Memory tab 🔹 Pro Tip 💡 Performance issues are often not slow code — they’re memory that never gets released 🚀 Final Thought Understanding Stack vs Heap gives you a huge edge in debugging and building scalable apps 💬 Have you ever faced a memory leak? What caused it? #JavaScript #WebDevelopment #Frontend #Performance #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
🧸 Closure — Story First Imagine: 👉 A child goes outside to play 👉 But he still remembers what’s inside his house That’s a closure. 👉 A function goes outside its original scope 👉 But still remembers variables from where it was created 🧠 Real Definition:- A closure is a javascript feature where a function remembers and can access variables from its outer (lexical) scope even after the outer function has finished executing. ⚙️ Behind the Scenes (JS Engine) 💡 Example:- function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); counter(); 📦 Step 1: Global Execution Context Created 1- Stored in Call Stack 2- Memory allocated: outer → function counter → undefined ⚙️ Step 2: outer() is called 👉 New Execution Context created for outer :- Inside its memory: count = 0 inner = function() {...} 👉 Normally, when outer() finishes → its memory should be deleted ❌ BUT… 👉 JavaScript sees: “inner function is still using count” So it does something special: 🔥 Closure is Created 👉 JS keeps count alive in memory 👉 Even after outer() is finished This saved memory is called: 👉 Lexical Environment ⚡ Step 3: Execution counter(); → 1 counter(); → 2 👉 Because count is remembered (not destroyed) 🧠 Where is this stored? 👉 The closure data is stored in: Execution Context memory Referenced via Scope Chain Internally kept in Heap (because it persists) (Heap is a region of memory where JavaScript stores reference types like objects, arrays, and functions.) 🔥 Why Closures Matter (Real World) Data privacy (private variables) React hooks Callbacks Event handlers #JavaScript #FrontendDeveloper #WebDevelopment #CodingJourney
To view or add a comment, sign in
-
🧠 𝗗𝗼 𝗬𝗼𝘂 𝗥𝗲𝗮𝗹𝗹𝘆 𝗞𝗻𝗼𝘄 𝗪𝗵𝗮𝘁 `new` 𝗗𝗼𝗲𝘀 𝗜𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁? ⤵️ The new Keyword in JavaScript: What Actually Happens ⚡ 🔗 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/dyAXzDHD 𝗧𝗼𝗽𝗶𝗰𝘀 𝗰𝗼𝘃𝗲𝗿𝗲𝗱 ✍🏻: ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺ ⇢ What actually happens internally when you use `new` ⇢ The 4-step process: create → link → run → return ⇢ Constructor functions & how they really work ⇢ Prototype linking & why it matters ⇢ How instances share methods but keep separate data ⇢ Recreating `new` manually (deep understanding) ⇢ What goes wrong when you forget `new` ⇢ Debugging real-world bugs related to constructors ⇢ new vs ES6 classes — what's really different ⇢ Key tradeoffs & hidden pitfalls Thanks Hitesh Choudhary Sir & Piyush Garg Sir, and the amazing Chai Aur Code community 🙌 #ChaiAurCode #JavaScript #WebDevelopment #Programming #SystemDesign #Frontend #Hashnode
To view or add a comment, sign in
More from this author
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