I've read the definition of closures probably 10 times. "A function bundled with its lexical scope." Made sense on paper. But I never truly got it until I came across the backpack analogy. Here's how it actually works: When a function is returned from a higher order function, it doesn't leave empty handed. It carries a backpack. That backpack is attached via a hidden [[scope]] link and contains persistent memory of the variables from its outer environment, even after that outer function has finished executing. The data lives on. Attached to the function. Quietly. And once I understood that, everything clicked: → once() runs a function exactly one time, then remembers it already ran → memoize() caches previous results so you never compute the same thing twice → iterators maintain position in a sequence across multiple calls → module pattern keeps variables private, exposes only what you choose → async programming lets callbacks remember the context they were created in All of these are closures in action. I've been writing JavaScript for 3 years. Going back to the fundamentals has been humbling and genuinely eye opening. If you've been skimming over closures, I'd recommend diving deep. It changes how you read code. #javascript #webdevelopment #softwareengineering #frontenddevelopment #continuouslearning
Karan Sandhu’s Post
More Relevant Posts
-
JavaScript hoisting is one of those things that feels like the language gaslighting developers collectively for 25+ years. console.log(a); var a = 10; JavaScript: “Oh, you meant this a? Yeah I know her.” No ReferenceError. Just undefined sitting there like it was invited to the meeting. Now try this: console.log(b); let b = 10; JavaScript suddenly becomes a strict Victorian school principal: “ABSOLUTELY NOT. Access before initialization? Straight to jail.” What’s funny is that somewhere along the way, an actual language quirk became so deeply woven into developer workflows that people started defending it like a beloved feature. One developer’s “this is clearly broken behavior” is another developer’s: “Actually, this is part of JavaScript’s execution context creation phase ” Your bug is my feature. Your chaos is my backward compatibility. Your 6 is my 9. At this point, I’m convinced half of software engineering is just humans emotionally adapting to historical accidents in programming languages. And honestly? That might be the most human thing about code. #javascript
To view or add a comment, sign in
-
Day 01: Precision Matters 🔢 Kicking off my coding journey by tackling a classic: The Plus Minus Challenge. The Problem: Given an array of integers, calculate the ratios of positive numbers, negative numbers, and zeros. The catch? The output must be precise to six decimal places. The Solution: It’s all about iteration and formatting. By looping through the array and categorizing each element, we can determine the counts. The key to meeting the precision requirement in JavaScript is using the .toFixed(6) method. javascript function plusMinus(arr) { let n = arr.length; let positive = 0, negative = 0, zero = 0; for(let val of arr) { if(val > 0) positive++; else if(val < 0) negative++; else zero++; } console.log((positive/n).toFixed(6)); console.log((negative/n).toFixed(6)); console.log((zero/n).toFixed(6)); } plusMinus(arr); Key Takeaway: Even simple logic requires attention to detail—especially when it comes to floating-point precision! #CodingChallenge #JavaScript #ProblemSolving #100DaysOfCode #DataStructures
To view or add a comment, sign in
-
Last night, I was debugging an API flow that should have taken 5 minutes… but it didn’t 😅 The code looked like this: .then().then().then().catch() And somewhere in that chain, things broke. Finding it? Painful. ⚠️ Problem Promise chains are powerful, but as they grow: • Hard to read 👀 • Error handling gets messy • Debugging feels like chasing shadows 💡 Solution / Insight I rewrote it using async/await: Replace .then() with await Wrap logic in try/catch Keep flow top-to-bottom Now it reads like normal code ✨ And performance? 👉 Almost identical. Both use Promises under the hood. 🧠 Takeaway It’s not about speed… it’s about clarity. Cleaner code = fewer bugs = faster dev 🚀 I share more simple dev insights here 👉 webdevlab.org 💬 Your turn Do you prefer Promise chains or async/await for real-world projects? #javascript #webdevelopment #asyncawait #programming #softwareengineering
To view or add a comment, sign in
-
-
𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗦𝗵𝗮𝗹𝗹𝗼𝘄 𝗖𝗼𝗽𝘆 𝘃𝘀 𝗗𝗲𝗲𝗽 𝗖𝗼𝗽𝘆 📦 If you’ve ever updated state and something weird happened… this might be why 👇 🔹 Shallow Copy → copies only the first level 🔹 Nested objects are still referenced (same memory) Example: ➡️ Using { ...obj } or Object.assign() 💡 Problem: Change a nested value… and you might accidentally mutate the original object 😬 🔹 Deep Copy → copies everything (all levels) 🔹 No shared references 🔹 Safe to modify without side effects Example: ➡️ structuredClone(obj) ➡️ or libraries like lodash ⚠️ The common pitfall: You think you made a copy: ➡️ { ...user } But inside: ➡️ user.address.city is STILL linked So when you update it: ❌ You mutate the original state ❌ React may not re-render correctly ❌ Bugs appear out of nowhere 🚀 Why this matters (especially in React): State should be immutable ➡️ Always create safe copies ➡️ Avoid hidden mutations ➡️ Keep updates predictable 💡 Rule of thumb: 🔹 Flat objects? → shallow copy is fine 🔹 Nested data? → consider deep copy Understanding this difference = fewer bugs + cleaner state management And yes… almost every developer gets burned by this at least once 😄 Sources: - JavaScript Mastery - w3schools.com Follow 👨💻 Enea Zani for more #javascript #reactjs #webdevelopment #frontend #programming #coding #developers #learnjavascript #softwareengineering #100DaysOfCode
To view or add a comment, sign in
-
-
🤔 Ever wondered… Why this works: console.log(a) // undefined var a = 10; But this crashes: console.log(b) // ReferenceError let b = 20; Even though both are declared later? 👉 This is where most developers think they understand JavaScript… but they don’t. 🚀 Let’s break it down: Hoisting & Temporal Dead Zone (TDZ) 🧠 Hoisting (What actually happens behind the scenes) JavaScript doesn’t execute your code line by line directly. Before execution, it runs a Memory Creation Phase where: • Variables & functions are registered in memory • Declarations are processed first 👉 This is what we call hoisting 📦 Variable Hoisting With var: • Declaration is hoisted • Initialized with undefined So: • You can access it before declaration • But you won’t get the actual value , since Initialized with undefined in memory creation phase 💡 Key insight: Hoisting ≠ moving code It’s about how memory is allocated internally. ⚠️ let & const → Temporal Dead Zone (TDZ) Yes — let and const are also hoisted. But… They stay in a Temporal Dead Zone from: 👉 start of scope → until declaration line Accessing them early = 💥 ReferenceError 💡 Takeaway: TDZ exists to prevent unpredictable bugs caused by premature access. 👑 Function Hoisting (VIP behavior) Function Declarations are fully hoisted: ✔ You can call them before declaration But Function Expressions behave differently: • var → undefined • let/const → ReferenceError ⚡ Why this actually matters (not just theory) Understanding hoisting + TDZ helps you: • Avoid silent bugs (undefined issues) • Write predictable, cleaner code • Debug scope-related issues faster • Truly understand how JS engine works 💡 Final Thought: Most developers memorize hoisting. Good developers understand execution context. Great developers write code that doesn’t depend on hoisting at all. 📌 I’ll be sharing more deep dives like this as I learn & build in public. Follow along if you’re into JavaScript internals 🚀 #JavaScript #FrontendDevelopment #WebDevelopment #Hoisting #TDZ #LearnJavaScript #CodingTips #BuildInPublic #100DaysOfCode
To view or add a comment, sign in
-
-
I spent hours stuck on a “simple” problem… sorting an array. No tutorial. No copy-paste. Just confusion, frustration, and trial & error. At first, nothing made sense: * Why isn’t my logic working? * Why do I need multiple loops? * Why does swapping break everything? But instead of escaping the discomfort… I stayed. I wrote it. Broke it. Rewrote it. Questioned everything. And then it clicked. I built my own custom sorting method (Bubble Sort) from scratch in JavaScript — not by memorizing, but by understanding. Biggest lesson from this: 👉 Real growth happens when you **sit with confusion instead of avoiding it 👉 Patience > Talent 👉 Struggle is not a sign of failure — it's the path to clarity Also learned: * Sorting is NOT about picking values, it's about **comparing & swapping repeatedly** * One pass is never enough — algorithms evolve step by step * Understanding beats memorization every single time Sharing my final implementation below👇 Course Instructor: Rohit Negi | Youtube Channel: CoderArmy #JavaScript #codiing #WebDevelopment #LearningInPublic #ProblemSolving #fullstackdevelopment
To view or add a comment, sign in
-
-
🚀 For...Of Loop — which many developers don’t know! Most developers use for or forEach()… but often overlook one of the cleanest loops in JavaScript 👇 🔹 for Loop (Traditional) ✔ Full control (index, conditions, steps) ✔ Best for complex logic 🔹 for...of Loop (Often Overlooked ⭐) ✔ Direct access to values ✔ Cleaner & more readable ✔ Works with arrays, strings, maps, sets 🔹 forEach() Loop ✔ Simple & functional style ✔ Great for quick operations ⚠️ Cannot use break or continue 💡 Quick Tip: Need control? → for Need clean value iteration? → for...of Need simple function execution? → forEach() 🔥 Start using for...of more — it makes your code cleaner and easier to read! #JavaScript #WebDevelopment #Coding #Frontend #Programming #Developers #LearnToCode
To view or add a comment, sign in
-
-
There's always something to gain from going back to the fundamentals. Between client projects and building out systems, I've been carving out time to sharpen my JavaScript. Recently covered: → Primitive vs Reference Data Types → Number, Null, Undefined, BigInt, and Symbols → The typeof operator → Ternary operators → Introduction to Object Destructuring None of this is glamorous. But the designers and developers who write clean, predictable code are almost always the ones who took the fundamentals seriously. Still a few more concepts on the list. Sharing the progress as I go. #JavaScript #WebDevelopment #Webflow #LearningInPublic
To view or add a comment, sign in
-
-
Today was one of those days where things finally clicked While working on one of my ongoing projects, I built a VS Code–like File Explorer from scratch in React — and it turned out to be a great learning experience. Here’s what I explored 🔹 Built a recursive tree structure to handle nested folders & files 🔹 Understood how recursion actually works in real UI problems 🔹 Implemented core features: → Create file / folder → Delete (with full nested structure) → Dynamic rendering 🔹 Learned an important pattern: 🔹filter + map + recursion = tree operations 🔹 Got deeper clarity on handling nested data: → Managing deeply nested state → Updating tree efficiently → Thinking recursively instead of flat logic Biggest takeaway: If you truly understand recursion, you can solve complex UI problems much more cleanly. Building real features inside projects hits very different than just watching tutorials #React #FrontendDevelopment #WebDevelopment #LearningInPublic #JavaScript #BuildInPublic
To view or add a comment, sign in
-
-
🚀 50 Weeks, 50 Projects – Week 6 Complete To push my development skills beyond tutorials, I'm continuing my 50 Weeks, 50 Projects challenge, where I build and ship one project every week. 🛠 Week 6 – API Lens: AI-Powered JSON Explorer Ever stared at a raw API response and had no idea what half the fields meant? That's exactly why I built this. Tech Stack: HTML · CSS · Vanilla JS · OpenRouter API (Mistral-7B, free tier) Design Style: Warm, human-first UI — cream tones, serif typography (Fraunces), and a layout that feels more like a notebook than a dev tool. Built specifically to be approachable for beginners. Functionality: 📋 Paste raw JSON or fetch any public API URL directly 🤖 AI explains every field in plain English — no docs needed 🌳 Interactive collapsible field tree with color-coded types ⏱ Unix timestamps decoded to human-readable dates automatically 🛡 Auto-detects response type: JWT, paginated list, error, REST 📋 One-click copy for JS, Python & cURL code snippets ⚡ 3-layer CORS proxy fallback — works with almost any public API Suggestions: I'd love feedback from the community! What other API patterns should I detect? Any features that would make this more useful in your daily workflow? Live URL : https://lnkd.in/dBcejh34 #50WeeksChallenge #BuildInPublic #WebDev #JavaScript #API #OpenSource #100DaysOfCode
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