💡 Cracking the Code: JavaScript's Lexical Scope & Scope Chain Ever wonder exactly how an inner function knows where to find a variable defined outside of it? Master Lexical Scope and the Scope Chain to unlock the true power of JavaScript, especially Closures! 1️⃣ Lexical Scope (The "Where You Live" Rule) Lexical scope (or Static Scope) is perhaps the most fundamental concept: Definition: Variable access is determined by where the code is physically written, not where the function is executed or called from. The Key: The surrounding code is "frozen" at definition time. Example: If function inner() is written inside function outer(), inner will always look to outer for variables, regardless of where inner() is later invoked. 2️⃣ The Scope Chain (The Lookup Path) The Scope Chain is the variable resolution mechanism that JavaScript uses at runtime: It defines the specific path the engine takes to find the value of a variable. The Lookup Order: The search always starts locally and moves outward: Current Scope ---> Parent Scope ---> Global Scope In Action: If you have level3 nested inside level2, which is nested inside level1, the function level3 can access variables defined in level1 by traversing this chain. 3️⃣ The Closure Connection 🔗 This is where the magic happens! Formula: Lexical Scope + Scope Chain = Closures Because of lexical scope, an inner function maintains a "memory" of its parent's variables even after the parent function has finished executing. This ability to "remember" is a closure!
Understanding JavaScript's Lexical Scope and Scope Chain
More Relevant Posts
-
🚀 Day 2: Dive Deep — JavaScript Hoisting Before your code runs, JavaScript secretly does a quick setup behind the scenes — this process is called Hoisting. In this phase, JavaScript scans your code and creates memory space for all variables and functions even before execution starts. ✨ What happens: Function declarations are fully stored in memory — you can call them even before they appear in the code. Variables (declared using var) are also lifted to the top, but only their names are stored — their values are set as undefined until the actual assignment happens. So when you see undefined before a variable is initialized, it’s not an error — it’s JavaScript saying, “Hey, I know this variable exists, but I haven’t given it a value yet!” Hoisting shows how JavaScript prepares your code in advance — setting the stage before the show begins. 🔥 Key takeaway: JavaScript doesn’t run line by line right away — it first creates memory for everything, marks variables as undefined, and then executes step by step. Understanding this tiny detail helps you debug smarter and truly see what’s happening behind the scenes.
To view or add a comment, sign in
-
-
Day 73 of #100DaysOfCode Today I dove into Object-Oriented JavaScript specifically Classes and the this keyword. In JavaScript, a class is like a blueprint for creating multiple objects with shared structure and behavior. It can include: A constructor() → initializes properties Methods → define actions for class instances Example: class Dog { constructor(name) { this.name = name; } bark() { console.log(`${this.name} says woof!`); } } const dog = new Dog("Gino"); dog.bark(); // Gino says woof! Here, this refers to the current object instance. In methods, it gives access to that object’s properties and behaviors. Key takeaways 🧠 Classes make code reusable and modular. this ensures context, it points to who is calling the method. Arrow functions don’t create their own this; they inherit from their scope. Mastering these two concepts is a huge step toward writing cleaner, scalable JavaScript.
To view or add a comment, sign in
-
💡 Why Almost Everything in JavaScript is an “Object” If you’ve ever heard “everything in JavaScript is an object”, you’re not alone — and you’re almost right. 😄 Here’s the real story 👇 JavaScript is a prototype-based language, where most things — from arrays to functions — are built on top of objects. This makes JavaScript incredibly flexible and dynamic. ✅ Numbers, strings, and booleans Even these primitives temporarily behave like objects when you access methods: "hello".toUpperCase(); // works because JS wraps it in a String object ✅ Functions and Arrays They’re technically objects too — with callable or iterable behavior added on top. That’s why you can do things like: myFunc.customProp = 42; ✅ Everything inherits from Object.prototype It’s the ultimate ancestor — where common methods like toString() and hasOwnProperty() live. 🧠 Key Takeaway JavaScript’s design treats almost everything as an object so it can: Extend behavior dynamically Support inheritance via prototypes Provide consistency across data types But remember: Primitives (null, undefined, number, string, boolean, symbol, bigint) are not true objects — they just act like them when needed. 🚀 TL;DR In JavaScript, objects are the foundation. Almost everything is built on top of them — it’s what gives JS its power, flexibility, and sometimes… confusion. 😅 #JavaScript #WebDevelopment #Frontend #React #Coding #Learning
To view or add a comment, sign in
-
Think you know JavaScript hoisting? The usual line: “variables and functions are moved to the top,” misses the deeper reason why. To truly understand hoisting, you need to look at how JavaScript executes code. Every execution context runs in two phases: 1. Memory Creation Phase: Before any code runs, JavaScript enters the memory creation phase. It scans through your file and allocates memory for all variables and function declarations. Variables are assigned undefined, while function declarations are fully copied into memory. That’s why you can access variables (though they’ll be undefined) and call functions before they’re declared. 2. Code execution phase: Only after memory allocation does JavaScript start running your code line by line. Hoisting isn’t about JavaScript moving code around; it’s the result of its two-phase execution model. Understanding this provides a much deeper insight into how JavaScript works under the hood. If you want to explore this further, I highly recommend Akshay Saini’s “Namaste JavaScript” series: https://lnkd.in/d8qZ_PSV — It explains these concepts clearly and practically.
To view or add a comment, sign in
-
🚀 Thenable-like Objects in JavaScript Did you know — a value doesn’t have to be a Promise to behave like one? 😮 If an object has a .then() method, JavaScript treats it as a Thenable. That means it can be awaited or chained just like a real Promise! const thenable = { then(resolve, reject) { setTimeout(() => resolve("✅ Resolved from Thenable!"), 1000); } }; Promise.resolve(thenable).then(console.log); // Output after 1s: ✅ Resolved from Thenable! Here’s what’s happening: Promise.resolve() checks if the value is thenable. If yes, it calls its .then() method. The result is adopted into a real Promise chain. ✨ Use Case: Thenables are handy when integrating with custom async systems or libraries that don’t return real Promises but follow similar behavior. 🧠 Key takeaway: > Any object with a .then() method is treated as a Promise by JavaScript — even if it’s not created using the Promise constructor!
To view or add a comment, sign in
-
I was reading a book called Eloquent JavaScript, and the author brought up the dilemma of speed vs. elegance. Let me give a simple example to explain what I mean: imagine a function that calculates the factorial of a number N. If we write it recursively, it’s short and elegant, but in JavaScript, recursion costs about 3x more than a regular loop. Of course, a factorial implemented with a for loop would still be short and easy to read. So here’s the question: is the trade-off between elegance and efficiency actually relevant, or is it trivial? In general, we aim to write code that works and is easy to understand. Focusing too much on elegance or efficiency can be paralyzing. Think about it — if we only focus on elegance, we’ll eventually need to iterate over complex data structures and deal with nested loops, where recursion becomes impractical. But if we only focus on efficiency, our code can quickly become long and verbose. In the end, leaning too far to either side is never a good thing.
To view or add a comment, sign in
-
How JavaScript Magically Knows What an Object Is Worth Ever wondered how JavaScript knows what to do when you compare or add objects, like {} + {} without throwing an error? That’s where valueOf() quietly steps in. 🔍 What It Actually Does When JavaScript needs to convert an object to a primitive (like during comparison, math operations, or string concatenation), it follows this internal process: - Calls the object’s valueOf() method first. - If that doesn’t return a primitive value, it tries toString() next. - If both fail, you get a TypeError. This entire process is handled by the ToPrimitive abstract operation defined in the ECMAScript spec, it decides how and when conversions happen. 🧠 Under the Hood Every JS object inherits a default valueOf() from Object.prototype. By default, it just returns the object itself (this). But you can override it to define custom behavior. const score = { value: 100, valueOf() { return this.value; // return primitive number }, }; console.log(score + 20); // 120 When + is used, JavaScript tries to coerce the object, it finds your valueOf() and uses its result.
To view or add a comment, sign in
-
How JavaScript Really Works: The Truth About Hoisting Most developers have heard of “hoisting” — the idea that variables and functions magically float to the top of their scope. Sounds simple. But dive into the ECMAScript specification, and you’ll find something surprising: there is no such thing as hoisting in the spec. Instead, JavaScript follows a well-defined three-phase execution model — and only certain declarations are truly “hoisted.” 🧠 The Three Phases of JavaScript Execution Static Semantics This phase analyzes code structure for validity. It runs only once before anything executes. EvaluateBody (Preparation phase) The engine sets up variables and function bindings based on declarations. This is where hoistable declarations come into play. Evaluation (Runtime execution) The actual running of code — now that everything is initialized. 🚫 Is “Hoisting” a Myth? The spec defines HoistableDeclaration, but it applies only to: function declarations, async function, generator function, async generator function. However, let, const, and class are not hoisted. Worse — they enter the temporal dead zone (TDZ), where accessing them before initialization throws a ReferenceError. 📌 Example (() => { "use strict"; console.log(hoistedFunc()); // OK // console.log(notHoisted); // ReferenceError function hoistedFunc() { return 'I am hoisted!'; } let notHoisted = 'I am NOT hoisted'; })(); 💡 Takeaway Hoisting isn’t magic. It’s the outcome of the EvaluateBody phase, where only certain declarations are pre-initialized. Understanding this deeper model helps avoid bugs — especially in strict mode.
To view or add a comment, sign in
-
-
Hoisting in JavaScript Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This means that you can use variables and functions before they are declared in the code. When JavaScript code runs, it’s not executed line by line immediately. The engine scans the code before running it. It creates something called a variable environment for each scope. During this creation phase, it: Registers all variable and function declarations Sets up memory bindings for them inside that scope Execution phase — actually runs the code line by line Hoisting happens during the creation phase, before any code executes. // Creation Phase (before execution) Memory Environment: a → undefined // var declaration found // Execution Phase console.log(a); // reads 'undefined' a = 10; // assigns new value TDZ is the period between the start of a scope and the point where a let or const varia https://lnkd.in/gc3k5ZaJ
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