#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
Mastering Array Manipulation in JavaScript with Senior Developer Techniques
More Relevant Posts
-
🔑 JavaScript Set Reference – Quick Guide 1. Creation js const mySet = new Set(); // empty const letters = new Set(["a","b","c"]); // from array 2. Core Methods MethodPurposeExampleReturnsadd(value)Add elementmySet.add("x")Updated Setdelete(value)Remove elementmySet.delete("a")Booleanclear()Remove all elementsmySet.clear()Empty Sethas(value)Check existencemySet.has("b")true/falsesizeCount elementsmySet.sizeNumber 3. Iteration Methods MethodPurposeExampleforEach(callback)Run function for each valuemySet.forEach(v => console.log(v))values()Iterator of valuesfor (const v of mySet.values()) {}keys()Same as values()mySet.keys()entries()Iterator of [value, value] pairsmySet.entries() 4. Set Logic Methods (ES2025+) MethodPurposeunion(otherSet)Combine elements of both setsintersection(otherSet)Common elementsdifference(otherSet)Elements in one set but not the othersymmetricDifference(otherSet)Elements in either set but not bothisSubsetOf(otherSet)True if all elements are in other setisSupersetOf(otherSet)True if contains all elements of other setisDisjointFrom(otherSet)True if no common elements 5. Example Usage js const a = new Set([1,2,3]); const b = new Set([3,4,5]); console.log(a.union(b)); // {1,2,3,4,5} console.log(a.intersection(b)); // {3} console.log(a.difference(b)); // {1,2} console.log(a.symmetricDifference(b));// {1,2,4,5} 6. Key Notes Unique values only → duplicates ignored. Insertion order preserved. Sets are iterable (unlike WeakSets). Useful for mathematical set operations and fast membership checks. 🎯 Memory Hook Think of a Set as a mathematical set in code: No duplicates. Easy union/intersection/difference. Fast membership checks with .has().
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 37 Till now… you’ve written all your JavaScript in one file 😵 👉 Everything mixed together 👉 Hard to manage 👉 Hard to scale What if you could **split your code into multiple files** and still use them together? 🤔 --- ## 🔥 Solution → Modules --- ## 🔹 What are Modules? Modules allow you to: 👉 Break code into **separate files** 👉 Reuse code easily 👉 Keep code clean & organized --- ## 🔹 Exporting Code ```javascript id="md1" // math.js export function add(a, b) { return a + b } ``` 👉 `export` makes function available outside --- ## 🔹 Importing Code ```javascript id="md2" // main.js import { add } from "./math.js" console.log(add(5, 3)) ``` 👉 Output: 8 --- ## 🔹 Default Export ```javascript id="md3" // user.js export default function greet() { console.log("Hello") } ``` Import: ```javascript id="md4" import greet from "./user.js" ``` --- ## 🔥 Real Life Example Think of a big project 🏢 👉 One file → login 👉 One file → dashboard 👉 One file → API All connected… but separate --- ## 🔥 Why Modules Matter? ✅ Clean code ✅ Reusable logic ✅ Easy to maintain ✅ Scalable projects --- ## 🔥 Simple Summary export → share code import → use code modules → organize code --- ### 💡 Programming Rule **Divide your code. Organize it. Scale it.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope Day 32 → Hoisting Day 33 → Closures Day 34 → Prototypes Day 35 → Classes Day 36 → Inheritance Day 37 → Modules Day 38 → Debounce (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
-
🚀 JavaScript Simplified Series — Day 38 You type in a search bar… And API call starts firing on **every single keystroke** 😵 👉 Type “A” → API call 👉 Type “Ab” → API call 👉 Type “Abh” → API call Server overload 💥 App slow 😓 --- ## 🔥 Problem → Too many function calls --- ## 🔥 Solution → Debounce --- ## 🔹 What is Debouncing? Debouncing means: 👉 **Delay execution** 👉 Until user stops typing --- ## 🔹 Example ```javascript id="db1" function debounce(fn, delay) { let timer return function(...args) { clearTimeout(timer) timer = setTimeout(() => { fn(...args) }, delay) } } ``` --- ## 🔹 Usage ```javascript id="db2" function search(query) { console.log("Searching for:", query) } let debouncedSearch = debounce(search, 500) // call this on input event debouncedSearch("Abhay") ``` 👉 Only runs after user stops typing --- ## 🔍 What’s happening? 👉 Every new call clears previous timer 👉 Only last call executes --- ## 🔥 Real Life Example Think of a **remote button 📺** 👉 You press multiple times 👉 TV reacts only after you stop --- ## 🔥 Where is Debounce used? 👉 Search bars 🔍 👉 Resize events 👉 Input fields 👉 API calls --- ## 🔥 Simple Summary Debounce → delay execution Avoid → unnecessary calls Improve → performance --- ### 💡 Programming Rule **Don’t run code on every action. Run it at the right time.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope Day 32 → Hoisting Day 33 → Closures Day 34 → Prototypes Day 35 → Classes Day 36 → Inheritance Day 37 → Modules Day 38 → Debounce Day 39 → Throttle (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
-
✅ JavaScript Advanced Concepts You Should Know 🔍💻 These concepts separate beginner JS from production-level code. Understanding them helps with async patterns, memory, and modular apps. 1️⃣ Closures A function that "closes over" variables from its outer scope, maintaining access even after the outer function returns. Useful for data privacy and state management. function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 2️⃣ Promises & Async/Await Promises handle async operations; async/await makes them read like sync code. Essential for APIs, timers, and non-blocking I/O. // Promise chain fetch(url).then(res => res.json()).then(data => console.log(data)).catch(err => console.error(err)); // Async/Await (cleaner) async function getData() { try { const res = await fetch(url); const data = await res.json(); console.log(data); } catch (err) { console.error(err); } } 3️⃣ Hoisting Declarations (var, function) are moved to the top of their scope during compilation, but initializations stay put. let/const are block-hoisted but in a "temporal dead zone." console.log(x); // undefined (hoisted, but not initialized) var x = 5; console.log(y); // ReferenceError (temporal dead zone) let y = 10; 4️⃣ The Event Loop JS is single-threaded; the event loop processes the call stack, then microtasks (Promises), then macrotasks (setTimeout). Explains why async code doesn't block. 5️⃣ this Keyword Dynamic binding: refers to the object calling the method. Changes with call site, new, or explicit binding. const obj = { name: "Sam", greet() { console.log(`Hi, I'm ${this.name}`); }, }; obj.greet(); // "Hi, I'm Sam" // In arrow function, this is lexical const arrowGreet = () => console.log(this.name); // undefined in global 6️⃣ Spread & Rest Operators Spread (...) expands iterables; rest collects arguments into arrays. const nums = [1, 2, 3]; const more = [...nums, 4]; // [1, 2, 3, 4] function sum(...args) { return args.reduce((a, b) => a + b, 0); } sum(1, 2, 3); // 6 7️⃣ Destructuring Extract values from arrays/objects into variables. const person = { name: "John", age: 30 }; const { name, age } = person; // name = "John", age = 30 const arr = [1, 2, 3]; const [first, second] = arr; // first = 1, second = 2 8️⃣ Call, Apply, Bind Explicitly set 'this' context. Call/apply invoke immediately; bind returns a new function. function greet() { console.log(`Hi, I'm ${this.name}`); } greet.call({ name: "Tom" }); // "Hi, I'm Tom" const boundGreet = greet.bind({ name: "Alice" }); boundGreet(); // "Hi, I'm Alice" 9️⃣ 💡 Practice these in a Node.js REPL or browser console to see how they interact. 💬 Tap ❤️ if you're learning something new!
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 36 You created a class… Now imagine 👇 You want another class with: 👉 Same properties 👉 Same methods 👉 Plus some extra features Will you rewrite everything again? ❌ That’s inefficient 😵 --- ## 🔥 Solution → Inheritance --- ## 🔹 What is Inheritance? Inheritance allows one class to: 👉 **Reuse properties & methods of another class** --- ## 🔹 Example ```javascript id="inh1" class User { constructor(name) { this.name = name } greet() { console.log("Hello " + this.name) } } class Admin extends User { deleteUser() { console.log("User deleted") } } let admin = new Admin("Abhay") admin.greet() admin.deleteUser() ``` 👉 Output: Hello Abhay User deleted --- ## 🔍 What’s happening? 👉 `Admin` inherited from `User` 👉 So it gets `greet()` automatically 👉 Plus its own method --- ## 🔹 super keyword ```javascript id="inh2" class Admin extends User { constructor(name, role) { super(name) this.role = role } } ``` 👉 `super()` calls parent constructor --- ## 🔥 Real Life Example Think of a **family 👨👩👧** 👉 Parent → basic traits 👉 Child → inherits + adds new traits --- ## 🔥 Simple Summary extends → inheritance super → parent constructor Reuse → no duplication --- ### 💡 Programming Rule **Don’t rewrite code. Reuse it with inheritance.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope Day 32 → Hoisting Day 33 → Closures Day 34 → Prototypes Day 35 → Classes Day 36 → Inheritance Day 37 → Modules (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
-
❓ 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
-
🚀 JavaScript Simplified Series — Day 31 You wrote a variable… But suddenly 😳 👉 It works in one place 👉 But gives error in another Why? 🤔 --- ## 🔥 This is called → Scope --- ## 🔹 What is Scope? Scope defines **where a variable can be accessed** 👉 Kaha use kar sakte ho 👉 Kaha nahi --- ## 🔹 1. Global Scope ```javascript id="sc1" let name = "Abhay" function greet() { console.log(name) } greet() ``` 👉 Accessible everywhere 📌 Global = sab jagah access --- ## 🔹 2. Function Scope ```javascript id="sc2" function test() { let age = 22 console.log(age) } test() console.log(age) ❌ ``` 👉 Error ❌ 📌 Function ke bahar access nahi --- ## 🔹 3. Block Scope (let & const) ```javascript id="sc3" if (true) { let city = "Delhi" console.log(city) } console.log(city) ❌ ``` 👉 Error ❌ 📌 Block ke bahar access nahi --- ## 🔥 var vs let vs const ```javascript id="sc4" if (true) { var x = 10 } console.log(x) // works 😳 ``` 👉 `var` ignores block scope 📌 `let` & `const` follow block scope --- ## 🔥 Real Life Example Think of a house 🏠 👉 Global → pura ghar 👉 Function → ek room 👉 Block → ek drawer Har cheez har jagah access nahi hoti --- ## 🔥 Simple Summary Global → everywhere Function → inside function Block → inside {} --- ### 💡 Programming Rule **Keep variables limited. Smaller scope = fewer bugs.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope Day 32 → Hoisting (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
-
JavaScript Proxy — A Hidden Superpower You Should Know Most of us create objects like this: const frameworkName = { name: "Next JS" }; But what if you could intercept and control every operation on this object? That’s exactly what JavaScript Proxy does. Think of it like a gatekeeper sitting in front of your object — it can monitor, modify, or block any interaction. const frameworkName = { name: "Angular" }; const proxyFramework = new Proxy(frameworkName, { get(target, prop) { console.log(`Reading ${prop}`); return target[prop]; }, set(target, prop, value) { console.log(`Updating ${prop} to ${value}`); if (value === "React") { console.log("React is not allowed!"); throw new Error("React is not allowed!"); // Throw an error to prevent the update return false; // Prevent the update } target[prop] = value; return true; } }); proxyFramework.name; // 👉 Reading name proxyFramework.name = "Next"; Why should you care? ✔ Track changes (great for debugging) ✔ Add validation before updating values ✔ Build reactive behavior (like frameworks do) ✔ Control or restrict access to data Real-world use cases: • Form validation without extra libraries • Logging state changes for debugging • Building custom state management • Data sanitization before saving Pro Tip: Frameworks like Vue use Proxy internally to make data reactive. Understanding this can level up your frontend skills. Have you used Proxy in your projects, or are you still sticking with plain objects? #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #Coding #Programming #LearnToCode
To view or add a comment, sign in
-
Most bugs don’t come from complex logic — they come from misunderstood behavior. One classic example in JavaScript: **shallow copy vs deep copy**. If you’ve worked with objects long enough, you’ve probably seen unexpected mutations. That usually comes down to how copying actually works under the hood. 🔹 SHALLOW COPY — copies structure, not depth Common methods: spread operator `{...obj}`, `Object.assign()`, array `slice()` / `concat()` ✔️ Creates a new top-level object ❌ Nested objects/arrays still share references ```js const user = { name: "Aman", prefs: { theme: "dark" } }; const copy = { ...user }; copy.prefs.theme = "light"; console.log(user.prefs.theme); // "light" ``` Even though `copy` looks independent, the nested object is still pointing to the same memory. 🔸 DEEP COPY — full separation Modern approach: `structuredClone()` ✔️ Completely independent copy ✔️ Handles nested objects, arrays, Map, Set, Date, etc. ```js const user = { name: "Aman", prefs: { theme: "dark" } }; const clone = structuredClone(user); clone.prefs.theme = "light"; console.log(user.prefs.theme); // "dark" ``` Quick comparison • `{...spread}` → shallow • `Object.assign()` → shallow • `structuredClone()` → deep ✅ • `JSON.parse(JSON.stringify())` → deep ⚠️ (drops Date, undefined, functions) • `_.cloneDeep()` → deep ✅ (useful for legacy support) When should you use what? → Flat data (no nesting)? Shallow copy is enough → Nested structures? Go for deep copy → Working with Date, Map, Set? Prefer `structuredClone()` → Need wide browser support? Use `_.cloneDeep()` Simple rule: If your data has depth, your copy should too. #JavaScript #WebDevelopment #Frontend #CodingTips #JS #SoftwareEngineering #Programming
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 33 You wrote a function… It finished execution… But somehow 😳 👉 It still remembers old variables? How is that possible? 🤯 --- ## 🔥 This is called → Closures --- ## 🔹 What is a Closure? A **closure** is when a function 👉 Remembers variables from its outer scope 👉 Even after the outer function has finished --- ## 🔹 Example ```javascript id="cl1" function outer() { let count = 0 return function inner() { count++ console.log(count) } } let counter = outer() counter() counter() counter() ``` 👉 Output: 1 2 3 --- ## 🔍 What’s happening? 👉 `outer()` executed once 👉 `inner()` still remembers `count` 👉 Value persists 😎 --- ## 🔥 Why is this powerful? Because function can **remember state** --- ## 🔹 Real Life Example Think of a **bank account 🏦** ```javascript id="cl2" function bankAccount() { let balance = 1000 return function deposit(amount) { balance += amount console.log(balance) } } let account = bankAccount() account(500) account(200) ``` 👉 Output: 1500 1700 👉 Balance remembered between calls --- ## 🔥 Where are closures used? 👉 Data privacy 👉 Counters 👉 Event handlers 👉 React hooks --- ## 🔥 Simple Summary Closure → function + memory Remembers outer variables Keeps state alive --- ### 💡 Programming Rule **Closures give functions memory. Use them to control data smartly.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope Day 32 → Hoisting Day 33 → Closures Day 34 → Prototype (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
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