So, closures are a thing in JavaScript. They're basically functions that remember stuff from their outer scope - and that's pretty cool. It's like a function has a memory, you know? A closure is a function that can access variables from its outer scope, even after the outer function has finished executing - which is wild. Here's the deal: when a function is defined inside another function, it's like they're related or something. The inner function has access to the outer function's variables, which is pretty handy. And when the outer function finishes executing, the inner function can still access its variables - it's like they're connected, you know? For instance, check out this example: ```javascript function createCounter() { let count = 0; return function increment() { count++; console.log(count); }; } ``` In this case, the `increment` function remembers the `count` variable from its outer scope - it's like it has a reference to it or something. Closures are used in a lot of JavaScript concepts, including React Hooks - so understanding them is pretty important. If you don't get closures, you might end up with bugs in your code, and that's no fun. So, what's the key to understanding closures? It's simple: a function remembers its outer scope - that's it. You can use closures to create private variables, which is pretty useful. For example: ```javascript function createBankAccount(initialBalance) { let balance = initialBalance; return { deposit(amount) { balance += amount; return balance; }, withdraw(amount) { if (amount > balance) { throw new Error('Insufficient funds'); } balance -= amount; return balance; }, getBalance() { return balance; } }; } ``` In this example, the `balance` variable is private - it can only be accessed through the returned methods, which is like a security feature or something. Anyway, that's closures in a nutshell. Check out this article for more info: https://lnkd.in/gsbBxJf5 #javascript #closures #reacthooks #coding
Understanding JavaScript Closures and Their Importance
More Relevant Posts
-
JavaScript Fundamentals - Part 3 Hoisting It is behavior of processing declarations before executing code. In simple terms: - JavaScript knows about variables and functions before running the code - This happens during the memory creation phase of an execution context So, hoisting is not moving code upward rather its preparing memory upfront. Why hoisting exists - its is side effect of how JS creates execution contexts. Before execution: - memory is allocated - identifiers are registered - scope is set up This allows: - function calls before their definition - predictable scope resolution Hoisting by Declaration Type var hoisting console.log(a); var a = 10; What happens: - a is hoisted - initialized with undefined - assigned 10 during execution So, console.log(a); // undefined Function Declaration Hoisting sayHi(); function sayHi(){ console.log("Hi"); } What happens: - entire function is hoisted - function can be called before declaration let and const Hoisting console.log(b); let b = 20; // ReferenceError: Cannot access 'b' before initialization What happens: - b is hoisted - but not initialized - exists in TDZ - Function Expressions sayHello(); var sayHello = function() { console.log("Hello"); }; What happens; - sayHello is hoisted as undefined - function body is not hoisted Result: TypeError: sayHello is not a function TDZ -it is the time between entering a scope and initializing let or const variable - variable exists - but cannot be accessed - prevents accidental usage before declaration TDZ is not special zone in memory, it is a state of a binding between hoisting and initialization { // TDZ starts console.log(a); //ReferenceErrror let a = 10; // TDZ ends } So, based on our above details, how can you describe Hoisting in one line ? Please follow for Part 4 updates. 👍 #javascriptfundamentals #uideveloper #corejs
To view or add a comment, sign in
-
💡JavaScript/React Tip💡 Using array reduce method helps to write better code. Let’s say you want to separate users based on their status or type. You might write code like this: const activeUsers = users.filter((user) => user.status === "active"); const inActiveUsers = users.filter((user) => user.status === "inactive"); Looks clean, right? But here's what's happening behind the scenes: 🔁 You're looping over the same array two times . Now imagine if your users list grows to 10,000+ users… That could affect performance. Also, If later you want to filter users by another status like disabled, then you need to add another line of code using filter function. ✅ Better approach: Use .reduce() to do all the grouping in one iteration. const { activeUsers, inActiveUsers } = users.reduce( (acc, user) => { if (user.status === "active") acc.activeUsers.push(user); if (user.status === "inactive") acc.inactiveUsers.push(user); return acc; }, { activeUsers: [], inactiveUsers: [] } ); 🧠 What’s happening here? → We loop through the array only once. → We check each user and push them into the appropriate bucket. → At the end, we destructure the object returned by the reduce method and get all two arrays. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #es6 #nextjs #webdevelopment
To view or add a comment, sign in
-
-
Hello everyone, I’d like to explain two JavaScript concepts—currying and closures—using the dynamic onChange handler in the code snippet below. Here’s a breakdown of how and why it works: 💡 The Concept: Instead of a standard function, we create a function that returns another function. 🧠 What is happening under the hood? 1. Currying (The Setup): We don't pass all arguments (field and e) at once. First, we call handleInputChange('email'). Result: This returns a new function that is sitting there, waiting specifically for the event e. 2. Closure (The Memory): Even after that first function finishes running, the returned function "remembers" the field variable ('email') because of closure. The Payoff: When React finally triggers the onChange event, our inner function executes with access to both the specific field name (saved from the closure) and the event (provided by React). One handler. Infinite inputs. Cleaner code. 🚀 Check out the implementation below. Have you used this pattern in your projects, or do you prefer a different approach? #JavaScript #ReactJS #WebDevelopment #CodingTips #CleanCode
To view or add a comment, sign in
-
-
So, you're writing JavaScript code across multiple files - it's a mess. Three files, to be exact: user.js, admin.js, and main.js. It's simple. You've got variables flying around, and they're all overwriting each other - not good. This happens because, by default, you're loading scripts into the global scope, which is like trying to have a conversation in a loud bar - everything gets lost in the noise. To fix this, you need to think about Modules - they're like little containers that keep your code organized. You enable Modules by adding type="module" to your script tag, like this: <script type="module" src="main.js"></script>. And just like that, you've got three strict rules in place: - File-Level Scope, which means variables aren't global by default - they're more like secrets shared among friends. - Strict Mode, which is like having a code reviewer who's always on your case - it's a good thing, trust me. - Deferred Execution, which means your code waits patiently until the HTML is parsed - it's like waiting for your coffee to brew before you start your day. Think of a Module like a private club - nothing gets in or out unless you explicitly allow it. You export what you want to share, and you import what you need - it's like trading secrets with your friends. And when you import a Module, you get a Live Reference, which is like having a direct hotline to the variable inside the Module - if something changes, you'll know instantly. Modules are also Singletons, which means the Engine evaluates them only once, and every subsequent import is like getting a reference to the same old friend - you're not starting from scratch every time. Using Modules gives you boundaries, and that's a beautiful thing - you can build complex systems without everything collapsing into the global scope. It's like having a clean and organized desk - you can focus on what matters. Source: https://lnkd.in/gD78hVjr #JavaScript #Modules #CodingBestPractices
To view or add a comment, sign in
-
🧠 JavaScript – Scope, Hoisting & this Understanding How JavaScript Works Internally To write better JavaScript, it’s not enough to know what to write we must understand how JavaScript executes code behind the scenes. This is where scope, hoisting, and this become important. 🔹 Scope in JavaScript Scope defines where a variable can be accessed. 🌍 Global Scope Variables declared outside functions or blocks. let appName = "MyApp"; function showName() { console.log(appName); } 👉 Accessible everywhere in the program. 🏠 Local (Function) Scope Variables declared inside a function. function greet() { let message = "Hello"; console.log(message); } 👉 Cannot be accessed outside the function. 📦 Block Scope Variables declared using let and const inside {}. if (true) { let count = 5; } 👉 count is not accessible outside the block. 🔹 Hoisting (Important Concept) Hoisting means JavaScript moves declarations to the top before execution. console.log(a); var a = 10; 👉 Output: undefined (The declaration is hoisted, not the value.) let and const with Hoisting console.log(b); let b = 5; 👉 This causes an error. Why? let and const are hoisted But not initialized (Temporal Dead Zone) 🔹 The this Keyword this refers to the object that is currently using the function. In a Regular Function console.log(this); 👉 Refers to the global object (window in browsers). Inside an Object let user = { name: "Alex", greet() { console.log(this.name); } }; 👉 this refers to the user object. Arrow Functions & this let user = { name: "Alex", greet: () => { console.log(this.name); } }; 👉 Arrow functions do not have their own this. 🧠 Simple Way to Remember Scope → where variables live Hoisting → how JS reads code this → who owns the function Understanding these prevents confusing bugs. ✅ Why This Matters Helps write predictable code Avoids scope-related errors Makes frameworks easier to understand Often asked in interviews If you understand this, you’re thinking like a real JavaScript developer. . . #JavaScript #WebDevelopment #ProgrammingBasics #LearningInPublic #FrontendDevelopment #FullStackJourney
To view or add a comment, sign in
-
-
I thought I understood this JavaScript concept… until I really did 👇 📌 Parameter Scope in JavaScript Function parameters are not special variables they are simply local variables scoped to the function. function greet(userName) { console.log(userName); } console.log(userName); // ❌ ReferenceError: userName is not defined Key Takeaway: userName exists only inside the function's execution context. But here’s the interesting part 👀 Parameters also follow lexical scope, which means inner functions can access them via closures: function outer(x) { function inner() { console.log(x); // ✅ Accesses 'x' from the outer scope } inner(); } And a subtle gotcha most beginners miss ⤵️ Default parameters are evaluated in their own scope at the moment the function is called, strictly before the function body begins to run. Understanding scope like this changed how I read and debug JavaScript code. Small concepts. Big clarity. 🚀 #JavaScript #WebDevelopment #LearningInPublic #Frontend #CodingTips #Scope
To view or add a comment, sign in
-
Why for loop with setTimeout in JavaScript does not work the way we think Look at the simple code below: for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } We can assume here that the output will be: 0, 1, 2 But the actual output is: 3, 3, 3 If the code is without setTimeout: for (var i = 0; i < 3; i++) { console.log(i); } The result is clear: 0, 1, 2 And the same result for the below as well: for (let i = 0; i < 3; i++) { console.log(i); } Output: 0, 1, 2 Confused!! Earlier, I bypassed the concept and simply used let instead of var whenever I used any asynchronous callback inside a for loop, so the code worked fine. But at the same time, I wanted the reason for the different behavior. Let me share what I explored after a long time going deeper into JavaScript and how it plays with variable types - var and let where loop is concerned. In case of let, JavaScript creates a variable instance in memory for each loop iteration. Each setTimeout looks for its corresponding instance: Iteration 0 → i0 (instance) → value: 0 → captured by setTimeout 1 Iteration 1 → i1 (instance) → value: 1 → captured by setTimeout 2 Iteration 2 → i2 (instance) → value: 2 → captured by setTimeout 3 But in case of var, there will be only a single instance, which is updated on each iteration. Since setTimeout takes 100 ms to execute, by that time the loop is finished, so the setTimeout always sees the final result. #javascript #webdevelopment #frontend #reactjs #nextjs #axios #fetchapi #JavaScriptTraps #FrontendDevelopment #AsyncJavaScript #Closures #JavaScriptTips #JavaScriptGotchas #CodingConcepts #programmingtips #developercommunity #codinglife #softwareengineering #webdev #learnjavascript #techcontent #100daysofcode
To view or add a comment, sign in
-
-
Cleaning Up Side Effects in JavaScript — The Pattern Most Bugs Come From Once you understand closures and the JavaScript memory model, the real challenge isn’t identifying side effects — it’s ending them correctly. In JavaScript, side effects like event listeners, timers, and async tasks don’t automatically stop when the function that created them finishes. They live independently and continue to run until you explicitly tell them to stop. This is intentional behavior, not a bug. Professional JavaScript code treats every side effect as a lifecycle. If you add an event listener, you also define when it should be removed. If you start an interval, you decide when it should be cleared. If you kick off async work, you need a way to cancel or ignore it when it’s no longer relevant. This is why cleanup logic should be written at the same time as setup logic. Pairing addEventListener with removeEventListener, setInterval with clearInterval, and async operations with cancellation or guards prevents stale closures and unnecessary memory retention. The rule is simple but powerful: Side effects must have a clear start and a clear end. When you design side effects this way, memory leaks become rare and behavior stays predictable.
To view or add a comment, sign in
-
-
Day 7: First-Class Functions, Function Statement, Function Expression & Anonymous Functions (JavaScript) JavaScript treats functions as first-class citizens. But what does that actually mean? 🔹 1️⃣ First-Class Functions In JavaScript, functions can: ✅ Be assigned to a variable ✅ Be passed as arguments ✅ Be returned from another function function greet() { return "Hello"; } function execute(fn) { console.log(fn()); } execute(greet); 👉 This ability makes concepts like callbacks, closures, and higher-order functions possible. 🔹 2️⃣ Function Statement (Function Declaration) function add(a, b) { return a + b; } ✔️ Hoisted completely ✔️ Can be called before definition 🔹 3️⃣ Function Expression const add = function(a, b) { return a + b; }; ✔️ Treated like a variable ❌ Not fully hoisted (lives in Temporal Dead Zone if let/const) 🔹 4️⃣ Anonymous Function A function without a name. setTimeout(function() { console.log("Hello"); }, 1000); 👉 Usually used in function expressions or callbacks. 🧠 Mental model to remember 🔥 Key Difference (Interview Favorite) Function Statement → Hoisted with definition Function Expression → Hoisted as variable (undefined / TDZ) Anonymous → No function name First-Class Function → Ability, not a type #Javascript #FirstClassFunction #FunctionExpression #FunctionStatement #AnonymousFunction #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
Why does 0 == false return true in JavaScript? 😵 If this confuses you, you're not alone. I wrote a guide explaining == vs === and how to avoid common pitfalls that trip up even experienced developers. Link below 👇 https://lnkd.in/dGP2aJZr #JavaScript #CodingTips #WebDev
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