Most bugs in JavaScript don’t come from syntax. They come from 𝐧𝐨𝐭 𝐮𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝𝐢𝐧𝐠 𝐡𝐨𝐰 𝐬𝐜𝐨𝐩𝐞 𝐚𝐜𝐭𝐮𝐚𝐥𝐥𝐲 𝐰𝐨𝐫𝐤𝐬. Today, I went back to revise one of the most important fundamentals from Akshay Saini 🚀 #NamasteJavaScript 𝐒𝐜𝐨𝐩𝐞, 𝐋𝐞𝐱𝐢𝐜𝐚𝐥 𝐄𝐧𝐯𝐢𝐫𝐨𝐧𝐦𝐞𝐧𝐭, 𝐚𝐧𝐝 𝐭𝐡𝐞 𝐒𝐜𝐨𝐩𝐞 𝐂𝐡𝐚𝐢𝐧. Let’s understand this using the image below. When the code shown in the image is executed: 1. First, it creates the 𝐆𝐥𝐨𝐛𝐚𝐥 𝐄𝐱𝐞𝐜𝐮𝐭𝐢𝐨𝐧 𝐂𝐨𝐧𝐭𝐞𝐱𝐭 (bottom box in the image) 2. When function a() is called, a 𝐧𝐞𝐰 𝐄𝐱𝐞𝐜𝐮𝐭𝐢𝐨𝐧 𝐂𝐨𝐧𝐭𝐞𝐱𝐭 is pushed to the call stack 3. When function c() is called, 𝐚𝐧𝐨𝐭𝐡𝐞𝐫 𝐄𝐱𝐞𝐜𝐮𝐭𝐢𝐨𝐧 𝐂𝐨𝐧𝐭𝐞𝐱𝐭 is created on top As, I already posted in my previous post each execution context has 𝐭𝐰𝐨 𝐩𝐚𝐫𝐭𝐬: • Memory • Code And 𝐞𝐚𝐜𝐡 𝐨𝐧𝐞 𝐚𝐥𝐬𝐨 𝐠𝐞𝐭𝐬 𝐚 𝐋𝐞𝐱𝐢𝐜𝐚𝐥 𝐄𝐧𝐯𝐢𝐫𝐨𝐧𝐦𝐞𝐧𝐭 — which contains: • Its local variables • And a 𝐫𝐞𝐟𝐞𝐫𝐞𝐧𝐜𝐞 𝐭𝐨 𝐢𝐭𝐬 𝐩𝐚𝐫𝐞𝐧𝐭’𝐬 𝐥𝐞𝐱𝐢𝐜𝐚𝐥 𝐞𝐧𝐯𝐢𝐫𝐨𝐧𝐦𝐞𝐧𝐭 (shown by arrows in the image orange box's) Now comes the most important part: 𝐒𝐜𝐨𝐩𝐞 𝐂𝐡𝐚𝐢𝐧 When c() tries to access a variable: • It first looks in 𝐢𝐭𝐬 𝐨𝐰𝐧 𝐦𝐞𝐦𝐨𝐫𝐲 • If not found → it follows the 𝐚𝐫𝐫𝐨𝐰 𝐭𝐨 𝐩𝐚𝐫𝐞𝐧𝐭 (𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐚) • If still not found → it goes to 𝐆𝐥𝐨𝐛𝐚𝐥 • If still not found → ❌ ReferenceError This 𝐩𝐚𝐭𝐡 𝐨𝐟 𝐚𝐫𝐫𝐨𝐰𝐬 is called the Scope Chain. So in this diagram: • c() does not find the variable in its own memory • It goes one level up to a( ) memory • Finds it there • And executes successfully But when we try to access the same variable from 𝐠𝐥𝐨𝐛𝐚𝐥, there is 𝐧𝐨 𝐩𝐚𝐭𝐡 𝐮𝐩𝐰𝐚𝐫𝐝 — so JavaScript throws an error. It matters where the function is written, not where it is called. That’s why it’s called 𝐋𝐞𝐱𝐢𝐜𝐚𝐥 𝐒𝐜𝐨𝐩𝐞. 𝐒𝐜𝐨𝐩𝐞 𝐢𝐬 𝐟𝐢𝐱𝐞𝐝 𝐚𝐭 𝐰𝐫𝐢𝐭𝐞 𝐭𝐢𝐦𝐞, 𝐧𝐨𝐭 𝐚𝐭 𝐫𝐮𝐧 𝐭𝐢𝐦𝐞. If you truly understand this diagram: * Closures become easy * Hoisting becomes logical * Async code becomes less “magical” * Debugging becomes 10x clearer Going back to fundamentals again and again is 𝐧𝐨𝐭 𝐚 𝐰𝐚𝐬𝐭𝐞 𝐨𝐟 𝐭𝐢𝐦𝐞. It’s what 𝐬𝐞𝐩𝐚𝐫𝐚𝐭𝐞𝐬 𝐫𝐞𝐚𝐥 𝐞𝐧𝐠𝐢𝐧𝐞𝐞𝐫𝐬 𝐟𝐫𝐨𝐦 𝐭𝐮𝐭𝐨𝐫𝐢𝐚𝐥 𝐜𝐨𝐝𝐞𝐫𝐬. Huge credit to Akshay Saini 🚀and the #NamasteJavaScript series for creating such a strong foundation in JavaScript internals. If you write JavaScript and 𝐜𝐚𝐧’𝐭 𝐝𝐫𝐚𝐰 𝐭𝐡𝐢𝐬 𝐝𝐢𝐚𝐠𝐫𝐚𝐦 𝐟𝐫𝐨𝐦 𝐦𝐞𝐦𝐨𝐫𝐲 — you’ve found your next revision topic. Back to basics. Always..🚀 Source: Namaste JavaScript – Scope Chain & Lexical Environment [https://lnkd.in/g5h-dA2P) #JavaScript #NamasteJavaScript #AkshaySaini #SoftwareEngineering #WebDevelopment #LearningInPublic #Backend #nodejs #systemdesign #Developers
Understanding JavaScript Scope Chain and Lexical Environment
More Relevant Posts
-
🔑 Master JavaScript's call, apply, and bind — Once and For All! These three methods often confuse developers, but they’re essential for controlling this context and writing flexible, reusable code. --- ⚙️ The Quick Guide: 1️⃣ call() Invokes a function immediately with a given this value and individual arguments. ```javascript func.call(thisArg, arg1, arg2, ...) ``` Use case: Borrowing methods from other objects. --- 2️⃣ apply() Invokes a function immediately with a given this value and arguments as an array. ```javascript func.apply(thisArg, [arg1, arg2, ...]) ``` Use case: Passing array data as function arguments (e.g., with Math.max). --- 3️⃣ bind() Returns a new function with a bound this value (and optional preset arguments), but doesn’t invoke it immediately. ```javascript const boundFunc = func.bind(thisArg, arg1, arg2, ...) ``` Use case: Creating function copies with fixed context for event handlers or callbacks. --- 🎯 Key Takeaway: · call() → Immediate execution, comma-separated args · apply() → Immediate execution, array args · bind() → Delayed execution, returns a bound function --- 🧠 Real-World Example: ```javascript const person = { name: 'Alice' }; function greet(greeting, emoji) { console.log(`${greeting}, ${this.name} ${emoji}`); } greet.call(person, 'Hello', '👋'); // Hello, Alice 👋 greet.apply(person, ['Hi', '😊']); // Hi, Alice 😊 const boundGreet = greet.bind(person, 'Hey'); boundGreet('🚀'); // Hey, Alice 🚀 ``` --- 💡 Pro Tip: Use bind() when you need to preserve this in async or event-driven code! --- 📌 Follow Sasikumar S for daily JavaScript breakdowns & practical tutorials ❤️ Join TechVerse Collective — A community for devs mastering fundamentals together 💌 Repost to help your network conquer this once and for all 👇 Comment — Which one do you use most: call, apply, or bind? 🤝 Connect: sasiias2024@gmail.com 💟 Deep Dive: sk-techland.web.app --- #JavaScript #WebDevelopment #Frontend #Coding #LearnJavaScript #ProgrammingTips #TechInterview #Developer #CodeNewbie #SoftwareEngineering #TechCommunity #JavaScriptTips #Bind #Call #Apply #ThisKeyword #TechVerse
To view or add a comment, sign in
-
⚙️ JavaScript – Prototypes & Classes Understanding Object-Oriented JavaScript JavaScript is not a class-based language by default. It uses prototypes to share properties and methods between objects. Understanding prototypes and classes helps you write structured, reusable, and scalable code. 🔹 What Is Prototypal Inheritance? Prototypal inheritance means objects can inherit properties and methods from other objects. Every JavaScript object has a hidden property that links it to another object called its prototype. 👉 This is how JavaScript achieves inheritance. 🔹 What Is __proto__? __proto__ is a reference to an object’s prototype. It points to the object from which properties are inherited Used internally by JavaScript Direct usage is not recommended (use Object.getPrototypeOf() instead) 👉 Through __proto__, JavaScript looks up properties in the prototype chain. 🔹 Prototype Chain When you access a property: JavaScript checks the object itself If not found, it checks its prototype Continues up the chain until null 👉 This chain is called the prototype chain. 🔹 Class Syntax (ES6) Classes are syntactic sugar over JavaScript’s prototype system. They provide a cleaner and more readable way to write object-oriented code. Under the hood, JavaScript still uses prototypes. 🔹 Constructor Method The constructor method is used to initialize object properties. Runs automatically when a new object is created Sets initial values Only one constructor per class 👉 Helps create multiple objects with similar structure. 🔹 Extending Classes (extends) The extends keyword is used to create a child class from a parent class. Child class inherits properties and methods Promotes code reuse Maintains a clean hierarchy 👉 This is inheritance using classes. 🔹 super Keyword super is used to call: Parent class constructor Parent class methods 👉 Must be called before using this in child constructors. 🧠 Simple Way to Remember Prototype → shared methods proto → link to prototype Prototype chain → lookup path class → cleaner syntax constructor → object initialization extends → inheritance super → parent access ✅ Why Prototypes & Classes Matter Core JavaScript interview topic Helps understand how objects really work Used heavily in frameworks like React Improves code organization and scalability Essential for object-oriented programming Without understanding prototypes, classes feel magical. With understanding, everything makes sense 🔥 Understand object-oriented JavaScript Mastering prototypes and classes builds a strong foundation for advanced JavaScript, frameworks, and backend development. . . #JavaScript #OOP #Prototypes #Classes #WebDevelopment #FrontendDevelopment #LearningInPublic #FullStackJourney
To view or add a comment, sign in
-
-
Difference Between Spread and Rest in JavaScript I remember the first time I saw ... in JavaScript. I thought it was a typo. Three dots sitting there like they forgot to finish typing. Then someone said, “That’s either spread or rest.” Either? Same symbol, different meaning? My brain paused. Many developers hit this moment early in their JavaScript journey. The syntax looks identical, but the behaviour feels opposite. It’s one of those small concepts that seems confusing at first, until it clicks. And once it clicks, your confidence grows, you become a better tech professional, and the codes of other developers becomes easier to reason about. Spread (...) is used to expand values. It takes an array, object, or string and spreads its items out into individual elements. Common uses of spread: Function calls Math.max(...[1, 2, 3]) becomes Math.max(1, 2, 3) Copying arrays or objects (shallow copy) const newArray = [...oldArray] Merging arrays or objects const merged = { ...obj1, ...obj2 } Spread is often used to maintain immutability, especially in frameworks like React(allowing developers to update data without directly altering the original (previous) state). Rest (...) is used to collect values. It takes multiple individual values and packs them into a single array or object. Common uses of rest: Function parameters function myFunc(...args) { // args is an array of all arguments } Destructuring const [first, ...rest] = array; In simple terms: - Spread spreads things out - Rest gathers things together Spread and rest are simple tools, but they unlock powerful patterns in modern JavaScript. Understanding them is not just about syntax, it’s about thinking clearly about how data moves in your code. If this explanation helped, give it a like so more developers can see it. Repost it for someone learning JavaScript. And drop your answer in the comments - which one confused you more when you first learned it? Let’s compare experiences.
To view or add a comment, sign in
-
🚀 New article Published-Functions in JavaScript ✍ Functions are one of the most important concepts in JavaScript. They help us to write reusable,clean and structured code. In this beginner-friendly article covered: ✔️ What function are ✔️ Function syntax with simple examples ✔️ Parameters and return values ✔️ Common beginner mistakes If you are starting your JavaScript journey ,this will help you to understand . 📖 Read the full article here: 👉 https://lnkd.in/gEW_TRRz I would love to hear your feedback and suggestions 🙌 .
To view or add a comment, sign in
-
Strengthening my JavaScript fundamentals 📚 I wrote a detailed article exploring how objects really work behind the scenes — prototypes, inheritance, Object.create(), null objects, and property descriptors. Breaking down core concepts helped me understand JS much better while building projects. Sharing in case it helps others too 🙂 https://lnkd.in/gUfh5jSr #JavaScript #JS #Frontend #WebDev #Programming #SoftwareDevelopment #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
When I first learned JavaScript async code… my functions looked like this: then → then → then → then 😭 Classic Callback Hell. It was unreadable and impossible to debug. So I broke everything down and created a beginner-friendly guide on: 👉 Promises 👉 Async/Await 👉 Writing clean async code If you’re learning JS or React, this will save you hours. Read here: 🔗 https://lnkd.in/gs_yQ_Mp #JavaScript #FrontendDeveloper #Coding #LearnToCode
To view or add a comment, sign in
-
Explicit Resource Management in JavaScript JavaScript is gaining a new language feature for automatic cleanup of resources like files, streams, and database connections, reducing bugs from forgotten cleanup code. - The `using` keyword automatically cleans up resources when they go out of scope, eliminating the need for manual `try/finally` blocks - Resources opt in by implementing `Symbol.dispose` (sync) or `Symbol.asyncDispose` (async) methods - Multiple resources are cleaned up automatically in reverse order, like a stack - `DisposableStack` and `AsyncDisposableStack` provide flexibility for conditional acquisition or refactoring legacy code - Supported in Chrome 123+, Firefox 119+, and Node.js 20.9+, but Safari support is still pending - Applies to both server-side and front-end scenarios including event listeners, subscriptions, and DOM cleanup This feature makes resource lifetimes explicit in code rather than relying on conventions, reducing memory leaks and making JavaScript more suitable for systems-level programming with less boilerplate and clearer intent. https://lnkd.in/gfRFHdG2 #javascript #frontend #performance #resourcemanagement #cleanup
To view or add a comment, sign in
-
You ever reopen a JavaScript file you wrote a month ago and think: "Who wrote this... and why were they so confident?" 😅 It worked. The tests were green. The logic felt sharp. You even remember thinking, "that's clean." ✨ And now? Changing one small thing feels heavier than it should. You've probably been there. We optimize for how code feels when we write it, not how it behaves when we revisit it. 🔁 Modern JavaScript makes cleverness easy. You can compress logic, chain conditions, and abstract like a wizard. 🧙♂️ But under debugging pressure or refactoring fatigue, clarity beats compression. Every. Time. The real test isn't when you write it. It's when you have to change it. 🛠️ When the structure makes sense, you're not decoding your past self—you're just building. So, be honest: If you reopened your last project right now, would it feel obvious or just impressive? 🤔 When that question hits a little too close to home, this unpacks why simpler JavaScript wins: 👇 https://lnkd.in/d-uP-v6N
To view or add a comment, sign in
-
Day 11: Callback Functions in JavaScript JavaScript is single-threaded… so how does it handle async tasks? 🤔 The answer starts with Callbacks. 🔹 What is a Callback? A callback function is a function that is: ✅ Passed as an argument to another function ✅ Executed later 🔹 Basic Example function greet(name) { console.log("Hello " + name); } function processUser(callback) { const name = "Shiv"; callback(name); } processUser(greet); Here, greet is a callback function. 🔹 Async Example setTimeout(function() { console.log("Executed after 2 seconds"); }, 2000); 👉 The function runs after a delay 👉 JavaScript does not block execution 🔥 Why Callbacks Are Important ✔️ Foundation of async JavaScript ✔️ Used in APIs, event listeners, timers ✔️ Core concept before learning Promises ⚠️ The Problem: Callback Hell When callbacks are nested too much: api1(function() { api2(function() { api3(function() { console.log("Done"); }); }); }); This leads to: ❌ Hard-to-read code ❌ Pyramid structure ❌ Difficult debugging This problem was later solved using Promises and Async/Await. #Javascript #CallBack #webdevelopment #LearnInPublic
To view or add a comment, sign in
-
Hoisting in JavaScript can be confusing at first, but it doesn't have to be. It's often described improperly, which only adds to the confusion. In this post, I try to help shed some light on what hoisting actually is. #javascript #hoisting #coding #developer https://lnkd.in/gs2a7y3B
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