🏠 Lexical Scope in JavaScript Think of your code like a house with rooms. 🌍 The whole house = Global Scope 🏠 Each room = A Function 🚪 A room inside another room = Nested Function Now here’s the important rule: 👉 Inner rooms can see outside. 👉 But outside rooms can’t see inside. Let’s understand using the image: 🌍 Global Scope (Outside the house) let hero = "Alice"; 🏠 Outer Function (First room) let spell = "Fire"; 🚪 Inner Function (Room inside room) let mana = 50; console.log(hero); // ✅ Can access (Global) console.log(spell); // ✅ Can access (Outer) console.log(mana); // ✅ Its own variable ✔ Inner function can access: Its own variables Parent function variables Global variables But if the outer function tries this: console.log(mana); // ✖️ Error It fails. Because outer cannot access inner’s variables. 🔑 Simple Rule to Remember: A function can use variables from: 🏠 Its own room ⬆ Parent rooms 🌍 Global But it cannot look inside child rooms. #javascript #typescript #reactjs #nextjs #frontend_developer #react_developer #web_Developer #scope #laxical
JavaScript Lexical Scope Explained
More Relevant Posts
-
JavaScript Event Loop – Quick Example Understanding the Event Loop is important for writing efficient asynchronous JavaScript. Example: console.log("Start") const prom = new Promise((res) => res(true)) setTimeout(() => console.log("setTimeout"), 0) process.nextTick(() => console.log("nextTick")) queueMicrotask(() => console.log("microtask")) console.log(prom) Output order will be: Start Promise { true } nextTick microtask setTimeout Why? Because JavaScript processes tasks in this order: 1. Synchronous code 2. Microtasks (nextTick, Promises, queueMicrotask) 3. Macrotasks (setTimeout, setImmediate) Understanding this helps when debugging async issues in frontend apps. #javascript #webdevelopment #frontend #vuejs #eventloop
To view or add a comment, sign in
-
Today while building a pagination component in React, I came across the use of Array.from() in JavaScript. The problem I was facing was simple: I wanted to show page numbers between the Previous and Next buttons. For example: Prev 1 2 3 4 5 Next At first, I was thinking about how to generate those numbers dynamically instead of writing them manually. That’s when I came across Array.from(). It helped me create an array of a specific length and then generate page numbers from it. Something like this: Array.from({ length: totalPages }, (_, i) => i + 1) This creates: [1, 2, 3, 4, 5] Which can then be mapped easily to render pagination buttons in React. A small thing, but it made pagination logic feel much cleaner and more dynamic. Am I understanding this correctly? Would love to know if there’s a better or more practical way you usually handle pagination numbers. #JavaScript #ReactJS #WebDevelopment #Frontend #Pagination
To view or add a comment, sign in
-
-
Ever noticed this in JavaScript? 👀 -------- console.log("start"); setTimeout(() => console.log("timeout")); Promise.resolve().then(() => console.log("promise")); console.log("end"); -------- Most developers expect setTimeout to run first. But the output is: -------- start end promise timeout -------- Why? Because Promises go into the Microtask Queue, while setTimeout goes into the Macrotask Queue. The JavaScript event loop always processes all microtasks before the next macrotask once the call stack is empty. Execution order becomes: 1️⃣ Synchronous code 2️⃣ Microtasks (Promise, queueMicrotask) 3️⃣ Macrotasks (setTimeout, setInterval, DOM events) So even setTimeout(fn, 0) will run after Promise callbacks. Understanding this small detail helps explain many tricky async bugs in real applications. #javascript #webdevelopment #frontend #async #eventloop
To view or add a comment, sign in
-
-
⚛️ Understanding the Order of Hooks in React One important rule while working with React Hooks is that the order of hooks must remain the same on every render. React relies on the call order of hooks to correctly associate state and effects with a component. Example: function Example() { const [count, setCount] = useState(0); const [name, setName] = useState(""); useEffect(() => { console.log("Component mounted or updated"); }, []); return <div>{count}</div>; } 🔹 Hooks are executed top to bottom on every render. 🔹 Changing their order can break React’s internal state tracking. ❌ Incorrect usage: if (condition) { const [count, setCount] = useState(0); // ❌ Hooks inside condition } ✅ Correct approach: const [count, setCount] = useState(0); if (condition) { // logic here } 📌 Rules of Hooks 1️⃣ Call hooks only at the top level 2️⃣ Call hooks only inside React functions Understanding this helps avoid bugs and keeps components predictable. #React #ReactJS #FrontendDevelopment #WebDevelopment #JavaScript #Hooks
To view or add a comment, sign in
-
🚀 Frontend System Design #3: JavaScript Event Loop JavaScript is single-threaded… But still handles async code smoothly 🤯 Most developers use: setTimeout Promises APIs But don’t fully understand what’s happening behind the scenes 👀 This is where the Event Loop comes in ⚡ 💡 Once you understand this: • Debugging becomes easier • Async code makes sense • Performance issues become clearer 👉 Slide 8 is something every developer should know 🧠 Quick Quiz: Which runs first? setTimeout(() => console.log("A"), 0) Promise.resolve().then(() => console.log("B")) Comment your answer 👇 📌 Save this if you found it useful Follow for more frontend system design 🚀 #JavaScript #Frontend #WebDevelopment #SystemDesign #ReactJS #Coding
To view or add a comment, sign in
-
Built a small frontend project — a Gradient Generator 🎨 Focused on improving my understanding of DOM manipulation, event handling, and dynamic UI updates using JavaScript. ⚙️ Features: • Random gradient generation • Direction control • Live preview • One-click copy 🌐 Live Demo: https://lnkd.in/gcQSkiWS 📂 GitHub: https://lnkd.in/g8H34Ped A simple build, but a good step forward in strengthening fundamentals. #webdevelopment #frontend #javascript
To view or add a comment, sign in
-
Why does React say: "Don't call hooks conditionally"? 🤔 Let’s break it down simply. React doesn’t track hooks by name. It tracks them by order. Every render, React just walks through hooks like this: 1st hook → 2nd hook → 3rd hook That’s it. No labels. No IDs. Just position. Now imagine this 👇 if (condition) { useEffect(() => { // do something }); } 👉 First render: Hook1 → Hook2 → Hook3 👉 Next render (condition = false): Hook1 → Hook3 Now React gets confused 😵 It expects Hook2… but suddenly sees Hook3. This breaks the internal hook mapping — and boom 💥 unexpected bugs or crashes. 👉 The rule exists because hooks must run in the same order on every render. That’s why: ❌ No hooks inside conditions ❌ No hooks inside loops ❌ No hooks inside nested functions 👉 Always call hooks at the top level. Once you understand this, React hooks feel much less “magical” and more predictable. #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #LearnInPublic
To view or add a comment, sign in
-
💡 Built a mini Todo List in JavaScript! • Add tasks ✅ • Mark them as completed ✔️ • Delete tasks ❌ • Interactive and animated ✨ A fun way to practice DOM manipulation, events, and JS arrays. Perfect for sharpening frontend skills! 🚀 #JavaScript #Frontend #WebDevelopment #Coding #LearnToCode #MiniProject #DOM #Interactive
To view or add a comment, sign in
-
Today something interesting happened while I was building a Custom Date Picker in NextJS.🗓 I have used useRef many times before, but honestly I was mostly using it without fully understanding the concept behind it But today… it finally clicked.💫 While implementing the feature, I realized that: • useRef creates a mutable object • The value is stored inside .current • The value persists between renders • Updating .current does not trigger a re-render • It can also be used to directly access DOM elements The most interesting part for me was understanding why React doesn't re-render when current changes. Sometimes you don’t truly understand a concept until you build something real with it. Small learning today, but a very satisfying one. 💫 What was the React concept that took you the longest to understand❓️ #React #JavaScript #FrontendDevelopment #ReactHooks #BuildInPublic #LearningJourney
To view or add a comment, sign in
-
💡React Tip💡 Whenever you want to store an object in a state, use null as the initial value like this: const [user, setUser] = useState(null); instead of an empty object like this: const [user, setUser] = useState({ }); So if you want to check if user exist or if there are any properties present inside it, you can just use simple if condition like this: if(user) { // user exists, do something } or use JSX expression like this: { user && <p>User found</p>} However, If you use an empty object as the initial value, then you need to check like this: if(Object.keys(user).length === 0) { // user exists, do something } or use JSX expression like this: { Object.keys(user).length === 0 && <p>User found</p>} So assigning an initial value of null will make your code simpler and easier to understand. 𝗙𝗼𝗿 𝗺𝗼𝗿𝗲 𝘀𝘂𝗰𝗵 𝘂𝘀𝗲𝗳𝘂𝗹 𝗰𝗼𝗻𝘁𝗲𝗻𝘁, 𝗱𝗼𝗻'𝘁 𝗳𝗼𝗿𝗴𝗲𝘁 𝘁𝗼 𝗳𝗼𝗹𝗹𝗼𝘄 𝗺𝗲. #javascript #reactjs #nextjs #webdevelopment
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