Why do some functions return another function(s) if we can just call the function whenever we need it? At first this feels unnecessary. If a function can already run when we call it, why would we want that function to return another function instead of just executing the logic immediately? The reason is that sometimes we want to create a function that remembers certain information for later use. Instead of passing the same data again and again every time we call a function, we can create a function that already remembers that data and uses it whenever it runs. So in some cases we are not just executing a function — we are creating a new function that carries some context with it. This behavior leads us to an important concept in JavaScript called Closures. A closure happens when a function remembers variables from the scope where it was created, even after that outer function has finished executing. Normally, when a function finishes running, its local variables should disappear. But if another function still references them, JavaScript keeps those variables alive. Closures are widely used in JavaScript for things like: • Creating private variables • Preserving state between function calls • Avoiding unnecessary global variables • Remembering configuration values • Supporting callbacks and asynchronous code In the example attached below, you can see how a function is able to access a variable that technically belongs to an outer scope. This happens because of lexical scoping, where a function remembers the environment in which it was created. Closures might seem like a small concept, but they explain many important patterns in JavaScript. A function in JavaScript doesn’t just carry its code. It also carries the environment where it was created. #javascript #closures #chaicode #chaiaurcode
Understanding JavaScript Closures and Lexical Scoping
More Relevant Posts
-
const variables cannot change. So why does this code print 0, 1, 2? When I first learned JavaScript, one thing confused me a lot. We all know: const → cannot be reassigned. But then in real projects I kept seeing this: for (let i = 0; i < 3; i++) { const value = i; console.log(value); } And the output becomes: 0 1 2 Wait… if const cannot change, how is the value changing every loop? The interesting part — it actually doesn’t change. Each loop iteration creates a new block scope, which means a new value variable is created every time. So JavaScript is not updating the same variable. It’s creating a completely new one in each iteration. Understanding this made several JavaScript concepts click for me: var • Function scoped • Hoisted and initialized with undefined • Can be reassigned and redeclared let • Block scoped • Hoisted but trapped in the Temporal Dead Zone (TDZ) until initialization • Can be reassigned but not redeclared const • Block scoped • Also lives in the TDZ • Must be initialized during declaration • Cannot be reassigned This is why most developers prefer using const by default: ✅ Prevents accidental reassignment ✅ Makes code easier to reason about ✅ Keeps variables predictable in larger codebases Only switch to let when reassignment is actually needed. Small JavaScript details like this often look simple… until you start thinking about how they actually work. I want to know which JS behavior made you go “Wait… what?!” the first time you saw it?
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗡𝗲𝗪 𝗞𝗲𝗬𝗪𝗼𝗥𝗱 𝗜𝗡 𝗝𝗮𝗩𝗮𝗦𝗰𝗿𝗶𝗽𝗧 You use the new keyword to create instances from classes in JavaScript. But what does new actually do? - It tells JavaScript to treat a function as a constructor and create a new object instance. - It links the new object's prototype to the constructor's prototype. - It binds this to the new object. - It executes the constructor body. - It returns the new object. When you use new with a constructor function, JavaScript performs these steps. - Creates a new empty object. - Links the new object's prototype to the constructor's prototype. - Binds this to the new object. - Executes the constructor body. - Returns the new object. For example: ``` is not allowed, using plain text instead function Person(name, age) { this.name = name; this.age = age; } const ritam = new Person("Ritam", 22); This creates a new instance with its own properties, linked to the shared prototype. You can add methods to the prototype: Person.prototype.sayHello = function() { console.log(`Hi, I'm ${this.name}`); }; Each instance has its own properties, but they share the same prototype methods. Understanding the new keyword is key to how JavaScript's object system works. Source: https://lnkd.in/gsGQpDeR
To view or add a comment, sign in
-
One JavaScript feature that quietly makes your code cleaner and safer: 👉 Optional Chaining (?.) Before: const city = user && user.address && user.address.city; Or worse… nested if checks everywhere. Now: const city = user?.address?.city; What’s actually happening? 👉 If anything in the chain is null or undefined, JavaScript just stops—and returns undefined instead of crashing. No more: “Cannot read property 'x' of undefined” It gets even better: user?.getProfile?.(); Calls the function only if it exists No more “is not a function” errors But here’s the part many people miss: 👉 Optional chaining hides errors if you overuse it If something should exist and doesn’t, ?. will quietly return undefined… and your bug becomes harder to notice. Rule of thumb: • Use ?. for optional data (API responses, external input) • Avoid it for required logic (core business rules) JavaScript gives you tools to write safer code. 👉 The real skill is knowing when not to use them. Do you use optional chaining everywhere—or selectively? #softwareengineering #javascript #codequality #webdevelopment
To view or add a comment, sign in
-
🚀 JavaScript Variables (var, let, const) & Hoisting. Before JavaScript executes your code… Have you ever wondered where variables are stored? 🤔 🧠 What is a Variable? A variable is a named container used to store data. ⚙️ JavaScript gives us 3 ways to declare variables: var a = 10; let b = 20; const c = 30; 🧠 What is Hoisting? 👉 Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before execution. 👉 In simple words: You can access variables and functions even before they are initialized. 📦 Example with var: console.log(x); // undefined var x = 5; 🚫 Example with let: console.log(y); // ❌ ReferenceError let y = 10; 🔒 Same with const: console.log(z); // ❌ ReferenceError const z = 15; 🎯 Key Differences: • var → hoisted + initialized (undefined) • let & const → hoisted but NOT initialized (Temporal Dead Zone) 👉 “In the next post, we’ll dive into Scope — the concept that truly defines how variables behave in JavaScript.” #JavaScript #WebDevelopment #Frontend #Coding
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗡𝗲𝗪 𝗞𝗲𝗬𝗪𝗼𝗥𝗱 𝗜𝗡 𝗝𝗮𝗩𝗮𝗦𝗰𝗿𝗶𝗽𝗧 You use the new keyword to create instances from classes in JavaScript. But what does new actually do? - It tells JavaScript to treat a function as a constructor and create a new object instance. - It links the new object's prototype to the constructor's prototype. - It binds this to the new object. - It executes the constructor body. - It returns the new object. Here's an example: ``` is not allowed, so function Person(name, age) { this.name = name; this.age = age; } const ritam = new Person("Ritam", 22); JavaScript does these steps: - Creates a new empty object. - Links the new object's prototype to Person.prototype. - Binds this to the new object. - Executes the constructor body. - Returns the new object. This creates a fully-formed instance with its own properties, linked to the shared prototype. - Every instance has an internal link pointing to the constructor's prototype object. - You can add methods to the prototype, and all instances will share them. Using new gives you a unique instance each time: - const ritam = new Person("Ritam", 22); - const priya = new Person("Priya", 20); Each instance has its own properties, but they share the same prototype methods. Understanding the new keyword helps you debug prototype chains and write advanced patterns. Source: https://lnkd.in/gsGQpDeR
To view or add a comment, sign in
-
6 days ago I made a post on: 📌 "Something i figured in JavaScript today that A.I code misinterprets." I am about to share that now, pay close attention. As a developer using JavaScript, this is in connecting with the scopes of JavaScript. The Scope of JavaScript refers to the visibility of variable and functions within a program of codes. Which are: 1. Global scope: this variable is visible anywhere in the javascript program. 2. Function scope: this is a variable created when a function is declared and it's variable and functions are only visible withing that function. A sample of it is: Function funName(){ var fs = "..." alert (fs); console.log(fs); } funName(); Now looking at this, A.I codes misinterprets the function scopes and genrate codes that carries just global scopes or even most times Interchange function scopes with global scopes when giving a variable function. 📌 The risk of this common error in our program will not appear at the beginning of the project but during debugging and code maintenance. Wonder why JavaScript bugs gives you sleepless nights? This is one of the main reasons. This is a call for developers and vibe coders to learn the intimate differences between GLOBAL SCOPE VARIABLES and FUNCION SCOPE VARIABLES. You A.I JavaScript code can cause you harm later if you do not learn this earlier. 📌 A.I. frequently misunderstands Hoisting and the Temporal Dead Zone (TDZ) when creating nested functions. It often defaults to legacy var logic within closure loops (because the bulk of the training data still uses it) rather than modern let/const for block scoping. It optimizes for visual syntax, not runtime safety. Automation without technical intuition creates technical debt. Want more daily strategy from the cutting edge of web infrastructure? connect with snow works #WorksTechnology #JavaScriptMastery #CodingArchitecture #AIPerformance #TechnicalIntuition #WebArchitecture #SoftwareDesign #WebDevStrategy
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗠𝗮𝗴𝗶𝗰 𝗢𝗳 𝘁𝗵𝗶𝘀 𝗜𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 You use JavaScript to create objects and functions. The `this` keyword is related to the prototype mechanism. This mechanism is a look-up chain for properties and inheritance. You can create an object from a function. This led to the concept of fake classes. Classes mimic objects and functions. But some authors say trying to bring class and inheritance design patterns to JavaScript is not a good idea. JavaScript uses prototypal inheritance. This is different from class-based inheritance. You should understand behavior delegation. This is a powerful design pattern that replaces the need for classes and inheritance. When you add a new property to an object's prototype, you can access it later. This is because the prototype property is linked to the object. You should learn how the object prototype system works. You need to understand how JavaScript thinks. The recommended way to inherit properties in JavaScript is through prototype chaining. This is better for performance. Here are some key things to know: - What `this` means inside normal functions - What `this` means inside objects - What `call()` does - What `apply()` does - What `bind()` does Source: https://lnkd.in/gGJwEWxg
To view or add a comment, sign in
-
Small JavaScript detail. Big source of bugs. Look at this code. let num1 = 8 let num2 = 2 console.log("Sum: " + num1 + num2); Many expect the output: Sum: 10 The real output: Sum: 82 Reason. JavaScript reads from left to right. The moment it hits a string, it converts the rest into string concatenation. Step by step execution. "Sum: " + 8 → "Sum: 8" "Sum: 8" + 2 → "Sum: 82" Fix the problem by calculating first. let total = num1 + num2; console.log("Sum: " + total); Output: Sum: 10 Takeaway. When combining numbers and strings in JavaScript, perform the calculation first. Then concatenate the result. Small detail. Cleaner code. Fewer bugs.
To view or add a comment, sign in
-
⚠️ JavaScript Function Expression — A Common Corner Case That Trips Developers 🔍 The Corner Case: Hoisting Behavior console.log(add(2, 3)); // ❌ TypeError: add is not a function var add = function(a, b) { return a + b; }; 👉 Why does this fail? Because only the variable declaration (var add) is hoisted, not the function itself. So internally, JavaScript sees this as: var add; console.log(add(2, 3)); // ❌ add is undefined add = function(a, b) { return a + b; }; ✅ Now Compare with Function Declaration console.log(add(2, 3)); // ✅ 5 function add(a, b) { return a + b; } 👉 Entire function is hoisted — so it works! 💥 Another Tricky Case (Named Function Expression) const foo = function bar() { console.log(typeof bar); }; foo(); // ✅ function bar(); // ❌ ReferenceError: bar is not defined 👉 bar is only accessible inside the function, not outside! 🎯 Key Takeaways ✔ Function expressions are NOT fully hoisted ✔ Only variable declarations are hoisted (var, let, const behave differently) ✔ Named function expressions have limited scope ✔ Always define function expressions before using them #JavaScript #Frontend #CodingInterview #WebDevelopment #JSConcepts #100DaysOfCode
To view or add a comment, sign in
-
"Var and functions move to the top of your file" ...but do they? Really? Think about it. Open any JavaScript file right now. Add a console.log before a var declaration. Run it. You get undefined — not an error. Call a function 50 lines before you've even written it. It works. Perfectly. Now try the same thing with let or const. It crashes. ReferenceError. If hoisting truly "moves code to the top" — why doesn't it move let and const too? Because nothing is moving anywhere. That explanation you've been hearing since day one? It's a lie. A convenient, oversimplified lie that every tutorial keeps repeating. The truth is — JavaScript reads your code twice. Yes. Twice. The first time, it doesn't execute anything. It just scans your entire file and quietly builds a memory map. Every var it finds gets stored as undefined. Every function gets stored completely. Every let and const gets stored too — but locked. Untouchable. Frozen until their exact line is reached. The second time, it actually runs your code. Line by line. And because memory was already set up, accessing a var before its declaration doesn't crash — it simply finds undefined sitting there, waiting. Nothing moved to the top. The engine just remembered it before you asked. This process has a name that most JavaScript developers have never properly learned — the Execution Context and its two phases. And once you understand it, JavaScript stops being weird. Closures make sense. Scope chains make sense. Even the this keyword starts clicking. I broke this down with code examples and step-by-step visuals on Medium. Link in comments 👇 #JavaScript #WebDevelopment #Programming #SoftwareEngineering #NodeJS #BackendDevelopment
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