JavaScript Concept — “The Power of Closures” 💭 Ever wondered how JavaScript functions “remember” the variables around them? That’s the magic of Closures — one of JavaScript’s most elegant features. Closures allow a function to access variables from its outer scope, even after that scope has closed. This concept powers some of the most powerful patterns in JS — from private variables to event handlers. Here’s a small example 👇 function counter() { let count = 0; return function() { count++; return count; }; } const add = counter(); console.log(add()); // 1 console.log(add()); // 2 It’s simple, elegant, and shows how deep JavaScript really is. #JavaScript #WebDevelopment #Coding #Frontend #Learning
How JavaScript Closures Work
More Relevant Posts
-
Today I spent some time understanding Hoisting in JavaScript, and it really helped me see how JS works behind the scenes. Here’s what I learned: 🔹 JavaScript reads the code in two phases: 1️⃣ 𝐌𝐞𝐦𝐨𝐫𝐲 𝐂𝐫𝐞𝐚𝐭𝐢𝐨𝐧 𝐏𝐡𝐚𝐬𝐞 – where variable & function declarations are hoisted 2️⃣ 𝐄𝐱𝐞𝐜𝐮𝐭𝐢𝐨𝐧 𝐏𝐡𝐚𝐬𝐞 – where the actual code runs 🔹 var is hoisted and set to undefined, so accessing it early doesn’t throw an error. 🔹 let & const are also hoisted but not initialized. They stay in the Temporal Dead Zone, which is why accessing them before the declaration gives a ReferenceError. 🔹 Function declarations are fully hoisted, so they can be called before they are written in the code. Understanding this concept made a lot of things clearer, especially why some errors happen in JS. Learning step by step and enjoying the process! 🚀 #JavaScript #LearningJourney #WebDevelopment #Frontend #Hoisting #10000coders #10kcoders
To view or add a comment, sign in
-
-
Ever seen a variable live even after its function dies? That’s Closure — the memory ninja of JavaScript 🧠 One of JavaScript’s most powerful (and tricky) features 💡 Let’s look at a simple example 👇 function counter() { let count = 0; return function () { count++; console.log(count); }; } const increment = counter(); increment(); // 1 increment(); // 2 increment(); // 3 Wait… how does count still remember its value? Didn’t the counter() function finish already? 😅 Here’s the magic 🪄 > A closure allows a function to “remember” the variables from the scope in which it was created — even after that scope is gone. In this example, The inner function still has access to count, Because it closes over the variables from its outer function. That’s why we call it a Closure 🔁 Closures are the reason we can create: ✅ Private variables ✅ Function factories ✅ Modular, memory-efficient code In short — > A closure is how JavaScript gives functions memory 🧠 #JavaScript #Closures #WebDevelopment #Frontend #MERNStack #NodeJS #ReactJS #Coding #SoftwareEngineering #Developers #JSFundamentals
To view or add a comment, sign in
-
🚀 JavaScript Closures — Small Concept, Big Power! Today, I revisited one of the most fundamental — yet powerful — concepts in JavaScript: Closures. Take a look at this simple example 👇 At first glance, it looks simple — but it’s doing something magical. Every time you call counter(), the variable count remembers its previous value even though outer() has already finished executing. That’s the beauty of closures — they allow functions to “remember” the environment in which they were created. This concept powers many real-world use cases: ✅ Data privacy (like private variables) ✅ Function factories ✅ State management in React hooks 💡 In short: Closures make JavaScript truly powerful and expressive. Have you used closures in an interesting way lately? Share your example below — I’d love to see how you’ve applied them in your projects! ⚡ #JavaScript #WebDevelopment #Closures #Frontend #Coding #LearningEveryday
To view or add a comment, sign in
-
-
How JS Converts [] + {} to [object Object] —🤯 JavaScript can be weirdly magical sometimes. Ever tried this in your console? 👇 [] + {} // Output: "[object Object]" At first glance, it looks confusing — why does an empty array and an empty object become a string? Let’s decode the magic 🪄 1️⃣ + Operator in JS The + operator doesn’t just add numbers — it can also concatenate strings. 2️⃣ Type Conversion Happens! [] (empty array) → when converted to string becomes "" (empty string). {} (empty object) → when converted to string becomes "[object Object]". 3️⃣ Final Expression So JS actually does: "" + "[object Object]" → "[object Object]" ✅ Bonus twist: Try reversing it: {} + [] Now it gives 0 because {} is treated as an empty block,not an object. 🤯 JavaScript — where logic meets magic ✨ 🔹 Follow Prashansa Sinha for more fun JS mysteries and simple explanations 👩💻 #JavaScript #WebDevelopment #Coding #Frontend #JS #LearnToCode #Programming #TechCommunity #Developers #CodeNewbie #WebDev
To view or add a comment, sign in
-
The Event Loop — The Beating Heart of JavaScript ❤️ Ever wondered how JavaScript manages to do so much — while still being single-threaded? That’s where the Event Loop comes in. Let’s break it down 👇 JavaScript runs in one thread — it can’t multitask by itself. But when you use things like 👉 setTimeout() 👉 Promises 👉 async/await 👉 event listeners they get handled outside the main thread — by the browser’s API — and are then pushed into the callback queue or microtask queue. The Event Loop constantly checks: > “Is the call stack empty? If yes, let’s push the next task from the queue.” That’s how JavaScript gives the illusion of multitasking. Synchronous code → runs first. Then microtasks (Promises) → then macrotasks (timeouts, intervals, etc.). Once you truly understand this, async behavior, callback hell, and even race conditions start making sense. 🔥 So next time someone says JS is “single-threaded,” just smile — because you know the Event Loop is secretly doing all the heavy lifting 😎 #JavaScript #EventLoop #AsyncProgramming #WebDevelopment #Frontend #NodeJS #ReactJS #MERNStack #CodeNewbie #100DaysOfCode #JS #TechCommunity #Programming #CleanCode #LearnJavaScript #SoftwareDevelopment #CodingJourney #DeveloperCommunity #TrendingNow
To view or add a comment, sign in
-
-
💡 Most devs think shallow copies always affect the original… but that’s not true! Let’s clear this common JavaScript misconception 👇 🧩 Example 1 — Primitives let obj = { a: 1, b: 2, c: 3 }; let obj2 = { ...obj }; obj2.b++; console.log(obj.b); // 2 ✅ unchanged ➡️ Here b is a primitive (number). Primitives are copied by value, so obj and obj2 have separate copies. Incrementing obj2.b doesn’t affect obj.b. ⚠️ Example 2 — Nested Objects let obj = { a: 1, b: { x: 10 } }; let obj2 = { ...obj }; obj2.b.x = 99; console.log(obj.b.x); // 99 ❗changed ➡️ Here b is an object, and a shallow copy only copies its reference. Both obj.b and obj2.b point to the same memory. So changing one affects the other. 💬 TL;DR Shallow copy doesn’t always affect the original — it depends on what’s inside the object. Primitives → safe Objects → shared #JavaScript #Frontend #WebDevelopment #ReactJS #CodingTips #Programming #JSFacts
To view or add a comment, sign in
-
“The Secret Behind JavaScript’s Magic — The Event Loop 🧠” When I first learned JavaScript, I used to wonder — how can it handle so many things at once even though it’s single-threaded? 🤔 The answer lies in one beautiful mechanism — The Event Loop. Here’s what actually happens behind the scenes 👇 1️⃣ JavaScript runs in a single thread — only one thing executes at a time. 2️⃣ But when something async happens (like setTimeout, fetch, or Promise), those tasks are offloaded to the browser APIs or Node.js APIs. 3️⃣ Once the main call stack is empty, the event loop takes pending callbacks from the task queue (or microtask queue) and pushes them back into the stack to execute. So while it looks like JavaScript is multitasking, it’s actually just scheduling smartly — never blocking the main thread. Example:- console.log("Start"); setTimeout(() => console.log("Inside Timeout"), 0); Promise.resolve().then(() => console.log("Inside Promise")); console.log("End"); Output:- Start End Inside Promise Inside Timeout Even though setTimeout was “0 ms”, Promises (microtasks) always run before timeouts (macrotasks). That’s the secret sauce 🧠💫 Understanding this single concept can help you debug async behavior like a pro. #JavaScript #EventLoop #Async #WebDevelopment #Coding
To view or add a comment, sign in
-
Hey, Mates. How are you doing? You know, Even experienced devs trip over JavaScript quirks sometimes — here are a few I’ve seen (and made myself 😅 as well): 1. Using var instead of let or const var is function-scoped and can cause weird bugs due to hoisting. ✅ Use let for variables that change and const for ones that don’t. 2. Forgetting to handle async properly Mixing promises, callbacks, and async/await can lead to race conditions or unhandled rejections. ✅ Always await async functions or chain with .then(), and wrap in try/catch. 3. Comparing values incorrectly == does type coercion (and sometimes weirdly!). ✅ Stick to === for strict comparison. 4. Misunderstanding this Arrow functions don’t have their own this — they inherit from the parent scope. ✅ Know when to use arrow functions vs regular ones. 5. Not handling floating-point math 0.1 + 0.2 !== 0.3 (yes, really). ✅ Use libraries like decimal.js or round your values when precision matters. ⸻ These are small details — but they separate good JavaScript from great JavaScript. 💬 What’s a JS mistake you’ve seen (or made) that taught you something valuable? #JavaScript #WebDevelopment #Programming #CodingTips #Frontend
To view or add a comment, sign in
-
Ever seen a variable live even after its function is done? 🤔 That’s not a bug — that’s Closure, one of JavaScript’s most powerful (and tricky) features 💡 Let’s look at a simple example 👇 function counter() { let count = 0; return function () { count++; console.log(count); }; } const increment = counter(); increment(); // 1 increment(); // 2 increment(); // 3 Wait… how does count still remember its value? Didn’t the counter() function finish already? 😅 Here’s the magic 🪄 > A closure allows a function to “remember” the variables from the scope in which it was created — even after that scope is gone. In this example, The inner function still has access to count, Because it closes over the variables from its outer function. That’s why we call it a Closure 🔁 Closures are the reason we can create: ✅ Private variables ✅ Function factories ✅ Modular, memory-efficient code In short — > A closure is how JavaScript gives functions memory 🧠 #JavaScript #Closures #WebDevelopment #Frontend #MERNStack #NodeJS #ReactJS #Coding #SoftwareEngineering #Developers #JSFundamentals
To view or add a comment, sign in
-
🚀 JavaScript isn’t just a language — it’s pure magic that runs the web! Let’s do a quick JS challenge 👇 👉 Guess what this code will print: console.log(typeof null); Most people say "null", but surprise — the answer is actually "object" 😲 That’s one of JavaScript’s oldest quirks — a bug that became a feature! It reminds us that no language is perfect, but JavaScript’s flexibility and weirdness are what make it so powerful. 💪 💬 Now your turn: What’s the most confusing or fun JS behavior you’ve encountered? Drop it in the comments — let’s see who can out-weird JavaScript today! ⚡ #JavaScript #Coding #WebDevelopment #ProgrammingHumor #LearnToCode
To view or add a comment, sign in
Full Stack Engineer | React, Node.js, TypeScript, Python | Generative AI
2wThanks for sharing 👍