Day 3: Hoisting — The JavaScript "Magic" That Isn't Magic at All! 🎩✨ Today, I tackled one of the most famous (and often misunderstood) concepts in JavaScript: Hoisting. If you've ever wondered why you can call a function before you even define it in your code, you've witnessed Hoisting in action! 🤔 What is Hoisting? Hoisting is a mechanism where variables and function declarations are moved to the top of their containing scope during the Memory Allocation Phase, before the code even starts executing. 🔍 Under the Hood (The Execution Context) Remember the "Big Box" (Execution Context) from Day 1? Here is what happens during the Memory Phase: Variables (var): JS allocates memory for variables and initializes them with a special value: undefined. Functions: JS stores the entire function body in memory. This is why: Calling a function at Line 1 works perfectly! ✅ Accessing a var at Line 1 returns undefined instead of an error! ⚠️ 💻 The Browser Demo (The Call Stack) Watching this live in the Sources tab of Chrome DevTools was a game-changer. Seeing the Global scope populate with variables before the first line of code executed made everything click. 💡 Interview Tip: When asked "What is Hoisting?", don't just say "it moves code to the top." Better Answer: "Hoisting is the process where the JS Engine allocates memory for variables and functions during the Creation Phase of the Execution Context. This allows us to access functions and variables even before they are initialized in the code, though var will return undefined until the execution reaches its assignment." Next up: Diving into how let and const handle hoisting differently (The Temporal Dead Zone!). Are you a var, let, or const person? Let's discuss below! 👇 #JavaScript #WebDevelopment #Hoisting #NamasteJavaScript #CodingInterviews #FrontendEngineer #ProgrammingLogic #JSFundamentals
Understanding JavaScript Hoisting and the Execution Context
More Relevant Posts
-
🧠 JavaScript Hoisting Explained Simply Hoisting is one of those JavaScript concepts that can feel confusing — especially when your code behaves unexpectedly. Here’s a simple way to understand it 👇 🔹 What is Hoisting? Hoisting means JavaScript moves declarations to the top of their scope before execution. But there’s a catch 👇 🔹 Example with var console.log(a); var a = 10; Output: undefined Why? Because JavaScript internally treats it like: var a; console.log(a); a = 10; 🔹 What about let and const? console.log(b); let b = 20; This throws a ReferenceError. Because "let" and "const" are hoisted too — but they stay in a “temporal dead zone” until initialized. 🔹 Function hoisting Functions are fully hoisted: sayHello(); function sayHello() { console.log("Hello"); } This works because the function is available before execution. 🔹 Key takeaway • "var" → hoisted with "undefined" • "let/const" → hoisted but not initialized • functions → fully hoisted 💡 One thing I’ve learned: Many “weird” JavaScript bugs come from not understanding hoisting properly. Curious to hear from other developers 👇 Did hoisting ever confuse you when you started learning JavaScript? #javascript #frontenddevelopment #webdevelopment #reactjs #softwareengineering #developers
To view or add a comment, sign in
-
-
🚀 JavaScript Hoisting — what it actually means (with a simple mental model) Most people say: “Variables and functions are moved to the top". Even the educators on youtube (some of them) are teaching that and even I remember answering that in my first interview call. That’s not wrong… but it’s also not the full picture. Then Priya what’s really happening? JavaScript doesn’t “move” your code. Instead, during execution, it runs in two phases: 1️⃣ Creation Phase Memory is allocated Variables → initialised as undefined Functions → fully stored in memory 2️⃣ Execution Phase Code runs line by line Values are assigned 🎨 Think of it like this: Before running your code, JavaScript prepares a “memory box” 📦 Creation Phase: a → undefined sayHi → function() { ... } Execution Phase: console.log(a) → undefined a = 10 🔍 Example 1 (var) console.log(a); // undefined var a = 10; 👉 Why? Because JS already did: var a = undefined; ⚡ Example 2 (function) sayHi(); // Works! function sayHi() { console.log("Hello"); } 👉 Functions are fully hoisted with their definition. 🚫 Example 3 (let / const) console.log(a); // ❌ ReferenceError let a = 10; 👉 They are hoisted too… But stuck in the Temporal Dead Zone (TDZ) until initialised. 🧩 Simple rule to remember: var → hoisted + undefined function → hoisted completely let/const → hoisted but unusable before declaration 💬 Ever seen undefined and wondered why? 👉 That’s hoisting working behind the scenes. #javascript #webdevelopment #frontend #reactjs #programming #100DaysOfCode
To view or add a comment, sign in
-
-
💡 Short Circuiting in JavaScript — Explained Simply In JavaScript, I came across a powerful concept called Short Circuiting. 👉 In simple words: JavaScript stops checking further values as soon as the result is decided. 🔹 OR (||) Operator It returns the first TRUE (truthy) value it finds. Example: console.log(false || "Javascript"); ✔️ Output: "Javascript" Another example: console.log(false || 10 || 7 || 15); ✔️ Output: 10 👉 Why? Because JavaScript finds 10 (true value) and stops checking further values 🔹 My Practice Code 👨💻 console.log("Short circuit in OR operator"); console.log(false || "Javascript"); console.log(false || "OR Operator"); console.log(false || 3); console.log(false || 10 || 7 || 15 || 20); // short circuit in OR operator console.log(false || "Javascript - client side scripting language" || "HTML - structure of web page" || "CSS - Cascading Style Sheet" || "Bootstrap - Framework of CSS"); 🔹 Recap: ✔️ JavaScript returns the first truthy value ✔️ It does not check remaining values once result is found ✔️ This makes code faster and efficient 📌 In simple words: Short Circuiting = JavaScript stops early when result is found #JavaScript #WebDevelopment #Coding #Learning #Frontend #100DaysOfCode
To view or add a comment, sign in
-
🧠 JavaScript Scope & Lexical Scope Explained Simply Many JavaScript concepts like closures, hoisting, and this become much easier once you understand scope. Here’s a simple way to think about it 👇 🔹 What is Scope? Scope determines where variables are accessible in your code. There are mainly 3 types: • Global Scope • Function Scope • Block Scope (let, const) 🔹 Example let globalVar = "I am global"; function test() { let localVar = "I am local"; console.log(globalVar); // accessible } console.log(localVar); // ❌ error 🔹 What is Lexical Scope? Lexical scope means that scope is determined by where variables are written in the code, not how functions are called. Example 👇 function outer() { let name = "Frontend Dev"; function inner() { console.log(name); } inner(); } inner() can access name because it is defined inside outer(). 🔹 Why this matters Understanding scope helps you: ✅ avoid bugs ✅ understand closures ✅ write predictable code 💡 One thing I’ve learned: Most “confusing” JavaScript behavior becomes clear when you understand how scope works. Curious to hear from other developers 👇 Which JavaScript concept clicked for you only after learning scope? #javascript #frontenddevelopment #webdevelopment #reactjs #softwareengineering #developers
To view or add a comment, sign in
-
-
🤯 One of the most confusing concepts in JavaScript — 'this' keyword If you've worked with JavaScript, you’ve probably asked: 👉 “What exactly does ‘this’ refer to?” Here’s the simple rule: 👉 “this = Who called me?” Let’s understand with examples 👇 📌 1. Object Method const user = { name: "Vinay", greet() { console.log(this.name); } }; user.greet(); // Vinay 👉 Here, 'this' refers to the user object 📌 2. Normal Function function show() { console.log(this); } show(); // window (in browser) 👉 Here, 'this' refers to the global object 📌 3. Arrow Function const obj = { name: "Vinay", greet: () => { console.log(this.name); } }; obj.greet(); // undefined 👉 Arrow functions don’t have their own 'this' 👉 They inherit it from the parent scope 📌 4. Event Listener button.addEventListener("click", function () { console.log(this); }); 👉 Here, 'this' refers to the clicked element 💥 Final Tip: 👉 “'this' is not about where it’s written, it’s about how it’s called.” Master this concept, and your JavaScript skills will level up 🚀 #JavaScript #WebDevelopment #Coding #DeveloperLife #Frontend #Programming #JSConcepts
To view or add a comment, sign in
-
-
🧠 Day 6 — Closures in JavaScript (Explained Simply) Closures are one of the most powerful (and frequently asked) concepts in JavaScript — and once you understand them, a lot of things start to click 🔥 --- 🔐 What is a Closure? 👉 A closure is when a function “remembers” variables from its outer scope even after that scope has finished executing. --- 🔍 Example: function outer() { let count = 0; return function inner() { count++; console.log(count); }; } const counter = outer(); counter(); // 1 counter(); // 2 --- 🧠 What’s happening? inner() still has access to count Even after outer() has finished execution This happens because of lexical scoping --- 🚀 Why Closures Matter ✔ Data privacy (like encapsulation) ✔ Used in callbacks & async code ✔ Foundation of React hooks (useState) ✔ Helps create reusable logic --- ⚠️ Common Pitfall for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } 👉 Output: 3 3 3 ✔ Fix: for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1000); } --- 💡 One-line takeaway: 👉 “A closure remembers its outer scope even after it’s gone.” --- If you’re learning JavaScript fundamentals, closures are a must-know — they show up everywhere. #JavaScript #Closures #WebDevelopment #Frontend #100DaysOfCode 🚀
To view or add a comment, sign in
-
🚀 JavaScript String Optimization You Probably Didn’t Know When you build strings in a loop like this: let bigString = ""; for (let i = 0; i < 1000; i++) { bigString += "chunk" + i; } It looks expensive… but surprisingly, it’s not (at first). 👉 JavaScript engines are smart. Instead of immediately creating a new string every time, they use something called a ConsString (concatenated string) — a lazy structure that avoids copying data. ⚡ This means: String building stays fast and memory-efficient No actual concatenation happens yet But here’s the catch… 💥 The moment you try to access the string (like bigString[0]), JavaScript materializes it — flattening everything into a real string, which can be expensive. 📌 Key Insight: Building strings → cheap Accessing/manipulating them → can trigger hidden cost 💡 Takeaway: Performance isn’t just about what you write — it’s about when the engine does the heavy work. #JavaScript #WebPerformance #CleanCode #Programming #FrontendDevelopment #DevTips #reactjs #webdevelopment
To view or add a comment, sign in
-
-
🔍 JavaScript Quirk: Hoisting (var vs let vs const) JavaScript be like: 👉 “I know your variables… before you even write them” 😅 Let’s see the magic 👇 console.log(a); var a = 10; 💥 Output: undefined Wait… no error? 🤯 Why? Because `var` is **hoisted** 📌 What is Hoisting? Hoisting is JavaScript’s behavior of **moving variable and function declarations to the top of their scope before execution**. 👉 JS internally does this: var a; console.log(a); // undefined a = 10; So the variable exists… but has no value yet. Now try with `let` 👇 console.log(b); let b = 20; 💥 Output: ReferenceError ❌ Same with `const` 👇 console.log(c); const c = 30; 💥 Error again ❌ Why? Because `let` & `const` are also hoisted… BUT they live in something called: 👉 “Temporal Dead Zone” (TDZ) Translation: 🧠 “You can’t touch it before it’s declared” --- 💡 Simple Breakdown: ✔ `var` → hoisted + initialized as `undefined` ✔ `let` → hoisted but NOT initialized ✔ `const` → same as let (but must assign value) 💀 Real dev pain: Using `var`: 👉 “Why is this undefined?” Using `let`: 👉 “Why is this error?” JavaScript: 👉 “Figure it out yourself” 😎 💡 Takeaway: ✔ Avoid `var` (legacy behavior) ✔ Prefer `let` & `const` ✔ Understand hoisting = fewer bugs 👉 JS is not weird… You just need to know its secrets 😉 🔁 Save this before hoisting confuses you again 💬 Comment “TDZ” if this finally made sense ❤️ Like for more JS quirks #javascript #frontend #codingtips #webdevelopment #js #developer
To view or add a comment, sign in
-
Have you ever struggled with timing in your JavaScript code? Understanding setTimeout and setInterval can transform how you handle asynchronous tasks. ────────────────────────────── Mastering setTimeout and setInterval Patterns Unlock the potential of setTimeout and setInterval in your JavaScript projects. #javascript #settimeout #setinterval #asynchronous #codingtips ────────────────────────────── Key Rules • Use setTimeout for one-time delays. • Use setInterval for repeated execution at intervals. • Clear intervals with clearInterval to prevent memory leaks. 💡 Try This setInterval(() => { console.log('This will run every second!'); }, 1000); setTimeout(() => { clearInterval(myInterval); console.log('Stopped the interval!'); }, 5000); ❓ Quick Quiz Q: What method would you use to execute a function repeatedly? A: setInterval. 🔑 Key Takeaway Mastering these timing functions can lead to cleaner and more efficient code! ────────────────────────────── Tests keep failing after tiny UI changes and your team wastes hours debugging selectors. Release confidence drops when flaky E2E results hide real regressions.
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