🧠 JavaScript Closures — Explained in a Simple Way In JavaScript, a closure happens when a function remembers and can still use variables from the place where it was created — even after the outer function has finished. Think of it like having a key to a room. Even if the door is closed later… you can still enter and use the items inside. 🔑🚪 Here’s a quick example: function outer() { let message = "Hello 👋"; return function inner() { console.log(message); }; } const fn = outer(); fn(); // 👉 Output: Hello 👋 ✅ inner() still has access to message ✅ That memory power = Closure 🌟 Why Closures Are Useful? Private data (hidden variables) Remembering values (callbacks, timers) Custom functions (pre-filled data) Example: function greet(name) { return () => console.log("Hello " + name); } const hiJohn = greet("John"); hiJohn(); // Hello John 🔹One-line Definition: Closure = Function + Remembered outer variables If you found this helpful, follow for more: JavaScript | Full Stack | Real-world Coding Tips #JavaScript #Closures #Coding #WebDevelopment #LearnJS #Cognothink
Understanding JavaScript Closures
More Relevant Posts
-
𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗟𝗲𝘅𝗶𝗰𝗮𝗹 𝗦𝗰𝗼𝗽𝗶𝗻𝗴 𝗮𝗻𝗱 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 Every JavaScript developer must master two powerful concepts: 𝗟𝗲𝘅𝗶𝗰𝗮𝗹 𝗦𝗰𝗼𝗽𝗶𝗻𝗴 and 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 — because they form the foundation of how functions truly work under the hood. ♟️𝗟𝗲𝘅𝗶𝗰𝗮𝗹 𝗦𝗰𝗼𝗽𝗶𝗻𝗴: It determines where variables can be accessed in your code. In JavaScript, a function can access variables defined in its own scope and in the scope where it was declared, not where it’s called. ♟️𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀: When a function “remembers” the variables from its outer scope even after that outer function has finished executing — that’s a closure in action. They allow functions to have “private” data and maintain state. As you can see in the picture below, example code shows that 𝚒𝚗𝚗𝚎𝚛() keeps access to count even after 𝚘𝚞𝚝𝚎𝚛() has returned — that’s the magic of 𝗰𝗹𝗼𝘀𝘂𝗿𝗲𝘀! ♟️Pro Tip: 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 are the secret behind many JS patterns like 𝗱𝗮𝘁𝗮 𝗽𝗿𝗶𝘃𝗮𝗰𝘆, 𝗳𝘂𝗻𝗰𝘁𝗶𝗼𝗻 𝗳𝗮𝗰𝘁𝗼𝗿𝗶𝗲𝘀, and 𝗲𝘃𝗲𝗻𝘁 𝗵𝗮𝗻𝗱𝗹𝗲𝗿𝘀. #JavaScript #WebDevelopment #Coding #Closures #LexicalScope #FrontendDevelopment #JSConcepts #WebDevCommunity #LearnToCode #CodeNewbie #ProgrammingTips #100DaysOfCode #DeveloperJourney
To view or add a comment, sign in
-
-
🤖 Day 3 of my 7-Day JavaScript Revision Challenge! Today’s focus: Arrays & Objects in JavaScript Arrays and objects are the core of how JavaScript stores, structures, and manages real-world data. Mastering them gives you the power to build efficient and dynamic applications. 📦⚡ 📚 1. Arrays 🔹 Arrays store ordered collections of values 🔹 They can contain numbers, strings, objects, or mixed data 🔹 Great for maintaining lists like tasks, users, products 🔹 Easy to add, remove, search, and transform data 🔐 2. Objects 🔹 Objects store information in key–value pairs 🔹 Perfect for describing structured items like a user or product 🔹 You can read, update, or add properties effortlessly 🔹 Ideal for representing real-life entities in your program 🧩 3. Array of Objects 🔹 The most commonly used data structure in JavaScript 🔹 Helps manage multiple structured records at once 🔹 Makes filtering, updating, grouping, and searching simple 🔹 Essential for APIs, database data, and frontend state 📝 4. Practice Challenges ✅ Find the largest number in a list ✅ Count how many students passed ✅ Remove duplicate numbers ✅ Add a new user to a list ✅ Convert object keys into a list 🔥 Key Takeaway Arrays and objects are powerful tools for managing and manipulating data. Understanding them makes your JavaScript skills sharper and more real-world ready. 💪💡 🚀 Up next — Day 4: Functions & Scope! #JavaScript #7DaysOfCode #WebDevelopment #CodingJourney #LearnJavaScript #FrontendDevelopment #JSChallenge #CodeNewbie #DeveloperCommunity #Programming #TechLearning #DailyCoding #JSPractice #AmanCodes #Arrays #Objects
To view or add a comment, sign in
-
-
💛 𝗗𝗮𝘆 𝟯 — 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝘀 𝗮𝗻𝗱 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 Today’s focus was one of the most powerful and favorite topics in JavaScript — 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 🔁 💡 𝗖𝗼𝗻𝗰𝗲𝗽𝘁: A closure gives a function access to its outer scope even after the outer function has finished execution. This enables data encapsulation, function factories, and state preservation. 💻 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 𝟭 — 𝗕𝗮𝘀𝗶𝗰 𝗖𝗹𝗼𝘀𝘂𝗿𝗲: function outer() { let count = 0; return function inner() { count++; console.log("Count:", count); }; } const counter = outer(); counter(); // Count: 1 counter(); // Count: 2 🧠 Here, inner() remembers the variable count from outer() even after it’s done — that’s closure in action! 💻 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 𝟮 — 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗮𝗹 𝗨𝘀𝗲: Closures power concepts like private variables: function createUser(name) { return { getName: function () { return name; }, }; } const user = createUser("Ravi"); console.log(user.getName()); // Ravi 🧠 𝗞𝗲𝘆 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴𝘀: ✅ Inner functions retain references to outer scope variables. ✅ Closures are the backbone of callbacks, event handlers, and functional programming. ✅ Used in frameworks like React (hooks rely on closure principles). 🔥 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Closures aren’t magic — they’re just functions remembering where they came from. #JavaScript #Closures #Functions #FrontendDevelopment #100DaysOfCode #LearningEveryday
To view or add a comment, sign in
-
🫢 Ever wondered what happens behind the scenes when you reassign a value in JavaScript? 🤔 👉 When you update a primitive data type (like string, number, boolean, undefined, null, symbol, or bigint), you’re not actually changing the existing value. 👉 Instead, JavaScript silently creates a new value in memory and points your variable to it. 🎯 👉 It’s like getting a brand-new notebook instead of erasing the old one — the old still exists, but you’ve just started fresh. 📒 ✨ So, while it looks like you’re modifying the value, you’re actually reassigning a new memory reference every time. 🌠 As they say, “Appearances can be deceiving.” 😉 The value seems to change, but deep down, it never truly does! 💡 In short: We often know that strings are immutable, but here’s the twist — all primitive data types are immutable in JavaScript! 🔥 💬 Idiom: “Appearances can be deceiving.” — Things may not be as they seem; something that looks one way on the surface may actually be very different underneath. #JavaScript #CodingTips #Programming #TechInsights #LearnToCode #DeveloperLife #FrontendDevelopment #CodeWisdom #ProfessionalLearning #CareerGrowth #JS #WebDevelopment
To view or add a comment, sign in
-
-
JavaScript Challenge 1. Find the second largest number in given array? const data = [3,2,5,4,5,6,54,55]; const findSecondLargest = (arr)=>{ let firstLargest= 0; let secondLargest = 0; for(let i=0;i<=arr.length;i++){ if(arr[i]>firstLargest){ secondLargest=firstLargest; firstLargest = arr[i]; }else if(arr[i] > secondLargest && arr[i] !== firstLargest){ secondLargest = arr[i]; } } return secondLargest } const result = findSecondLargest(data); console.log(result) // Output 54 hashtag #JavaScript hashtag #WebDevelopment hashtag #CodingTips hashtag #Frontend hashtag #LearnToCode Follow me Mohd Arif for coding questions and JavaScript practice!
To view or add a comment, sign in
-
🚀 Deep Clone an Object in JavaScript (the right way!) Most of us have tried this at least once: const clone = JSON.parse(JSON.stringify(obj)); …and then realized it breaks when the object has functions, Dates, Maps, or undefined values 😬 Let’s fix that 👇 ❌ The Problem with JSON.parse(JSON.stringify()) >It’s quick, but it: >Removes functions >Converts Dates into strings >Skips undefined, Infinity, and NaN >Fails for Map, Set, or circular references ✅ Option 1: Use structuredClone() (Modern & Fast) Available in most modern browsers and Node.js (v17+). It can handle Dates, Maps, Sets, and even circular references — no errors, no data loss. const deepCopy = structuredClone(originalObject); Simple, native, and reliable 💪 ✅ Option 2: Write Your Own Recursive Deep Clone Useful for older environments or if you want to understand the logic behind cloning. 💡 Pro Tip: If you’re working with complex or nested data structures, always prefer structuredClone(). It’s the modern, built-in, and safest way to deep clone objects in JavaScript. 🔥 Found this useful? 👉 Follow me for more JavaScript deep dives made simple — one post at a time. #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #LearnJavaScript #Programming #DeveloperCommunity #WebDev #ES6 #JSDeveloper #JavaScriptTips #JavaScriptObjects #JavaScriptClone #JavaScriptCloneObject
To view or add a comment, sign in
-
🎯 Function Parameters & Arguments in JavaScript — Pass Data Like a Pro! Functions become powerful when you can send data to them — that’s where parameters and arguments come in! Let’s break it down 👇 --- 💡 Definition: Parameters are variables listed in the function definition. Arguments are the actual values you pass when calling the function. --- 🧩 Example: function greet(name) { // 'name' is a parameter console.log("Hello, " + name + "! 👋"); } greet("Kishore"); // 'Kishore' is an argument greet("Santhiya"); ✅ Output: Hello, Kishore! 👋 Hello, Santhiya! 👋 --- ⚙ Multiple Parameters Example: function add(a, b) { console.log("Sum:", a + b); } add(5, 10); add(3, 7); ✅ Output: Sum: 15 Sum: 10 --- 🧠 Key Points: Parameters are placeholders. Arguments are real data. You can pass default values too: function greet(name = "Guest") { console.log("Welcome, " + name); } greet(); // Output: Welcome, Guest --- 🔖 #JavaScript #Functions #WebDevelopment #Frontend #JSConcepts #CodingTips #LearnToCode #WebDevCommunity #100DaysOfCode #DeveloperJourney #ProgrammingBasics
To view or add a comment, sign in
-
⚡ Level Up Your JS Skills: 8 Powerful Array Methods to Know Working with arrays is something we do every day as JavaScript developers.knowing how to handle them efficiently makes your code smarter and easier to maintain. Here are some powerful and useful array methods 👇 🔁 map() – Transforms each element and returns a new array. Perfect for rendering lists or transforming data. 🧹 filter() – Creates a new array with elements that meet a condition. Ideal for filtering data or removing unwanted items. ➕ reduce() – Combines array elements into a single value. Great for totals, averages, or aggregating data. 🔍 some() – Checks if at least one element meets a condition. Useful for quick validations or checks. ✅ every() – Checks if all elements meet a condition. Ensures data consistency across your array. 🔎 includes() – Checks if an array contains a value. Cleaner alternative to indexOf(). 🧩 join() – Merges all elements into a single string. Perfect for formatting text or creating CSV-style output. ✂️ splice() – Adds or removes elements directly (mutates the array). Handy for modifying arrays in place. #JavaScript #WebDevelopment #Frontend #React #TypeScript #CodingTips #CleanCode #ArrayMethods
To view or add a comment, sign in
-
⚡ Level Up Your JS Skills: 8 Powerful Array Methods to Know Working with arrays is something we do every day as JavaScript developers.knowing how to handle them efficiently makes your code smarter and easier to maintain. Here are some powerful and useful array methods 👇 🔁 map() – Transforms each element and returns a new array. Perfect for rendering lists or transforming data. 🧹 filter() – Creates a new array with elements that meet a condition. Ideal for filtering data or removing unwanted items. ➕ reduce() – Combines array elements into a single value. Great for totals, averages, or aggregating data. 🔍 some() – Checks if at least one element meets a condition. Useful for quick validations or checks. ✅ every() – Checks if all elements meet a condition. Ensures data consistency across your array. 🔎 includes() – Checks if an array contains a value. Cleaner alternative to indexOf(). 🧩 join() – Merges all elements into a single string. Perfect for formatting text or creating CSV-style output. ✂️ splice() – Adds or removes elements directly (mutates the array). Handy for modifying arrays in place. #JavaScript #WebDevelopment #Frontend #React #TypeScript #CodingTips #CleanCode #ArrayMethods
To view or add a comment, sign in
-
#1: JavaScript Variables - From Basics to Best Practices 🚀 Just stumbled upon a JavaScript behavior that might surprise many beginners - and even some experienced developers! Let me break it down: // The usual suspects const apiKey = "abc123"; let userName = "sandeepsharma"; var userRole = "admin"; // The sneaky one that causes trouble userLocation = "Berlin"; // Wait, no declaration?! Here's what's happening behind the scenes: When you assign a value without const, let, or var, JavaScript quietly creates a global variable: // In browser environments: window.userLocation = "Berlin"; console.log(userLocation); // "Berlin" - it works! Why this should scare you: 🌐 Pollutes the global namespace 🔍 Makes debugging a nightmare 💥 Can overwrite existing variables 🚨 Throws ReferenceError in strict mode The Professional Fix: "use strict"; // Your new best friend const apiKey = "abc123"; // Constant values let userName = "sandeepsharma"; // Variables that change var userRole = "admin"; // Legacy - avoid in new code let userStatus; // Properly declared undefined My Golden Rules for Variables: 1. Start with const - use it by default 2. Upgrade to let only when reassignment is needed 3. Retire var - it's time to move on 4. Never use undeclared variables - strict mode prevents this 5. Always initialize variables - even if with undefined Pro Debugging Tip: // Instead of multiple console.log statements: console.table({apiKey, userName, userRole, userLocation, userStatus}); Notice Line: Explicit declarations make your code more predictable, maintainable, and professional. That accidental global variable might work today but could cause hours of debugging tomorrow! What's your favorite JavaScript variable tip? Share in the comments! 👇 #JavaScript #WebDevelopment #ProgrammingTips #Coding #SoftwareEngineering #Tech #CareerGrowth
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