What is Scope Chain in JavaScript? Understanding how JavaScript looks for variables helps everything make more sense. 🔹 Knowing why inner functions can access outer variables 🔹 Debugging undefined issues with confidence 🔹 Writing clean, predictable and bug-free JS code ❌ The code below can be confusing without understanding the Scope chain let x = 50; function outerFunction() { function innerFunction() { console.log(x); // Where does x come from? } innerFunction(); } outerFunction(); // output 50 ✅ The code below works because of the Scope Chain let x = 10; function outerFunction() { let y = 20; function innerFunction() { console.log(x, y); } innerFunction(); } outerFunction(); // output 10 20 Scope chain follow some steps that are listed below. 1️⃣ First, it looks in the current scope 2️⃣ Then, it checks the outer (parent) scope 3️⃣ This continues up to the global scope 4️⃣ If the variable is not found, JavaScript throws a ReferenceError ✅ Key takeaway: Inner functions can access variables from their outer scopes because of the scope chain. #JavaScript #ScopeChain #JSConcepts #WebDevelopment #FrontendDevelopment #LearnJavaScript #SoftwareDevelopment #DeveloperTips
Understanding JavaScript Scope Chain: Accessing Variables in Nested Functions
More Relevant Posts
-
Today I learned about Functions in JavaScript! A Function is a reusable block of code designed to perform a specific task. It executes when it is "invoked" or called, helping developers follow the DRY (Don't Repeat Yourself) principle. There are four key types of functions in JavaScript: 1. Function Declaration These are hoisted, meaning they can be called before they are defined in the code. ex. console.log(greet("Vaseem")); function greet(name) { return `Hello, ${name}!`; } 2. Function Expression: A function assigned to a variable. Unlike declarations, these are not hoisted. ex. const add = function(a, b) { return a + b; }; 3. Arrow Functions (ES6+) A concise syntax introduced in modern JavaScript. They do not have their own this binding, making them ideal for callbacks. ex. const multiply = (x, y) => x * y; 4. Immediately Invoked Function Expression (IIFE) A function that runs as soon as it is defined. It is commonly used to create a private scope. ex. (function() { console.log("Programming started.."); })(); #JavaScript #WebDevelopment #Programming #CodingTips #SoftwareEngineering #Frontend #JSFunctions #TechLearning
To view or add a comment, sign in
-
JavaScript Scope Chain — Explained Simply (No Fluff) If you’ve ever wondered “Where the hell did this variable come from?”, this is for you. Understanding the scope chain explains: Why inner functions can access outer variables Why undefined or ReferenceError happens How JavaScript actually resolves variables ❌ Confusing without scope chain let x = 50; function outerFunction() { function innerFunction() { console.log(x); // Where does x come from? } innerFunction(); } outerFunction(); // 50 ✅ Clear when you know the rule let x = 10; function outerFunction() { let y = 20; function innerFunction() { console.log(x, y); } innerFunction(); } outerFunction(); // 10 20 🔍 How JavaScript finds variables 1️⃣ Look in the current scope 2️⃣ Move to the parent scope 3️⃣ Continue up to the global scope 4️⃣ Not found? → ReferenceError Key takeaway: Inner functions don’t magically get variables — JavaScript walks up the scope chain until it finds them. If you don’t understand scope, you’ll write unpredictable JS. If you do, debugging becomes boring — and that’s a good thing. #JavaScript #WebDevelopment #Frontend #ReactJS #Programming #ScopeChain #CleanCode
To view or add a comment, sign in
-
Treat your functions like VIPs. That's the secret to JavaScript's power. 🎩✨ In many older languages, functions are just specific blocks of code. In JavaScript, they are 𝐅𝐢𝐫𝐬𝐭-𝐂𝐥𝐚𝐬𝐬 𝐂𝐢𝐭𝐢𝐳𝐞𝐧𝐬. But what does that actually mean? And how is it different from a 𝐇𝐢𝐠𝐡𝐞𝐫-𝐎𝐫𝐝𝐞𝐫 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧? Here is the breakdown: 🥇 𝐅𝐢𝐫𝐬𝐭-𝐂𝐥𝐚𝐬𝐬 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 (𝐓𝐡𝐞 𝐂𝐚𝐩𝐚𝐛𝐢𝐥𝐢𝐭𝐲) This refers to the 𝑙𝑎𝑛𝑔𝑢𝑎𝑔𝑒 𝑓𝑒𝑎𝑡𝑢𝑟𝑒 itself. It means JavaScript treats functions just like any other variable (like a number or string). • ✅ You can assign them to variables. • ✅ You can pass them as arguments to other functions. • ✅ You can return them from other functions. 🚀 𝐇𝐢𝐠𝐡𝐞𝐫-𝐎𝐫𝐝𝐞𝐫 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧𝐬 (𝐓𝐡𝐞 𝐈𝐦𝐩𝐥𝐞𝐦𝐞𝐧𝐭𝐚𝐭𝐢𝐨𝐧) This is a function that 𝑢𝑡𝑖𝑙𝑖𝑧𝑒𝑠 that First-Class capability. If a function accepts another function as a parameter (like a callback) or returns a function (like a factory), it is a 𝐇𝐢𝐠𝐡𝐞𝐫-𝐎𝐫𝐝𝐞𝐫 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧. 𝐑𝐞𝐚𝐥-𝐖𝐨𝐫𝐥𝐝 𝐄𝐱𝐚𝐦𝐩𝐥𝐞: The `multiplier` function in the infographic is a classic example of a Higher-Order function returning a First-Class function. This pattern is the basis of 𝐂𝐥𝐨𝐬𝐮𝐫𝐞𝐬 and 𝐂𝐮𝐫𝐫𝐲𝐢𝐧𝐠! Check out the visual guide below to master these patterns. 👇 What is your favorite Higher-Order function? (I'm a big fan of `.reduce()`) #JavaScript #FunctionalProgramming #WebDevelopment #CodingPatterns #SoftwareEngineering #Frontend
To view or add a comment, sign in
-
-
🧵 How JavaScript Does 10 Things at Once (While Being Single-Threaded) 🔄 Ever wondered how JavaScript handles API calls, timers, or async tasks without freezing the browser UI? The secret is the Event Loop. Even though JavaScript is single-threaded (it can do only one thing at a time), the Event Loop allows it to be asynchronous and non-blocking. Here’s a simple 4-step breakdown of how it works 👇 1️⃣ Call Stack This is the “Now” zone. JavaScript executes synchronous code here. If a function is in the stack, the engine is busy. 2️⃣ Web APIs / Node APIs When you use `setTimeout`, `fetch`, or DOM events, JavaScript hands them off to the browser/Node environment. This keeps the call stack free so the UI doesn’t freeze. 3️⃣ Callback Queue & Microtask Queue Once async tasks complete, their callbacks wait here. 👉 Promises (Microtasks) always run before timers (`setTimeout`). 4️⃣ Event Loop This is the coordinator. It constantly checks: • Is the Call Stack empty? • If yes → move the next task from the queue to the stack. 🔑 Golden Rule: Avoid blocking the Event Loop with heavy synchronous code — otherwise users will experience laggy interfaces. Learning this really helped me understand async JavaScript better 🚀 #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering #EventLoop #Programming #javascript
To view or add a comment, sign in
-
-
Day 3: JavaScript Hoisting — Magic or Logic? Yesterday, we learned that JavaScript creates memory for variables before it executes the code. Today, let’s see the most famous (and sometimes confusing) result of that: Hoisting. What is Hoisting? Hoisting is a behavior where you can access variables and functions even before they are initialized in your code without getting an error. Wait... why didn't it crash? 🤔 If you try this in other languages, it might throw an error. But in JS: During Memory Phase: JS saw var x and gave it the value undefined. It saw the function getName and stored its entire code. During Execution Phase: When it hits console.log(x), it looks at memory and finds undefined. When it hits getName(), it finds the function and runs it! ⚠️ The "Let & Const" Trap Does hoisting work for let and const? Yes, but with a catch! They are hoisted, but they are kept in a "Temporal Dead Zone". If you try to access them before the line where they are defined, JS will throw a ReferenceError. Pro Tip: Always define your variables at the top of your scope to avoid "Hoisting bugs," even though JS "magically" handles them for you. Crucial Takeaway: Hoisting isn't code physically moving to the top; it’s just the JS Engine reading your "ingredients" before "cooking" (Phase 1 vs Phase 2). Did you know about the Temporal Dead Zone? Let me know in the comments! #JavaScript #WebDev #100DaysOfCode #Hoisting #CodingTips #FrontendDeveloper
To view or add a comment, sign in
-
-
So, you wanna get a grip on JavaScript. It's all about functions and objects, really. They're the building blocks. A function is like a recipe - it's a set of instructions that does something, and you can use it over and over. You can make functions in a few different ways: - the classic function declaration, - function expressions, which are kinda like assigning a function to a variable, - and then there's the arrow function, which is like a shorthand way of doing things. For example, you can use functions like this: console.log(greet("Ajmal")); - it's like calling a friend to say hello. Or, you can create a function that adds two numbers together, like this: const add = function (a, b) { return a + b; }; - it's basic, but it works. And then there's the arrow function, which is super concise, like this: const multiply = (a, b) => a * b; - it's like a quick math trick. Objects, on the other hand, are like containers - they store data in key-value pairs, so you can keep things organized. It's like having a toolbox, where you can store all your functions and data in one place. You can use objects to make your code more manageable, and that's a beautiful thing. Check out this article for more info: https://lnkd.in/gTMkkSGP #JavaScript #Functions #Objects
To view or add a comment, sign in
-
📌 JavaScript concat() Method – Explained Simply The concat() method in JavaScript is used to merge two or more arrays or strings and return a new combined result — without modifying the original data. 👉 Key Characteristics 🔹 Does not mutate the original array or string 🔹 Returns a new array or string 🔹 Preserves the order of elements 🔹 Can accept multiple arguments 👉 Why use concat()? 🔹 Ideal when you want to combine data safely 🔹 Helps maintain immutability, which is important in React and modern JavaScript 🔹 Makes code cleaner and more readable For arrays, concat() is often preferred over push() when you don’t want to change the original array. 🔁 Immutability leads to predictable and bug-free code. #JavaScript #WebDevelopment #Frontend #JSMethods #CleanCode #Learning
To view or add a comment, sign in
-
-
The event loop sounds complex, but the idea behind it is simple. JavaScript runs code on a single thread. It does one thing at a time. When something takes time (like a timer, I/O, or a network call), JavaScript doesn’t wait. Instead: • the task is started • JavaScript continues executing other code • the result is handled later The event loop’s job is just this: • check if the main stack is free • take the next ready task • execute it Callbacks, promises, and async code don’t run in parallel. They run when the event loop gets a chance to pick them up. Understanding this made it clearer why: • long synchronous code blocks everything • async code still needs careful ordering • “non-blocking” doesn’t mean “instant” Once this clicks, a lot of JavaScript behavior stops feeling random. #JavaScript #BackendDevelopment #WebFundamentals #SoftwareEngineering #NodeJS
To view or add a comment, sign in
-
-
𝗵𝗼𝘄 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗵𝗮𝗻𝗱𝗹𝗲𝘀 𝗮𝘀𝘆𝗻𝗰 𝗰𝗼𝗱𝗲? It's single-threaded. So how does it handle setTimeout, API calls, and user clicks without freezing? 𝗧𝗵𝗲 𝗮𝗻𝘀𝘄𝗲𝗿: Event Loop Here's what actually happens: JavaScript has 4 main parts: ↳ Call Stack — runs your code ↳ Web APIs — handles async tasks (setTimeout, fetch, DOM events) ↳ Callback Queue — stores completed callbacks ↳ Event Loop — moves callbacks to stack when stack is empty Example: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); console.log("End"); Output: Start End Timeout Wait, why does Timeout come last? ↳ console.log("Start") → runs immediately ↳ setTimeout → sent to Web API ↳ console.log("End") → runs immediately ↳ Stack empty → Event Loop pushes callback ↳ console.log("Timeout") → runs now Even with 0ms delay, setTimeout waits for stack to clear. My takeaway: JavaScript isn't slow. It's just smarter than I thought. Understanding Event Loop = understanding async JavaScript. #JavaScript #FrontendDevelopment #LearningInPublic #SDE
To view or add a comment, sign in
-
So you're trying to verify types in TypeScript - it's a thing. But here's the deal, JavaScript doesn't really care about types at runtime. TypeScript types are basically erased after compilation, leaving you with just JavaScript values. You can do runtime checks, though - like checking if something's a string with `typeof x === "string"`, or if it's a Date object with `x instanceof Date`. Or, you know, checking if an object has a certain property with `"swim" in animal`. And then there's the `animal.kind === "fish"` check - that's a good one too. TypeScript uses these checks to narrow down union types, which is pretty cool. For example, you can use `typeof` narrowing in a function like `padLeft` - it takes a padding value that can be either a number or a string, and an input string. Or, you can use `instanceof` narrowing in a function like `logValue` - it takes a value that can be either a Date object or a string. And then there's the `"in"` narrowing - that's useful when you have a type like `Fish` that has a `swim` method. You can also reuse a check across multiple places using type predicates - like the `isFish` function that checks if an animal is a fish. It's like, you can use it to filter an array of animals and get only the fish. If you can change the data shape, using a `kind` property is a good idea - like, you can have a `Fish` type with a `kind` property that's set to `"fish"`. It's just easier that way. So, to sum it up: use JavaScript checks to narrow types, and type predicates to reuse the narrowing - that's the way to do it. Check out this article for more info: https://lnkd.in/gFKxe3ZE #TypeScript #TypeVerification #JavaScript
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