🚀 JavaScript Hoisting 💥 JavaScript Hoisting Explained: Why Your Code Breaks Before It Runs 👉 Hoisting is JavaScript's behavior of moving declarations to top of their scope during execution. 🔹 1. What Gets Hoisted? - var: Hoisted, initialized as undefined - let: Hoisted, not initialized (TDZ) - const: Hoisted, not initialized (TDZ) - function: Fully hoisted 🔹 2. Variable Hoisting (var) console.log(x); var x = 5; 👉 Output: undefined 👉 Behind the scenes: var x; console.log(x); // undefined x = 5; 🔹 3. let & const Hoisting (TDZ) console.log(a); let a = 10; 👉 Output: ReferenceError 👉 Why? Because of Temporal Dead Zone (TDZ) 👉 Variable exists but cannot be accessed before declaration 🔹 4. Function Hoisting ✅ Function Declaration (Fully Hoisted) greet(); function greet(){ console.log("Hello"); } 👉 Works perfectly ❌ Function Expression (Not Fully Hoisted) greet(); var greet = function(){ console.log("Hello"); } 👉 Output: TypeError: greet is not a function 🔹 5. Temporal Dead Zone (TDZ) 👉 Time between: Variable hoisted Variable declared During this time → ❌ cannot access variable { console.log(x); // ❌ Error let x = 5; } 🔹 6. Common Mistakes ❌ Using variables before declaration ❌ Confusing var with let ❌ Assuming all functions behave the same ⭐ Most Important Points ✅ var → hoisted with undefined ✅ let/const → hoisted but in TDZ ✅ Function declarations → fully hoisted ✅ Function expressions → not fully hoisted 🎯 Quick Summary - JavaScript moves declarations up, not values - var → usable before declaration (but undefined) - let/const → cannot use before declaration - Functions → behave differently based on type If this finally made hoisting click for you… 👉 Drop a ❤️ and comment "HOISTED" 👉 Follow Mohd Sharfuddin Khan for more bite-sized dev concepts that actually make sense
JavaScript Hoisting Explained: Var, Let, Const, and Functions
More Relevant Posts
-
*🚀 JavaScript Hoisting* Hoisting is one of the most confusing but important concepts in JavaScript. 👉 Hoisting is JavaScript's behavior of moving declarations to top of their scope during execution. React Virtual Dom vs Real Dom Tutorial: i found this Video on Youtube may be this can help you!! https://lnkd.in/d-nGsVTE *🔹 1. What Gets Hoisted?* - var: Hoisted, initialized as undefined - let: Hoisted, not initialized (TDZ) - const: Hoisted, not initialized (TDZ) - function: Fully hoisted *🔹 2. Variable Hoisting (var)* console.log(x); var x = 5; 👉 Output: undefined 👉 Behind the scenes: var x; console.log(x); // undefined x = 5; *🔹 3. let & const Hoisting (TDZ)* console.log(a); let a = 10; 👉 Output: ReferenceError 👉 Why? Because of Temporal Dead Zone (TDZ) 👉 Variable exists but cannot be accessed before declaration *🔹 4. Function Hoisting* ✅ Function Declaration (Fully Hoisted) greet(); function greet(){ console.log("Hello"); } 👉 Works perfectly ❌ Function Expression (Not Fully Hoisted) greet(); var greet = function(){ console.log("Hello"); } 👉 Output: TypeError: greet is not a function *🔹 5. Temporal Dead Zone (TDZ)* 👉 Time between: Variable hoisted Variable declared During this time → ❌ cannot access variable { console.log(x); // ❌ Error let x = 5; } *🔹 6. Common Mistakes* ❌ Using variables before declaration ❌ Confusing var with let ❌ Assuming all functions behave the same *⭐ Most Important Points* ✅ var → hoisted with undefined ✅ let/const → hoisted but in TDZ ✅ Function declarations → fully hoisted ✅ Function expressions → not fully hoisted *🎯 Quick Summary* - JavaScript moves declarations up, not values - var → usable before declaration (but undefined) - let/const → cannot use before declaration - Functions → behave differently based on type *Double Tap ❤️ For More*
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗝𝗮𝗳𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 You've worked with JavaScript, so you've heard: "JavaScript is single-threaded." Then you wonder: "How does it handle multiple things at once?" This confusion comes from a misleading idea: JavaScript does not simulate multithreading - it achieves concurrency by avoiding blocking. Here's how it works: - JavaScript runs on a single thread - One call stack, one task at a time, no parallel execution - JavaScript executes fast tasks immediately - Delegates slow tasks to the runtime (browser / Node.js) - Continues executing other code, handles results later JavaScript relies on four components: - Executes code one function at a time - Handles timers, network, etc. - Uses background threads internally - Stores completed async tasks, moves tasks from queue to stack when stack is empty This creates the illusion of multiple tasks running at once. But internally, JavaScript delegates tasks, runs other tasks, and handles results later. Your JavaScript code never runs in parallel unless you use workers. You need Web Workers (browser) or Worker Threads (Node.js) for parallel execution. This model gives non-blocking execution, high performance for I/O, and a simpler mental model. However, CPU-heavy tasks will block everything. JavaScript handles multiple tasks without multithreading by delegating slow work to the runtime, continuing execution immediately, and using the event loop to process results later. Source: https://lnkd.in/guWSNstx Optional learning community: https://t.me/GyaanSetuAi
To view or add a comment, sign in
-
Day 3/30 — JavaScript Journey JavaScript Conditionals (if / else, switch) Today your code learns to DECIDE. 🧠 Most beginners write code that runs. Great developers write code that thinks. 🔥 The Core Idea Conditionals turn JavaScript from a calculator into a decision engine. Your code stops doing everything… and starts doing the right thing at the right time. ⚡ if / else → Real-Time Decisions Use this when logic is dynamic and complex. if (user.isLoggedIn) { showDashboard(); } else { redirectToLogin(); } 👉 Reads like human thinking: “If this is true → do this, otherwise → do that.” ⚡ else if → Multiple Paths if (score > 90) { grade = "A"; } else if (score > 75) { grade = "B"; } else { grade = "C"; } 👉 Your code evaluates top → bottom First match wins. Execution stops. ⚡ switch → Clean Structured Decisions Best when comparing one value against many options switch (role) { case "admin": access = "full"; break; case "user": access = "limited"; break; default: access = "guest"; } 👉 Cleaner than multiple else if 👉 Faster to scan, easier to maintain ⚠️ Critical Concepts (Most People Miss This) • Truthiness matters if ("0") // true 😳 if (0) // false • === vs == 5 == "5" // true (loose) 5 === "5" // false (strict) 👉 Always prefer === (predictable behavior) • Missing break in switch = fall-through bug case "admin": access = "full"; // no break → next case runs too ⚠️ 🧠 Pro Insight Conditionals are not just syntax… They define your application’s behavior logic. Bad logic = bugs Good logic = clean systems 💡 When to Use What Situation Best Choice Complex logic / ranges if / else Multiple conditions else if Single variable, many values switch 🚀 Final Thought Beginners write: “Make it work” Developers evolve to: “Make it decide correctly” Because in real systems… logic is everything. If you master conditionals, you don’t just write code anymore — you control outcomes. 🔥
To view or add a comment, sign in
-
-
Promises in JavaScript Explained Simply. When working with async code, the main problem is: “How do I handle something that will complete later?” That’s where Promises come in. A Promise is basically: A value that will be available in the future. It has 3 states: Pending → still working Fulfilled → completed successfully Rejected → failed Example: const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve("Data received"); }, 1000); }); promise .then((data) => console.log(data)) .catch((err) => console.log(err)); What’s happening here? The async task starts (setTimeout) JavaScript doesn’t wait → it continues running other code Once the task is done, resolve() is called .then() handles the result Why Promises matter: Before Promises: We used callbacks → which often led to “callback hell” With Promises: Cleaner code Better error handling Easier to chain async operations Real-life example: Fetching data from an API: fetch("/api/user") .then(res => res.json()) .then(data => console.log(data)) .catch(err => console.error(err)); Key idea: A Promise doesn’t give you the result immediately it gives you a way to handle the result when it’s ready. Once you understand this, async JavaScript becomes much easier to reason about.
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 23 A website without interaction is boring… 😴 No clicks No input No response Just static content ❌ 🤔 Real Question How does a website know… 👉 When you click a button? 👉 When you type in an input? 👉 When you scroll? This is where Events come in. 🔥 What is an Event? An event is something that happens in the browser 👉 Click 👉 Hover 👉 Key press 👉 Scroll JavaScript listens to these events and reacts. 🔹 Adding an Event Listener let button = document.querySelector("button") button.addEventListener("click", function() { console.log("Button Clicked") }) 👉 When user clicks → function runs 🔹 Common Events // Click button.addEventListener("click", fn) // Input input.addEventListener("input", fn) // Key press document.addEventListener("keydown", fn) 🔹 Real Example let btn = document.querySelector("button") let heading = document.querySelector("h1") btn.addEventListener("click", function() { heading.innerText = "You clicked the button!" }) 👉 Click → text change 😎 🔹 Event Object JavaScript automatically gives event details button.addEventListener("click", function(event) { console.log(event) }) 📌 You get info like: 👉 Mouse position 👉 Target element 👉 Key pressed 🔥 Real Life Example Think of a doorbell 🔔 You press → sound comes 👉 Action → Reaction Same in JS: User action → Event → Response 🔥 Simple Summary Event → user action addEventListener → listen to event function → response 💡 Programming Rule Websites react to users. Events make that possible. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
🚀 𝗟𝗲𝘃𝗲𝗹𝗶𝗻𝗴 𝘂𝗽 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗿𝗲𝗮𝗱𝗮𝗯𝗶𝗹𝗶𝘁𝘆 𝘄𝗶𝘁𝗵 𝗧𝗲𝗺𝗽𝗹𝗮𝘁𝗲 𝗟𝗶𝘁𝗲𝗿𝗮𝗹𝘀 String concatenation in JavaScript can quickly turn messy—especially as logic scales. That’s where template literals step in and change the game. I've put together a detailed blog breaking this down: “𝗠𝗮𝘀𝘁𝗲𝗿𝗶𝗻𝗴 𝗧𝗲𝗺𝗽𝗹𝗮𝘁𝗲 𝗟𝗶𝘁𝗲𝗿𝗮𝗹𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗦𝗮𝘆 𝗚𝗼𝗼𝗱𝗯𝘆𝗲 𝘁𝗼 𝗦𝘁𝗿𝗶𝗻𝗴 𝗖𝗼𝗻𝗰𝗮𝘁𝗲𝗻𝗮𝘁𝗶𝗼𝗻 𝗡𝗶𝗴𝗵𝘁𝗺𝗮𝗿𝗲𝘀” Link: https://lnkd.in/dQdeSyxh 🔍 What the blog covers: 🔹 Why traditional string concatenation becomes hard to maintain 🔹 How template literals improve readability and developer experience 🔹 Practical use-cases with expressions and multi-line strings 🔹 Writing cleaner, more scalable JavaScript code If you're working with JavaScript, this is a small shift that delivers a big productivity gain. Grateful for the continuous learning ecosystem and guidance from: Hitesh Choudhary Piyush Garg Anirudh J. Chai Aur Code Akash Kadlag Suraj Kumar Jha Nikhil Rathore Jay Kadlag DEV Community #JavaScript #WebDevelopment #TechnicalWriting #CleanCode #LearningInPublic #Chaicode #Cohort
To view or add a comment, sign in
-
Lately, I’ve been going deeper into JavaScript coercion, and the more I study it, the less random JavaScript feels. A lot of behaviour that looks strange at first starts making sense once you realise that JavaScript is following rules defined in the ECMAScript specification. Recently, I focused on the abstract operations behind conversion, especially: - ToNumber - StringToNumber - ToString - ToPrimitive - OrdinaryToPrimitive One of the biggest takeaways for me is that JavaScript does not just “guess” what to do with values. It follows a defined process depending on the operation being performed. For example: - `"5" - 1` works because subtraction expects numbers. - `Number("")` becomes `0`. - `Number(undefined)` becomes `NaN`. - `ToNumber(BigInt)` throws an error, but `ToString(BigInt)` works. - When an object is involved, JS first tries to extract a primitive value before continuing coercion The part I found especially interesting was object-to-primitive conversion. If JavaScript encounters an object in a coercion context, it first checks for `Symbol.toPrimitive`. If that is not available, it falls back to `OrdinaryToPrimitive`, where the order of calling `toString()` and `valueOf()` depends on the hint being used: - string hint → toString() first - number hint → valueOf() first I also learned more about why string-to-number conversion behaves the way it does: - Number("25") gives 25 - Number(" 25 ") also gives 25 - Number("Infinity") gives Infinity - Number("1_000") gives NaN - Number("10n") gives NaN What is changing my understanding the most is this: - Instead of memorising “weird JavaScript behaviour”, I’m now trying to ask: 1. What operation is being performed? 2. What type of value does that operation expect? 3. Which abstract operation is JavaScript using behind the scenes? That mindset makes the language much easier to reason about. I’ve also been maintaining detailed notes on what I’m learning. If anyone wants to go deeper into these topics, I’ve uploaded them here: GitHub repo: https://lnkd.in/ephuZ-w6 #JavaScript #TypeScript #WebDevelopment #SoftwareEngineering #ECMAScript #100DaysOfCode
To view or add a comment, sign in
-
-
Day 10/30 — JavaScript Journey JavaScript Functions = The Real Power Engine ⚡ Without functions, you're just writing instructions. With functions, you start building systems. 🚀 What is a Function (Real Meaning) A function is a reusable block of logic that: Takes input (parameters) Processes it Returns output 👉 It’s how you abstract complexity and write scalable code. 🔥 Why Functions Matter (High Impact) ♻️ Reusability → Write once, use everywhere 🧠 Abstraction → Hide complexity, expose simplicity 🧱 Modularity → Break big problems into smaller units ⚡ Maintainability → Easy to debug & update 🔗 Composition → Combine small functions → powerful systems 🧠 Types of Functions (Core Arsenal) 1. Function Declaration Hoisted (can use before definition) Best for core logic 2. Function Expression Stored in variables Not hoisted → safer control 3. Arrow Functions (Modern JS) Short, clean syntax No this binding → predictable behavior 4. Higher-Order Functions (Advanced) Functions that: Take functions as input Return functions as output 👉 Backbone of functional programming ⚡ Key Concepts You MUST Master 🔹 Parameters vs Arguments Parameters = placeholders Arguments = actual values 🔹 Return vs Console return → gives value back console.log → just prints 👉 Beginners confuse this → breaks logic flow 🔹 Pure Functions Same input → same output No side effects 👉 Critical for predictable systems 🔹 Closures (Game Changer) Function remembers its scope even after execution 👉 Enables: Data privacy Function factories Advanced patterns 💣 Common Mistakes (Destroying Your Code) ❌ Not returning values ❌ Overusing global variables ❌ Writing huge monolithic functions ❌ Ignoring function naming clarity ❌ Misunderstanding this 🧩 Real-World Thinking Bad Developer ❌ → Writes 500 lines of repeated logic Smart Developer ✅ → Writes 5 reusable functions → Builds scalable architecture 🧠 Pro Insight (Level Up) Functions are not just syntax — they are design tools When you master functions: You start thinking in systems You write clean, testable, scalable code You move from coder → engineer Functions = Control + Reuse + Power If you don’t master functions, you don’t control JavaScript. If you master them, you control everything. 🚀
To view or add a comment, sign in
-
-
🚀 Callbacks vs Promises in JavaScript — Why Modern Code Avoids Callback Hell One of the biggest challenges in JavaScript is handling asynchronous operations such as API calls, file reading, or timers. For years, developers relied on Callbacks to execute code after an async task finished. But as applications grew, this approach introduced a serious problem: Callback Hell. 🕸️ Callback Hell problems • Deeply nested code (Pyramid of Doom) • Harder debugging and error handling • Poor readability and maintainability Example structure developers often struggled with: Callback → Callback → Callback → Callback 💎 Promises (ES6) changed the game A Promise represents the eventual result of an asynchronous operation. A Promise can be in one of three states: • Pending • Fulfilled • Rejected Promises improve asynchronous code by providing: ✔ Cleaner structure through Promise chaining ✔ Centralized error handling with .catch() ✔ Better readability and maintainability ⚡ Technical Advantage (Under the hood) Promises are processed through the Microtask Queue inside the JavaScript Event Loop. This means they are executed with higher priority than traditional callbacks scheduled in the task queue. ⚡ Powerful Promise utilities Modern JavaScript also provides powerful Promise tools: • Promise.all() → run multiple async operations in parallel • Promise.race() → resolve with the fastest result These utilities help improve performance and concurrency in real-world applications. 🌟 And then came async/await async/await is not a replacement for Promises. It is simply syntactic sugar built on top of Promises that allows asynchronous code to look like synchronous code — improving readability and clean architecture. 💡 Quick Summary Callback → Function executed after a task finishes Promise → Object representing the future completion or failure of an async operation 💬 Question for developers When dealing with multiple dependent API calls… Do you still use callbacks, or do you prefer the clarity of Promises / async-await? #javascript #webdevelopment #frontend #softwareengineering #coding #cleancode
To view or add a comment, sign in
-
More from this author
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