If Hoisting Confuses You, Your JavaScript Fundamentals Aren’t Strong Ask a JavaScript developer one simple question: “What is hoisting?” Most people answer confidently: “JavaScript moves variables and functions to the top.” And that’s exactly how you know… they don’t really understand JavaScript. Because JavaScript never moves your code. The Hoisting Illusion Hoisting isn’t magic. It’s not code rearrangement. It’s not a compiler trick. Hoisting is a side effect of how JavaScript creates memory before execution. That difference matters. A lot. What Actually Happens (The Real Story) Before any JavaScript code runs, the engine does two phases: 1️⃣ Memory Creation Phase Allocates memory for variables and functions Function declarations get fully stored Variables declared with var get undefined let and const are placed in the Temporal Dead Zone (TDZ) 2️⃣ Execution Phase Code runs line by line Values are assigned Functions are invoked No code moves. Only memory is prepared. Why Fake Confidence Falls Apart People who memorize hoisting say things like: “let is not hoisted” “Functions are hoisted but variables are not” Both are wrong. Everything is hoisted. The difference is how it’s initialized. That’s why this works: console.log(a); // undefined var a = 10; But this crashes: console.log(b); // ReferenceError let b = 10; Same hoisting. Different memory rules. Production Reality Check Hoisting bugs don’t show up in tutorials. They show up as: undefined values in production Weird behavior after refactors “Works on localhost, breaks in prod” And the dev says: “JavaScript is weird.” No. Your understanding was shallow. The Real Test of JavaScript Skill If someone can clearly explain: Why var behaves differently What TDZ actually is Why function declarations work before definition They don’t just know JavaScript. They understand it. The Interview Trap Hoisting is dangerous because: Beginners memorize rules Intermediates repeat slogans Seniors explain execution context Interviewers know this. Hoisting questions aren’t about syntax — they’re about mental models. If you understand hoisting, you understand: Execution context Scope Closures (Indirectly) the event loop Miss hoisting, and everything else is shaky. Final Thought Hoisting doesn’t expose beginners. It exposes pretenders. If you want real JavaScript confidence: Stop memorizing rules. Start understanding the engine. That’s where real senior devs are made. #javascript #webdevelopment #frontend #react #programming #softwareengineering
JavaScript Hoisting Explained: Memory Creation and Execution Phases
More Relevant Posts
-
🚀 Day 4 / 100 — JavaScript Fundamentals Refresher #100DaysOfCode challenge Today I revised some core JavaScript concepts that every developer should know. These are small things we often overlook… but they’re essential for debugging and writing clean code. Here’s a quick JavaScript revision :👇 🧠 1. Hoisting Hoisting means JavaScript moves variable and function declarations to the top of their scope before execution. console.log(a); // undefined var a = 5; Why undefined? Because var a is hoisted, but the value 5 is assigned later. So internally JS sees this as: var a; console.log(a); a = 5; ⚡ 2. Hoisting with let and const let and const are also hoisted, but they behave differently. They cannot be accessed before declaration. console.log(a); // ❌ ReferenceError let a = 10; Unlike var, they are not initialized during hoisting. 🚫 3. Temporal Dead Zone (TDZ) The Temporal Dead Zone is the time between: • When a variable is hoisted • And when it is declared During this period, the variable exists but cannot be accessed. Example: console.log(a); // ReferenceError let a = 10; The variable a is in the Temporal Dead Zone until the line where it’s declared. This prevents many bugs that happened with var. 🖥️ 4. console.log() The most common debugging tool. console.log("Hello World"); Used to: • Print values • Inspect objects • Debug logic Think of it as a developer’s flashlight 🔦 ❌ 5. console.error() Used to display error messages in the console. console.error("Something went wrong"); Usually appears in red and helps identify critical problems quickly. ⚠️ 6. console.warn() Used for warnings that might cause issues later. console.warn("This feature is deprecated"); Displayed in yellow in most browsers. ⏱️ 7. setTimeout() Executes a function once after a delay. setTimeout(() => { console.log("Runs after 2 seconds"); }, 2000); Common uses: • Delayed UI actions • Notifications • API retries 🔁 8. setInterval() Executes a function repeatedly after a fixed interval. setInterval(() => { console.log("Runs every 2 seconds"); }, 2000); Used for: • Timers • Polling APIs • Real-time updates 💡 Key takeaway: Great developers don’t just chase new frameworks — they master the fundamentals. Revisiting JavaScript basics always uncovers something new. 🔥 Day 4 completed. 96 days to go. #javascript #100daysofcode #webdevelopment #coding #developers #programming #learninpublic #buildinpublic #SheryiansCodingSchool #Sheryians
To view or add a comment, sign in
-
-
💻 Day 88 — Mastering JavaScript Objects Today's learning was focused on one of the most important foundations of JavaScript: Objects. Objects are everywhere in JS — from APIs to DOM elements, browser events, user data, configurations, classes, and much more. Understanding them deeply is crucial for becoming a strong JavaScript developer. 🎯 What I Learned / Practiced 🔹 Creating & Accessing Objects — Learned how to create objects with key–value pairs and practiced accessing values using dot notation; discovered that JavaScript handles duplicate keys by overriding earlier values with the latest one 🔹 Extracting Keys, Values & Entries — Practiced using Object.keys() to return all keys, Object.values() to return all values, and Object.entries() to return key–value pairs; these are extremely useful when iterating over objects or converting them into arrays 🔹 Updating & Deleting Object Properties — Learned that object properties can be updated anytime and unwanted keys can be removed using the delete operator 🔹 Understanding this Keyword — Explored how this works inside objects; inside an object method, this refers to the current object, making it possible to access its properties 🔹 Functions & Object Context (call, apply, bind) — Learned how to borrow object properties into standalone functions using call() to invoke the function with a given object, apply() (similar to call but accepts an array of arguments), and bind() to return a new function with fixed object context 🔹 JavaScript Quirks (Type Coercion) — Explored surprising JavaScript comparisons like false == [], false == '', and false == ![], which showed how loose equality (==) performs type coercion and can produce unexpected results 💡 Simple Example I created an object representing a user with properties like name and age. Then I used this inside a method to access those properties. I also practiced using call() to borrow a method from one object and use it with another object's data. This helped me understand how execution context works and how to control it when needed. 🌱 Reflection / Key Takeaways Today helped me strengthen my understanding of how objects store and manage data, context binding using this, call, apply, and bind, and JavaScript's unique type coercion behavior. These concepts form a strong base for upcoming topics like classes, prototypes, and advanced object manipulation. Objects are truly the foundation of modern JavaScript development. 🔗 Links GitHub:https://lnkd.in/gX8M3P4g Live Demo (Vercel):https://lnkd.in/gx9rBKYE 🙏 Thank you for the continuous guidance and support Codegnan | Uppugundla Sairam | Saketh Kallepu | Ambica Kiranmayee Bellamkonda #Day88 #FullStackDevelopment #FrontendDevelopment #JavaScript #Objects #WebDevelopment #LearningJourney
To view or add a comment, sign in
-
Most developers learn JavaScript… but very few actually understand how it works under the hood. Lately, I’ve been diving deep into concepts from JavaScript Hard Parts, and honestly… it completely changed how I see functions. At first, I thought a function is just: ➡️ Input → Process → Output But it turns out… that’s only half the story. Every time a function runs, JavaScript creates a new execution context → a fresh memory space that gets wiped out after execution. That’s why functions don’t “remember” anything between calls… right? Well… not always. Here’s where things get interesting 👇 When you define a function inside another function, JavaScript does something powerful and hidden: It doesn’t just store the function’s code… It also stores a link to the data around it at the moment it was created. That hidden link is what we call: 👉 Closure Think of it like this: Every function has a backpack 🎒 Inside it, there’s data from where it was defined (not where it’s called). So when the function runs later: It first checks its local memory If not found… it opens its backpack And uses that stored data And here’s the real game-changer: 🔥 Functions in JavaScript have TWO types of memory: Temporary memory → created on every run (and deleted) Persistent memory → stored in the closure (and stays alive) Even more interesting… Every time you call a function that returns another function: ➡️ You create a completely new closure Which means: Different functions Different private data Same logic… different memory Why does this matter? Because this concept powers a LOT of real-world patterns: ✅ Private variables (data hiding) ✅ Memoization (performance optimization) ✅ Module pattern (clean architecture) ✅ Async callbacks & API handling ✅ Iterators & generators The biggest mindset shift for me was this: ❌ Data access is NOT based on where a function is executed ✅ It’s based on where the function is defined (Lexical Scope) This one concept alone explains a huge part of how JavaScript really works. And once it clicks… you stop writing code that “just works” and start writing code that’s intentional, optimized, and scalable. Still learning… but this was one of those “aha” moments I had to share. If you’re learning JavaScript, don’t skip this part. It’s not just theory… it’s the foundation of everything. #JavaScript #Frontend #WebDevelopment #Programming #Closure #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
-
🚀 JavaScript Simplified Series — Day 10 Most beginners get confused when they hear this: 👉 “Functions can take other functions as input.” Wait… what? 🤯 Yes. In JavaScript, functions are first-class citizens. That means: ✔ You can store them in variables ✔ Pass them as arguments ✔ Return them from other functions And this leads to two very powerful concepts: 👉 Callback Functions 👉 Higher Order Functions 🔹 1. Callback Functions (Function inside a function) A callback is simply a function that is passed into another function and executed later. Let’s understand with a simple example 👇 function greet(name) { console.log("Hello " + name) } function processUser(name, callback) { callback(name) } processUser("Abhay", greet) 👉 Output: Hello Abhay 🔍 What’s happening here? greet is a function We pass it into processUser Inside processUser, we call it → callback(name) 📌 So, greet becomes a callback function 💡 Real-life example: Ordering food online 🍔 You place an order → wait When food is ready → delivery happens 👉 That “what happens next” is a callback 🔹 2. Higher Order Functions (Functions that use functions) A Higher Order Function (HOF) is a function that: ✔ Takes another function as input OR ✔ Returns a function Example 👇 function calculate(a, b, operation) { return operation(a, b) } function add(x, y) { return x + y } console.log(calculate(5, 3, add)) 👉 Output: 8 🔍 Breakdown: calculate is a Higher Order Function It takes operation (a function) as input Then calls it → operation(a, b) 📌 This makes your code flexible and reusable 💡 Real-life example: Think of a calculator 🧮 You give: numbers + operation Calculator decides what to do 👉 That’s exactly how HOF works 🔥 Where are these used? You already use them daily without realizing: [1, 2, 3].map(num => num * 2) 👉 map() is a Higher Order Function 👉 (num => num * 2) is a callback 🔥 Simple Summary Callback → function passed into another function Higher Order Function → function that uses other functions 💡 Programming Rule Functions are not just code… They are values you can pass around. 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 (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
-
DSA + JavaScript Journey Two incredibly important concepts today — one that completes my recursion understanding, and one that unlocks real-world JavaScript development! 🧠 ───────────────────────── 📌 DSA: Space Complexity in Recursion ───────────────────────── Most people calculate space complexity wrong for recursive functions. Today I learned exactly how to do it right! ❌ Common mistake: Adding up space from every node in the recursion tree ✅ Correct approach: Space complexity = maximum height (deepest path) of the recursion tree Why? Because of how the call stack actually works: → Each function call is pushed onto the call stack → When a call returns, it is popped off immediately → Only one branch is active at any point in time → The peak stack size = the longest path from root to base case 📊 Example — Fibonacci f(6): → f(6) → f(5) → f(4) → f(3) → f(2) → f(1) = 6 calls deep → Once f(1) returns and pops, f(2) calls f(0) — still just 1 branch active → Maximum stack size = 6 = O(n) space complexity 💡 Key insight: The call stack grows and shrinks as functions are pushed and popped. The maximum number of frames simultaneously on the stack = the deepest path = space complexity. This understanding is critical for analysing Merge Sort, Quick Sort, and all multi-branch recursive algorithms coming up next! ───────────────────────── 📌 JavaScript Revision: this Keyword & OOP Concepts ───────────────────────── Today's JS session covered one of the most confusing yet most powerful parts of the language! ⚙️ 🔑 The this Keyword → In global context → this refers to the window object → Inside a regular function → this depends on how the function is called → Inside an arrow function → this is inherited from the surrounding scope (lexical this) → Inside a method → this refers to the object that owns the method → With new keyword → this refers to the newly created object 🏗️ OOP in JavaScript → Objects & Classes — blueprint for creating objects with class syntax → Constructor — initialises object properties when created with new → Encapsulation — bundling data and methods together inside a class → Inheritance — extends keyword lets a child class inherit from a parent → super() — calls the parent class constructor → Polymorphism — same method name, different behaviour in child classes → Prototypes & prototype chain — how JS objects inherit from each other under the hood The moment it all clicked: this inside a class method always refers to the instance — that's how objects know their own data! 🤯 ───────────────────────── 🙏 Thank you, Rohit Negi Sir! ───────────────────────── Space complexity in recursion, the call stack mechanism.. From recursion to OOP — the foundations are getting rock solid. The grind continues 🔥 #DSA #Recursion #SpaceComplexity #JavaScript #OOP #ObjectOrientedProgramming #ThisKeyword #LearnToCode #100DaysOfCode #CodingJourney #WebDevelopment #Programming #CallStack
To view or add a comment, sign in
-
-
JavaScript Notes — Execution Context, Hoisting, Closures While revising JavaScript fundamentals, I wrote down a few clear notes about how the engine actually executes code. Execution Context When a JavaScript program runs, the engine creates an Execution Context. 1️⃣ Global Execution Context (GEC) This is created first when the program starts. 2️⃣ Function Execution Context (FEC) Whenever a function is called, JavaScript creates a new execution context for that function. The flow looks something like this: Global Context → Function Context → Nested Function Context → … Each function call adds a new context to the call stack, and it is removed once execution finishes. Parts of an Execution Context Every execution context contains four main components: 1. Variable Environment Stores variables and function declarations defined inside the current execution context. 2. Lexical Environment Represents the scope chain. It determines how JavaScript resolves variables by checking outer scopes. Example chain: Global Scope → Function Scope → Inner Function Scope → … 3. this Binding Represents the current execution context object. In browsers (global scope), this usually refers to the window object. 4. Outer Environment Reference Points to the parent lexical environment, which allows JavaScript to access variables from outer scopes. In function contexts, this environment also includes the arguments object, which is an array-like structure containing the arguments passed to the function. Hoisting Hoisting is how JavaScript handles variable and function declarations during the creation phase of execution. What actually happens: Declarations are registered in memory before code execution. Variables declared with var are initialized as undefined. Example: console.log(a); // undefined var a = 10; The engine internally interprets it roughly like this: var a; console.log(a); a = 10; Closure A closure happens when an inner function can access variables from its outer function even after the outer function has finished executing. This works because the inner function retains a reference to the lexical environment where it was created. Scope Scope simply defines where a variable exists and where it can be accessed. Common types: Global Scope Function Scope Block Scope (let / const) These are not “advanced tricks.” They are core mechanics of how the JavaScript engine works. If you don’t understand execution context, hoisting, and closures, debugging JavaScript becomes guesswork instead of reasoning. Currently revising fundamentals alongside DSA practice to strengthen both problem-solving and JavaScript internals. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #JavaScriptFundamentals #ExecutionContext #Closures #Hoisting #Developers #BuildInPublic #CodingJourney #TechLearning
To view or add a comment, sign in
-
🚀 JavaScript Error Handling Might Change Soon! Most JavaScript developers use try...catch every day. It works, but in real-world projects it often creates some common problems: ⚠️ Block scope limitations ⚠️ Too much boilerplate code ⚠️ Nested try/catch blocks 😵 ⚠️ Harder composition in async workflows Now there is an interesting TC39 Stage-1 proposal exploring a new idea — the JavaScript try operator. Instead of writing big try...catch blocks, errors could be converted into structured values directly inside expressions. Example 👇 const { ok, error, value } = try await fetch("/api/users") Or even this 👇 const [ok, fetchErr, res] = try fs.readFileSync("data.txt") ✨ This looks much cleaner ✨ Less nesting ✨ Easier async error handling ✨ More composable code This pattern is similar to error handling approaches used in Rust 🦀 and Go 🐹, where errors are treated as normal values instead of exceptions. I wrote a detailed blog explaining everything: 📌 How the TC39 process works 📌 Why try...catch becomes messy in large applications 📌 How the try operator proposal works 📌 Real examples and practical use cases 🔗 Read the full blog here: https://lnkd.in/gZkDbMjd 💬 Curious to hear from other developers: Would you use a try operator in JavaScript if it becomes part of the language? 🤔 #javascript #webdevelopment #programming #frontend #nodejs #softwareengineering #reactjs #nextjs #TC-39
To view or add a comment, sign in
-
What is result of [] === [] in javascript ? If you can’t answer this, your React apps are likely re-rendering way more than they should. In JavaScript and TypeScript, the answer is false. But why? Understanding this is the key to mastering performance and avoiding those "phantom" bugs in useEffect. 🏠 The "Two Houses" Analogy Imagine two houses. They have the exact same floor plan, the same paint color, and the same furniture. * Are they the same style? Yes. * Are they the same address? No. In JavaScript, Objects, Arrays, and Functions are Reference Types. When you create [], you aren't just creating a value; you are allocating a specific spot in memory (an address). * The first [] lives at Address A. * The second [] lives at Address B. When you use ===, JavaScript doesn't look at the "furniture" inside the array. It asks: "Are these two pointing to the exact same address?" Since Address A is not Address B, the result is false. ⚠️ Why this is a "React Killer" React uses Shallow Comparison to decide if it should re-render or trigger an effect. If you define an object or array inside your component body like this: useEffect(() => { // This runs on EVERY single render! console.log("Data fetched"); }, [ { id: 1 } ]); // ❌ New object = New reference every time Even though the ID is always 1, React sees a new address every time the component functions runs. It thinks the data has changed, so it triggers the effect again. And again. And again. ✅ How to fix it To keep your app fast, you need to preserve the Reference: * Move it outside: If the data is static, define it outside the component. * useMemo: Wrap objects/arrays in useMemo to keep the same memory address between renders. * useCallback: Use this for functions to prevent them from being "re-created" on every render. The Golden Rule: In React, it's not just about what the data is, it's about where it lives in memory. Have you ever spent hours debugging a useEffect loop only to realize it was a reference issue? Let’s talk about it in the comments! 👇 w3schools.com JavaScript Mastery #JavaScript #TypeScript #ReactJS #WebDevelopment #FrontendEngineering #CodingTips #PerformanceOptimization
To view or add a comment, sign in
-
-
What is result of [] === [] in javascript ? If you can’t answer this, your React apps are likely re-rendering way more than they should. In JavaScript and TypeScript, the answer is false. But why? Understanding this is the key to mastering performance and avoiding those "phantom" bugs in useEffect. 🏠 The "Two Houses" Analogy Imagine two houses. They have the exact same floor plan, the same paint color, and the same furniture. * Are they the same style? Yes. * Are they the same address? No. In JavaScript, Objects, Arrays, and Functions are Reference Types. When you create [], you aren't just creating a value; you are allocating a specific spot in memory (an address). * The first [] lives at Address A. * The second [] lives at Address B. When you use ===, JavaScript doesn't look at the "furniture" inside the array. It asks: "Are these two pointing to the exact same address?" Since Address A is not Address B, the result is false. ⚠️ Why this is a "React Killer" React uses Shallow Comparison to decide if it should re-render or trigger an effect. If you define an object or array inside your component body like this: useEffect(() => { // This runs on EVERY single render! console.log("Data fetched"); }, [ { id: 1 } ]); // ❌ New object = New reference every time Even though the ID is always 1, React sees a new address every time the component functions runs. It thinks the data has changed, so it triggers the effect again. And again. And again. ✅ How to fix it To keep your app fast, you need to preserve the Reference: * Move it outside: If the data is static, define it outside the component. * useMemo: Wrap objects/arrays in useMemo to keep the same memory address between renders. * useCallback: Use this for functions to prevent them from being "re-created" on every render. The Golden Rule: In React, it's not just about what the data is, it's about where it lives in memory. Have you ever spent hours debugging a useEffect loop only to realize it was a reference issue? Let’s talk about it in the comments! 👇 w3schools.com JavaScript Mastery #JavaScript #TypeScript #ReactJS #WebDevelopment #FrontendEngineering #CodingTips #PerformanceOptimization
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
Great explanation 👍 Very useful