𝐂𝐥𝐨𝐬𝐮𝐫𝐞𝐬 𝐞𝐱𝐩𝐥𝐚𝐢𝐧 𝐰𝐡𝐲 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 𝐢𝐧 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐝𝐨𝐧’𝐭 𝐟𝐨𝐫𝐠𝐞𝐭 𝐭𝐡𝐞𝐢𝐫 𝐨𝐫𝐢𝐠𝐢𝐧𝐬. For a long time, I knew that functions could be assigned to variables, passed into other functions, and even returned — yet they continued to work correctly long after their outer function had finished executing. That behavior felt counterintuitive at first. The clarity came from understanding 𝐥𝐞𝐱𝐢𝐜𝐚𝐥 𝐬𝐜𝐨𝐩𝐢𝐧𝐠. In JavaScript, a 𝐜𝐥𝐨𝐬𝐮𝐫𝐞 is created when a function is bundled together with its 𝐥𝐞𝐱𝐢𝐜𝐚𝐥 𝐞𝐧𝐯𝐢𝐫𝐨𝐧𝐦𝐞𝐧𝐭. When a function is returned from another function, it doesn’t lose access to the variables it needs. Instead, it retains references to the scope where it was originally defined. What made this click for me: • Functions can be 𝐚𝐬𝐬𝐢𝐠𝐧𝐞𝐝 𝐭𝐨 𝐯𝐚𝐫𝐢𝐚𝐛𝐥𝐞𝐬 and 𝐩𝐚𝐬𝐬𝐞𝐝 𝐚𝐬 𝐚𝐫𝐠𝐮𝐦𝐞𝐧𝐭𝐬 • Returned functions 𝐩𝐫𝐞𝐬𝐞𝐫𝐯𝐞 𝐭𝐡𝐞𝐢𝐫 𝐥𝐞𝐱𝐢𝐜𝐚𝐥 𝐬𝐜𝐨𝐩𝐞 • Closures maintain 𝐬𝐭𝐚𝐭𝐞 𝐚𝐜𝐫𝐨𝐬𝐬 𝐞𝐱𝐞𝐜𝐮𝐭𝐢𝐨𝐧𝐬 • This behavior holds true even in 𝐚𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐨𝐮𝐬 𝐜𝐨𝐝𝐞 This shifted how I think about real-world JavaScript patterns. Closures form the backbone of: • 𝐌𝐨𝐝𝐮𝐥𝐞 𝐝𝐞𝐬𝐢𝐠𝐧 𝐩𝐚𝐭𝐭𝐞𝐫𝐧𝐬 • 𝐂𝐮𝐫𝐫𝐲𝐢𝐧𝐠 𝐢𝐧 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 • Utility functions like 𝐨𝐧𝐜𝐞 • Managing state in the 𝐚𝐬𝐲𝐧𝐜 𝐰𝐨𝐫𝐥𝐝 (setTimeout, callbacks) Once closures are seen as a natural outcome of lexical scoping, they stop feeling mysterious — and start feeling intentional. #JavaScript #SoftwareEngineering #ProblemSolving #DeveloperJourney #LearningInPublic #TechCommunity #ContinuousLearning Picture Credit :- Ayush Verma
Understanding JavaScript Closures and Lexical Scoping
More Relevant Posts
-
✨ 𝗗𝗮𝘆 𝟴 𝗼𝗳 𝗠𝘆 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗝𝗼𝘂𝗿𝗻𝗲𝘆 🚀 Today I explored 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗢𝗯𝗷𝗲𝗰𝘁𝘀 𝗮𝗻𝗱 𝘁𝗵𝗲𝗶𝗿 𝗠𝗲𝗺𝗼𝗿𝘆 𝗠𝗮𝗻𝗮𝗴𝗲𝗺𝗲𝗻𝘁 𝗶𝗻-𝗱𝗲𝗽𝘁𝗵, and learned how objects are actually structured behind the scenes in memory. I discovered that JavaScript objects are stored in the heap, and the variable holds a reference (pointer) in the stack. But what’s more interesting is that internally, objects have different pointers: • 𝗠𝗮𝗽 𝗣𝗼𝗶𝗻𝘁𝗲𝗿 → points to the object’s hidden class (structure and layout of properties) • 𝗣𝗿𝗼𝗽𝗲𝗿𝘁𝗶𝗲𝘀 𝗣𝗼𝗶𝗻𝘁𝗲𝗿 → points to where named properties are stored • 𝗘𝗹𝗲𝗺𝗲𝗻𝘁𝘀 𝗣𝗼𝗶𝗻𝘁𝗲𝗿 → points to indexed elements (used especially in arrays) This explains how JavaScript engines optimize objects for performance and access speed. Understanding these low-level details helps me see JavaScript beyond syntax — it’s helping me understand how things really work under the hood. Building strong fundamentals step by step. #JavaScript #100DaysOfCode #WebDevelopment #LearningJourney #FrontendDevelopment #ComputerScience
To view or add a comment, sign in
-
-
🔍 Prototypes and this in JavaScript — going beyond the syntax into the actual mechanics. Here's what's worth knowing: 🧬 On Prototypes Methods aren't copied to every object instance. They live once on the prototype — all instances share them via reference. That's how JS stays memory efficient even with thousands of objects. Every method lookup is a live chain traversal, every single time. Object.create is pure prototype wiring — it sets the [[Prototype]] of a new object. That's it. 🎯 On this — four rules, in priority order 1️⃣ new binding → this = newly created object 2️⃣ Explicit binding → .call() .apply() .bind() — you decide 3️⃣ Implicit binding → obj.method() — this = object left of the dot 4️⃣ Default binding → standalone call — this = window or undefined Arrow functions sit outside all four rules — they inherit this lexically from wherever they were defined. ⚠️ The classic trap js setTimeout(this.log, 1000); // this is lost Detach a method from its object and this evaporates. Fix → arrow wrapper, .bind(), or bind in the constructor. Each has different tradeoffs. 🧠 On EventEmitters and memory Per-instance state must always be initialized in the constructor. If it accidentally lands on the prototype — every instance shares the same object. Emitting on one instance fires callbacks registered on all instances. Silent. No error thrown. Every .on() listener holds a closure reference — keeping objects alive in memory long after they're "destroyed." Always implement .off(). Always clean up. Follow along — sharing one deep dive at a time. 🚀 #JavaScript #Prototypes #FrontendEngineering #WebPerformance #PlatformEngineering
To view or add a comment, sign in
-
🚀 Understanding Variables & Functions in JavaScript (Behind the Scenes) When we declare a variable or write a function in JavaScript, a lot happens internally before execution. • Memory Creation Phase Before running the code, JavaScript allocates memory: Variables are stored in memory. If declared with var, they are initialized as undefined. Functions are fully stored in memory (hoisted completely). • Execution Phase Now the code runs line by line. Values replace undefined, and functions execute when called. • Stack & Heap Stack Memory → Stores primitive values and function execution context. Heap Memory → Stores objects, arrays, and reference types. • Main Thread JavaScript is single-threaded. All variables, functions, and execution contexts go through the Call Stack (main thread). • Why Memory Address Matters? For reference types, the variable doesn’t store the actual value — it stores the address pointing to heap memory. That’s why copying objects behaves differently from copying primitives. Understanding this helps in: ✔ Avoiding bugs ✔ Writing optimized code ✔ Understanding hoisting ✔ Managing memory better JavaScript may look simple, but internally it follows a well-structured execution model. #JavaScript #WebDevelopment #MemoryManagement #DSA #Frontend Vikas Kumar Pratyush Mishra
To view or add a comment, sign in
-
-
🧠Mastering JavaScript — One Concept at a Time (2/32) Today I am very happy because my understanding of hoisting, scope, and sharing with you is now complete. 🔥Scope in Real Life Scope simply means: Where can I access this variable? Block Scope → Code inside {} like in loops, if , etc. Function Scope → Code inside a function let and const follow block scope. var ignores block scope — which leads to bugs. 🧨Hoisting JavaScript prepares memory before running code. It moves all declarations to the top — this is called hoisting. But: var is hoisted and set to undefined let and const are hoisted but not initialised — so accessing them early gives ReferenceError ⚠Common Confusions (JS Reality Checks) const doesn't make things fully constant. It protects the variable, not the value. var is outdated — it's better to use let and const let and const behave similarly, but const gives more safety use it when you're not planning to reassign. 🧠 Mindset Rule Use const by default. Use let only when you plan to change the value. Avoid var — it belongs to the past. Revisiting these fundamentals makes JavaScript feel less “magical” and more predictable. In the next post, I’ll go deeper into how the Data Type and Type System. How long did it take you to understand scope and hoisting truly? #JavaScript #LearningInPublic #WebDevelopment #FrontendDevelopment #MasteringJavaScript
To view or add a comment, sign in
-
🔍 Understanding Scope & Lexical Environment in JavaScript If you’ve ever wondered how JavaScript knows where a variable lives, the answer lies in scope and the lexical environment. 📌 Scope Scope determines where variables are accessible in your code. let globalVar = "I am global"; function outer() { let outerVar = "I am outer"; function inner() { let innerVar = "I am inner"; console.log(globalVar); // Accessible console.log(outerVar); // Accessible console.log(innerVar); // Accessible } inner(); } outer(); Each function creates its own scope, but inner functions can access variables from outer scopes. 📌 Lexical Environment A lexical environment is created whenever JavaScript executes code. It consists of: • Local variables • References to its outer environment This is why JavaScript supports closures — functions remember where they were created. function counter() { let count = 0; return function() { count++; console.log(count); }; } const increment = counter(); increment(); // 1 increment(); // 2 Even after counter() finishes, the inner function remembers count. ⸻ 💡 Key Takeaway: • Scope → Where variables can be accessed • Lexical Environment → How JavaScript keeps track of those variables Understanding this is key to mastering closures, hoisting, and the execution context. #JavaScript #WebDevelopment #Frontend #Closures #Scope #CodingInterview
To view or add a comment, sign in
-
🚀 JavaScript Hoisting Explained Clearly Most developers hear about hoisting… But very few truly understand what actually happens behind the scenes. Let’s break it down. When JavaScript runs your code, it does NOT execute it line by line immediately. First, it creates something called the Execution Context. There are two main phases: 1️⃣ Creation Phase (Hoisting Phase) 2️⃣ Execution Phase 🔵 Creation Phase (Hoisting Phase) During this phase: • Memory is allocated for variables and functions • Function declarations are stored completely in memory • var variables are initialized with undefined • let and const are hoisted but remain in the Temporal Dead Zone (TDZ) Example that works: greet(); function greet() { console.log("Hello"); } Example that throws an error: sayHi(); const sayHi = function () { console.log("Hi"); }; Reason: Only the variable is hoisted, not the function expression. 🔴 Execution Phase Now JavaScript executes the code line by line. • Variables receive their actual values • Functions run when called Important Insight Hoisting does NOT mean JavaScript moves your code to the top. It means JavaScript allocates memory before execution begins. If you understand hoisting deeply, you automatically understand: • Execution Stack • Scope Chain • Closures • TDZ • var vs let vs const Master this concept once, and JavaScript starts making real sense. #JavaScript #WebDevelopment #Frontend #ExecutionContext #Hoisting #LearnToCode #Programming #Developers
To view or add a comment, sign in
-
-
Most developers reach for IDs, classes, or extra state before remembering this: JavaScript already gives you a clean way to attach structured metadata directly to DOM elements. If you have ever used data-* attributes in HTML, you can access them in JavaScript through the dataset property. No parsing. No brittle string manipulation. No unnecessary DOM lookups. It is simple, readable, and surprisingly underused. This pattern is especially useful for event delegation, lightweight UI state, dynamic lists, and keeping behaviour close to the element it belongs to. Small details like this make frontend systems cleaner and easier to reason about without introducing extra abstractions. Not everything needs global state. Sometimes the platform already solved the problem. In the example attached, notice how `data-user-id` becomes `dataset.userId`. Hyphenated attributes automatically convert to camelCase. It is a small feature, but small features compound into cleaner, more maintainable frontend code. What is one underrated JavaScript feature you think more developers should use? Github Gist: https://lnkd.in/d6pjMP7J #webdevelopment #javascript #cleancode
To view or add a comment, sign in
-
-
📌 Understanding Array.from() in JavaScript When working with array-like or iterable objects in JavaScript, we often need a clean way to convert them into real arrays. That’s where Array.from() becomes incredibly useful. 👉 What is Array.from()? 💠 Array.from() creates a new array from: 🔹 Array-like objects (e.g., NodeList, arguments) 🔹 Iterable objects (e.g., strings, Sets, Maps) 👉 In simple terms: It converts “not exactly arrays” into proper arrays. 👉 Why is it Important? 🔹 Converts DOM collections into arrays 🔹 Helps generate dynamic arrays 🔹 Supports transformation while creation 🔹 Cleaner alternative to loops Array.from() is a powerful utility method that simplifies working with iterable and array-like data structures. Mastering it improves code readability and makes your JavaScript more expressive and efficient. #JavaScript #Frontend #WebDevelopment #CodingTips #LearnToCode
To view or add a comment, sign in
-
-
#Hello_Connections #Day16 of #100DaysofCodeChallenge Project Name: JavaScript Calculator Details:Built a fully functional Calculator using HTML, CSS, and JavaScript that performs basic arithmetic operations with a clean and responsive UI. What I Focused On: DOM manipulation with JavaScript Handling button click events Implementing calculation logic Using JavaScript string methods for delete functionality Creating a structured grid layout using CSS Grid Key Features: Perform basic arithmetic operations (+ − × ÷) AC (clear all) and DEL (delete last digit) functionality Responsive grid-based button layout Clean modern UI with gradient background Challenges:Handling invalid expressions and preventing the calculator from breaking when incorrect inputs are entered. How I Solved It:Used a try...catch block around the eval() function to safely evaluate expressions and display "Error" when invalid calculations occur. This project helped me practice JavaScript event handling, DOM manipulation, and building functional UI components. Code Of School -Avinash Gour & Ritendra Gour #Day16 #100DaysOfCode #FrontendDevelopment #HTML #CSS #JavaScript #WebDevelopment #LearningInPublic 🚀
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗥𝗲𝗮𝗹 𝗥𝗲𝗮𝘀𝗼𝗻 𝗪𝗵𝘆 𝗧𝘆𝗽𝗲𝗼𝗳([]) 𝗥𝗲𝘁𝘂𝗿𝗻𝘀 "𝗢𝗯𝗷𝗲𝗰𝘁" You've seen this before: typeof [] // "object" You think: that's an array, why does JavaScript say it's an object? Let's look at why this happens. In JavaScript, typeof returns one of these values: -undefined- "boolean" - "number" -string- "bigint" - "symbol" -function- "object" Notice what's missing? There's no "array". This is not an accident. In JavaScript, arrays are not a separate type. When you write const arr = [], you're actually doing const arr = new Array(). Array is a constructor that creates an object. So, typeof [] returnsobject because arrays are specialized objects with: - Numeric keys - A dynamic length property - Built-in methods like map, filter, reduce For example: const arr = ["a", "b"] console.log(Object.keys(arr)) // ["0", "1"] console.log(arr.length) // 2 Internally, it behaves like an object with special behavior. In the ECMAScript spec, arrays are called “exotic objects”. Why didn't JavaScript make typeof [] return "array"? Two reasons: - Historical design: JavaScript was created in
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