🧠Mastering JavaScript — One Concept at a Time (2/32) Today I am very happy because my understanding of hoisting, scope, and sharing with you is now complete. 🔥Scope in Real Life Scope simply means: Where can I access this variable? Block Scope → Code inside {} like in loops, if , etc. Function Scope → Code inside a function let and const follow block scope. var ignores block scope — which leads to bugs. 🧨Hoisting JavaScript prepares memory before running code. It moves all declarations to the top — this is called hoisting. But: var is hoisted and set to undefined let and const are hoisted but not initialised — so accessing them early gives ReferenceError ⚠Common Confusions (JS Reality Checks) const doesn't make things fully constant. It protects the variable, not the value. var is outdated — it's better to use let and const let and const behave similarly, but const gives more safety use it when you're not planning to reassign. 🧠 Mindset Rule Use const by default. Use let only when you plan to change the value. Avoid var — it belongs to the past. Revisiting these fundamentals makes JavaScript feel less “magical” and more predictable. In the next post, I’ll go deeper into how the Data Type and Type System. How long did it take you to understand scope and hoisting truly? #JavaScript #LearningInPublic #WebDevelopment #FrontendDevelopment #MasteringJavaScript
Mastering JavaScript Fundamentals: Scope, Hoisting and Variables
More Relevant Posts
-
🚀 JavaScript Hoisting Explained Clearly Most developers hear about hoisting… But very few truly understand what actually happens behind the scenes. Let’s break it down. When JavaScript runs your code, it does NOT execute it line by line immediately. First, it creates something called the Execution Context. There are two main phases: 1️⃣ Creation Phase (Hoisting Phase) 2️⃣ Execution Phase 🔵 Creation Phase (Hoisting Phase) During this phase: • Memory is allocated for variables and functions • Function declarations are stored completely in memory • var variables are initialized with undefined • let and const are hoisted but remain in the Temporal Dead Zone (TDZ) Example that works: greet(); function greet() { console.log("Hello"); } Example that throws an error: sayHi(); const sayHi = function () { console.log("Hi"); }; Reason: Only the variable is hoisted, not the function expression. 🔴 Execution Phase Now JavaScript executes the code line by line. • Variables receive their actual values • Functions run when called Important Insight Hoisting does NOT mean JavaScript moves your code to the top. It means JavaScript allocates memory before execution begins. If you understand hoisting deeply, you automatically understand: • Execution Stack • Scope Chain • Closures • TDZ • var vs let vs const Master this concept once, and JavaScript starts making real sense. #JavaScript #WebDevelopment #Frontend #ExecutionContext #Hoisting #LearnToCode #Programming #Developers
To view or add a comment, sign in
-
-
🚀 Day 75 — Visualizing the JavaScript Call Stack Today I learned how JavaScript actually executes code behind the scenes using something called the Call Stack. Understanding this completely changed how I think about function execution. 🧠 What is the Call Stack? The Call Stack is a mechanism used by JavaScript to keep track of function execution. 👉 JavaScript is single-threaded, meaning it executes one task at a time. So whenever a function runs, it is added to the stack. 🔹 How It Works Think of it like a stack of plates: ✅ New function → placed on top ✅ Function finished → removed from top This follows the rule: LIFO (Last In, First Out) 🔍 Example function third() { console.log("Third function"); } function second() { third(); console.log("Second function"); } function first() { second(); console.log("First function"); } first(); ⚙ Execution Flow (Step by Step) 1️⃣ first() added to Call Stack 2️⃣ second() added 3️⃣ third() added 4️⃣ third() executes → removed 5️⃣ second() executes → removed 6️⃣ first() executes → removed Finally → Stack becomes empty ✅ 📌 Why Call Stack Matters Understanding Call Stack helps explain: ✅ Function execution order ✅ Debugging errors ✅ Stack Overflow errors ✅ Infinite recursion problems ✅ Async behavior understanding ⚠ Example of Stack Overflow function repeat() { repeat(); } repeat(); Since the function never stops, the stack keeps growing until: ❌ Maximum Call Stack Size Exceeded 💡 Key Learning JavaScript doesn’t randomly run code. Every function waits its turn inside the Call Stack, making execution predictable and structured. Understanding this made debugging much easier for me. #Day75 #JavaScript #CallStack #WebDevelopment #LearningInPublic #DeveloperJourney
To view or add a comment, sign in
-
-
🚀 JavaScript Magic: Why "Undefined" is actually a Feature, not a Bug! I just had a "Wow" moment diving into the JavaScript Execution Context, and it changed how I look at my code. Ever wondered why you can console.log a variable before you even declare it, and JavaScript doesn't lose its mind? 🤯 🧠 The Secret: Two-Phase Execution When your code runs, JavaScript doesn't just start at line 1. It takes two passes: 1.Memory Creation Phase: JS scans your code and allocates space for all variables and functions. 2. Execution Phase: It runs the code line-by-line. ⚡ The var Behavior (Hoisting) If you use var, JavaScript initializes it as undefined during the memory phase. Result: You can log it early. No error, just a quiet undefined. It’s like the variable is there, but its "suit" hasn't arrived yet. 🛑 The let & const Twist (TDZ) Try the same thing with let or const, and the engine throws a ReferenceError. Why? The Temporal Dead Zone (TDZ). While let and const are also "hoisted," they aren't initialized. They stay in a "dead zone" from the start of the block until the moment the code actually hits the declaration. The Lesson: JavaScript isn't just reading your code; it's preparing for it. Understanding the Execution Context makes debugging feel like having X-ray vision. 🦸♂️ Have you ever been bitten by the Temporal Dead Zone, or do you still find yourself reaching for var out of habit? Let’s discuss! 👇 #JavaScript #WebDevelopment #CodingTips #Frontend #Programming101
To view or add a comment, sign in
-
🚀 Understanding Variables & Functions in JavaScript (Behind the Scenes) When we declare a variable or write a function in JavaScript, a lot happens internally before execution. • Memory Creation Phase Before running the code, JavaScript allocates memory: Variables are stored in memory. If declared with var, they are initialized as undefined. Functions are fully stored in memory (hoisted completely). • Execution Phase Now the code runs line by line. Values replace undefined, and functions execute when called. • Stack & Heap Stack Memory → Stores primitive values and function execution context. Heap Memory → Stores objects, arrays, and reference types. • Main Thread JavaScript is single-threaded. All variables, functions, and execution contexts go through the Call Stack (main thread). • Why Memory Address Matters? For reference types, the variable doesn’t store the actual value — it stores the address pointing to heap memory. That’s why copying objects behaves differently from copying primitives. Understanding this helps in: ✔ Avoiding bugs ✔ Writing optimized code ✔ Understanding hoisting ✔ Managing memory better JavaScript may look simple, but internally it follows a well-structured execution model. #JavaScript #WebDevelopment #MemoryManagement #DSA #Frontend Vikas Kumar Pratyush Mishra
To view or add a comment, sign in
-
-
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
-
If 𝐡𝐨𝐢𝐬𝐭𝐢𝐧𝐠 still feels like “JavaScript moves code to the top,” your fundamentals need reinforcement. JavaScript never rearranges your code. What actually happens is simpler—and more powerful. Before execution, the engine creates memory. That’s where `var`, `let`, `const`, and function declarations are registered. Understanding this changes everything. During the **memory creation phase**: * `var` is hoisted and initialized with `undefined` * `let` and `const` are hoisted but placed in the **Temporal Dead Zone (TDZ)** * Function declarations are fully stored in memory Then comes the **execution phase**, where code runs line by line and values are assigned. That’s why this works: `console.log(a)` → `undefined` `var a = 10;` But this throws an error: `console.log(b)` → ReferenceError `let b = 10;` 𝐒𝐚𝐦𝐞 𝐡𝐨𝐢𝐬𝐭𝐢𝐧𝐠. 𝐃𝐢𝐟𝐟𝐞𝐫𝐞𝐧𝐭 𝐢𝐧𝐢𝐭𝐢𝐚𝐥𝐢𝐳𝐚𝐭𝐢𝐨𝐧 𝐫𝐮𝐥𝐞𝐬. In production, shallow understanding leads to undefined values, unpredictable refactors, and “JavaScript is weird” complaints. It’s not weird. It’s precise. Practical reminders: * Avoid `var` in modern codebases * Declare variables at the top of their scope intentionally * Understand TDZ before debugging scope-related errors Strong engineers don’t memorize slogans—they understand execution context. Can you clearly explain why `let` behaves differently from `var` without saying “it’s not hoisted”? #JavaScript #WebDevelopment #FrontendEngineering #CleanCode #ExecutionContext #SoftwareEngineering #ProgrammingFundamentals
To view or add a comment, sign in
-
-
🚀 Understanding the JavaScript Event Loop (Microtasks vs Macrotasks) Consider this code: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); What’s the output? Many expect: Start Timeout Promise End But actual output is: Start End Promise Timeout Why? Because of the Event Loop. JavaScript handles tasks in two major queues: • Microtasks (Promises, queueMicrotask) • Macrotasks (setTimeout, setInterval) Execution order: 1️⃣ Synchronous code runs first 2️⃣ Microtasks run next 3️⃣ Then Macrotasks Even if setTimeout has 0ms delay, it still waits for the macrotask queue. Understanding this explains: • Why some async bugs feel “random” • Why Promises run before setTimeout • Why UI updates sometimes behave unexpectedly JavaScript isn’t single-threaded chaos. It’s single-threaded with a well-defined event model. Understanding the Event Loop changes how you debug async code. What async behavior confused you the most before learning this? #javascript #frontenddeveloper #webdevelopment #eventloop #softwareengineering
To view or add a comment, sign in
-
-
Today I practiced an important JavaScript concept: Flattening a nested array manually using loops. Instead of using the built-in .flat() method, I implemented the logic myself to deeply understand how flattening actually works. 🧠 Problem Given this array: [1, [2, 3], [4, 5], 6] Return: [1, 2, 3, 4, 5, 6] 🔍 My Approach Created an empty result array. Looped through each element of the main array. Checked if the current element is an array using Array.isArray(). If it’s an array: Loop through it Push each inner element individually into result If it’s not an array: Push it directly into result 💡 Key Line That Does the Magic result.push(arr[i][j]); This line: Accesses elements inside the nested array Pushes them individually into the final result Removes one level of nesting 🎯 What I Learned How nested loops work in real problems The difference between pushing an array vs pushing its elements What “one-level flattening” actually means How .flat() works internally ⏱ Time Complexity O(n) — every element is visited once. Building fundamentals > memorizing shortcuts. Next step: Flatten deeply nested arrays using recursion 🔥 #JavaScript #FrontendDeveloper #ProblemSolving #WebDevelopment #100DaysOfCode #DSA #LearningInPublic
To view or add a comment, sign in
-
Most developers reach for IDs, classes, or extra state before remembering this: JavaScript already gives you a clean way to attach structured metadata directly to DOM elements. If you have ever used data-* attributes in HTML, you can access them in JavaScript through the dataset property. No parsing. No brittle string manipulation. No unnecessary DOM lookups. It is simple, readable, and surprisingly underused. This pattern is especially useful for event delegation, lightweight UI state, dynamic lists, and keeping behaviour close to the element it belongs to. Small details like this make frontend systems cleaner and easier to reason about without introducing extra abstractions. Not everything needs global state. Sometimes the platform already solved the problem. In the example attached, notice how `data-user-id` becomes `dataset.userId`. Hyphenated attributes automatically convert to camelCase. It is a small feature, but small features compound into cleaner, more maintainable frontend code. What is one underrated JavaScript feature you think more developers should use? Github Gist: https://lnkd.in/d6pjMP7J #webdevelopment #javascript #cleancode
To view or add a comment, sign in
-
-
💡 Understanding the JavaScript Event Loop (Made Simple) When I started learning JavaScript, I was confused about how setTimeout, button clicks, and API calls worked — especially since JavaScript is single-threaded. This visual really helped me understand what happens behind the scenes: 👉 1. Call Stack – Runs code line by line (synchronous code) 👉 2. Web APIs – Handles async tasks like timers and fetch requests 👉 3. Callback Queue – Stores completed async callbacks 👉 4. Event Loop – Moves callbacks to the stack when it’s empty 🔎 Simple Example: console.log("Start"); setTimeout(() => { console.log("Inside Timeout"); }, 0); console.log("End"); 👉 What do you think the output will be? The output is: Start End Inside Timeout Even though the timeout is set to 0 milliseconds, it doesn’t run immediately. Here’s why: 1️⃣ "Start" goes to the call stack → executes 2️⃣ setTimeout moves to Web APIs 3️⃣ "End" executes 4️⃣ The callback moves to the queue 5️⃣ The Event Loop waits until the stack is empty 6️⃣ Then it pushes "Inside Timeout" to the stack That’s the Event Loop in action 🚀 Understanding this concept made: ✅ Promises easier ✅ Async/Await clearer ✅ Debugging smoother If you're learning JavaScript, mastering the Event Loop is a big step forward. #JavaScript #WebDevelopment #BeginnerDeveloper #AsyncProgramming #FrontendDevelopment #mernstack #fullstack
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