🧠 How Garbage Collection Works in JavaScript (Under the Hood) JavaScript handles memory automatically through Garbage Collection (GC), but understanding how it works helps developers avoid memory leaks and unintended object retention. The goal of GC is simple: 👉 Identify objects that are no longer reachable and reclaim their memory. JavaScript engines primarily rely on two algorithms. 1️⃣ Reference Counting (Historical Approach) In Reference Counting, every object maintains a count of how many references point to it. When the reference count reaches 0, the object becomes eligible for garbage collection. Example: let obj = { name: "JS" }; let ref = obj; obj = null; // reference count decreases but object still exists ref = null; // reference count becomes 0 → object can be collected ⚠️ Problem: Circular References let a = {}; let b = {}; a.ref = b; b.ref = a; Even if a and b are no longer accessible from the program, they still reference each other. Their reference count never becomes zero, leading to memory that cannot be reclaimed. 2️⃣ Mark-and-Sweep (Modern JavaScript Engines) Modern engines like V8 JavaScript Engine, Spider Monkey JavaScript Engine, and JavaScript Core use Mark-and-Sweep based garbage collection. This algorithm operates in two phases: 1. Mark Phase The GC starts from root objects (e.g., the global execution context, stack references). It recursively traverses and marks all reachable objects. 2. Sweep Phase Objects that were not marked are considered unreachable. The GC reclaims that memory. In simple terms: If an object cannot be reached from the root, it becomes garbage. ⚙️ Why This Matters for Developers Understanding GC helps when dealing with: • Closures retaining large objects • Detached DOM nodes in browsers • Long-lived references in caches or event listeners These patterns can keep objects reachable, preventing garbage collection and causing memory leaks. 💡 Takeaway JavaScript doesn’t free memory when variables go out of scope. It frees memory when objects become unreachable from the root set. #JavaScript #FrontendEngineering #MemoryManagement #V8 #WebDevelopment
JavaScript Garbage Collection Explained
More Relevant Posts
-
🧠 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 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
-
𝗧𝗵𝗲 𝗣𝗼𝘄𝗲𝗿 𝗢𝗳 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁'𝘀 𝗘𝗻𝗴𝗶𝗻𝗲 𝗢𝗽𝘁𝗶𝗺𝗶𝗭𝗮𝘁𝗶𝗼𝗻𝘀 JavaScript has become a robust platform for complex web applications. This is due to advancements in JavaScript engines like V8 and SpiderMonkey. These engines have made significant strides in optimizing JavaScript execution. Here are key milestones in JavaScript engine development: - V8 (2008): Compiled JavaScript code directly to native machine code. - TraceMonkey (2008): Introduced tracing JIT compilation. - Chakra (2009): Incorporated advanced optimization strategies and parallel processing. Modern JavaScript engine optimizations rely on Just-In-Time (JIT) compilation. This combines interpretation with compilation by translating JavaScript code into machine code at runtime. For example, consider a function that calculates the factorial of a number. The engine compiles this function during the first execution. Subsequent invocations execute the compiled code directly. Other optimization techniques include: - Inline caching: Speeds up property access on objects. - Type specialization: Optimizes performance based on argument types. - Garbage collection: Manages memory by allocating new objects in a "young" heap and promoting long-lived objects to an "old" heap. Each optimization technique has trade-offs. While JIT can produce faster execution, it adds overhead during the warm-up phase and can introduce slower paths due to deoptimizations. To write performant code, use profiling tools and remain vigilant regarding optimization pitfalls. Consider these resources for further reading: - V8 Documentation - MDN Web Docs - JavaScript Performance - JavaScript Engines in Depth - Google I/O
To view or add a comment, sign in
-
𝗧𝗵𝗲 𝗣𝗼𝘄𝗲𝗿 𝗢𝗳 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁'𝘀 𝗘𝗻𝗴𝗶𝗻𝗲 𝗢𝗽𝘁𝗶𝗺𝗶𝗭𝗮𝘁𝗶𝗼𝗻𝘀 JavaScript has become a robust platform for complex web applications. This is due to advancements in JavaScript engines like V8 and SpiderMonkey. These engines have made significant strides in optimizing JavaScript execution. Here are key milestones in JavaScript engine development: - V8 (2008): Compiled JavaScript code directly to native machine code. - TraceMonkey (2008): Introduced tracing JIT compilation. - Chakra (2009): Incorporated advanced optimization strategies and parallel processing. Modern JavaScript engine optimizations rely on Just-In-Time (JIT) compilation. This combines interpretation with compilation by translating JavaScript code into machine code at runtime. For example, consider a function that calculates the factorial of a number. The engine compiles this function during the first execution. Subsequent invocations execute the compiled code directly. Other optimization techniques include: - Inline caching: Speeds up property access on objects. - Type specialization: Optimizes performance based on argument types. - Garbage collection: Manages memory by allocating new objects in a "young" heap and promoting long-lived objects to an "old" heap. Each optimization technique has trade-offs. While JIT can produce faster execution, it adds overhead during the warm-up phase and can introduce slower paths due to deoptimizations. To write performant code, use profiling tools and remain vigilant regarding optimization pitfalls. Consider these resources for further reading: - V8 Documentation - MDN Web Docs - JavaScript Performance - JavaScript Engines in Depth - Google I/O
To view or add a comment, sign in
-
Most JavaScript developers use classes every day. But many don’t realize that JavaScript doesn’t actually have classical inheritance at all. Under the hood, everything is built on prototypes. When you access a property on an object, JavaScript doesn't just look inside that object. If the property isn’t there, the engine walks up the prototype chain until it finds it. 👀 Example: const animal = { speak() { return "Some sound"; } }; const dog = Object.create(animal); dog.bark = () => "Woof"; console.log(dog.bark()); // "Woof" console.log(dog.speak()); // "Some sound" Even though "dog" doesn’t define "speak", JavaScript finds it on "animal". Because Object.create(animal) links them through the internal [[Prototype]]. So when a property is missing, JavaScript simply keeps climbing the chain. And here’s the interesting part: Even modern syntax like `class Dog extends Animal {}` still builds the same prototype chain under the hood. Classes are just syntactic sugar. Understanding this explains a lot of weird behavior in real apps: - methods appearing where you didn’t define them - confusing this bugs - performance differences between objects JavaScript objects are basically small dictionaries connected through prototypes. 🤔 Curious: What was the most confusing JavaScript behavior you’ve debugged that suddenly made sense once you understood how the language works under the hood?
To view or add a comment, sign in
-
-
𝗝𝗮𝗵𝗮 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗦𝘆𝗻𝘁𝗮𝗫, 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁𝘀, 𝗖𝗼𝗺𝗺𝗲𝗻𝘁𝘀 & 𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲𝘀 JavaScript syntax is a set of rules that define how code must be written. JavaScript is case-sensitive. This means name, Name, and NAME are treated as different things. You use whitespace to make your code readable. - Hard to read: let x=5;let y=10;let z=x+y; - Easy to read: let x = 5; let y = 10; let z = x + y; A statement is a single instruction that tells JavaScript to do something. - let age = 25; declares a variable - console.log(age); prints the value to the console - alert("Hello, World!"); shows a popup in the browser Statements usually end with a semicolon. - let city = "Chennai"; is recommended - let city = "Chennai" also works, but avoid relying on this You can group multiple statements inside curly braces. - if (age > 18) { console.log("Adult"); console.log("Can vote"); } Comments are notes you write in your code. JavaScript ignores them when running the code. - Use // to comment out a single line - Use /* ... */ to comment across multiple lines A variable is like a labelled box - it stores a value that your program can use later. - var is the old way to declare variables - let and const are used in modern JavaScript Variable names must follow these rules: - Must start with a letter, underscore _, or dollar sign $ - Cannot start with a number - Cannot use reserved keywords You can update a variable's value. - var score = 10; - score = 20; updates the value If you declare a variable but don't assign a value, it holds the special value undefined. Key concepts: - Syntax: rules for writing valid JavaScript - Statement: a single instruction - Comment: notes in code ignored by JavaScript - Variable: a named container to store values Source: https://lnkd.in/gmeiXa5P
To view or add a comment, sign in
-
🚀 JavaScript’s New Temporal API — A Modern Fix for the Old Date Problems For years, JavaScript developers have struggled with the limitations of the built-in Date object. Timezones, inconsistent parsing, and confusing APIs often turn simple date operations into frustrating bugs. That’s exactly why Temporal is being introduced as the modern replacement for JavaScript’s legacy Date system. Here’s why Temporal is a big improvement: 🔹 Clear and Predictable API The old Date object mixes many responsibilities into one confusing interface. Temporal separates concepts like absolute time, dates, and timezones, making code easier to read and maintain. 🔹 First-Class Timezone Support Handling timezones with Date is painful and often requires external libraries. Temporal provides built-in timezone-aware objects, reducing the need for tools like Moment.js or date-fns. 🔹 Immutable by Design Date objects are mutable, which can lead to subtle bugs when values change unexpectedly. Temporal objects are immutable, making them safer and more predictable. 🔹 Better Date & Time Calculations Adding days, months, or durations with Date often leads to unexpected results. Temporal provides dedicated types like PlainDate, Duration, and ZonedDateTime for precise calculations. 🔹 More Reliable Parsing & Formatting Temporal uses standardized ISO formats, avoiding the inconsistent parsing behavior that developers frequently encounter with Date. 💡 Why This Matters for Developers Temporal isn’t just another API—it’s a complete redesign of how JavaScript handles time. It aims to eliminate many of the common bugs and frustrations developers have faced for decades. As the JavaScript ecosystem evolves, Temporal will likely become the new standard for reliable date and time handling. 👨💻 If you write JavaScript regularly, Temporal is definitely something worth learning early.
To view or add a comment, sign in
-
🚀 JavaScript Functions — Explained Functions are the backbone of JavaScript What is a Function? >> A function is a reusable block of code designed to perform a specific task. 1. Function Declaration: A function defined using the function keyword with a name. function greet(name) { return "Hello " + name; } ✔️ Hoisted (can be used before declaration) 2. Function Expression: A function stored inside a variable. const greet = function(name) { return "Hello " + name; }; ❌ Not hoisted like declarations 3. Arrow Function: A shorter syntax for writing functions using =>. const greet = (name) => "Hello " + name; ✔️ Clean and concise ⚠️ Does not have its own this 4. Parameters: Variables listed in the function definition. function add(a, b) { } >> a and b are parameters 5. Arguments: Actual values passed to a function when calling it. add(2, 3); >> 2 and 3 are arguments 6. Return Statement: The return keyword sends a value back from a function and stops execution. function add(a, b) { return a + b; } 7. Callback Function: A function passed as an argument to another function. function greet(name) { console.log("Hello " + name); } function processUser(callback) { callback("Javascript"); } 8. Higher-Order Function: A function that takes another function as an argument or returns a function. >> Examples: map(), filter(), reduce() 9. First-Class Functions: In JavaScript, functions are treated like variables. ✔️ Can be assigned to variables ✔️ Can be passed as arguments ✔️ Can be returned from other functions #JavaScript #WebDevelopment #FrontendDevelopment #Coding #Programming #LearnToCode
To view or add a comment, sign in
-
JavaScript is easy to start with - but surprisingly hard to truly understand. Many developers can write JavaScript. Far fewer understand what actually happens under the hood. And that difference is often what separates someone who just writes code from someone who can truly reason about it. Here are a few core JavaScript internals every developer should understand: 🔹 Execution Context & Call Stack JavaScript code runs inside execution contexts. Each function call creates a new execution context that gets pushed onto the call stack. Understanding this explains recursion behavior, stack overflows, and how scope is resolved during execution. 🔹 Event Loop JavaScript itself runs on a single thread, but asynchronous behavior is enabled by the runtime (e.g., the browser or Node.js). The event loop coordinates the call stack, task queue (macrotasks), and microtask queue (Promises, queueMicrotask, etc.) to decide when callbacks are executed. 🔹 Closures A closure occurs when a function retains access to variables from its lexical scope, even after the outer function has finished executing. Closures are widely used for encapsulation, stateful functions, and many library/framework patterns. 🔹 Prototypes & Inheritance JavaScript uses prototype-based inheritance. Objects can inherit properties and methods through the prototype chain. Even modern "class" syntax is syntactic sugar on top of this mechanism. 🔹 Hoisting During the creation phase of an execution context, declarations are processed before code execution. Function declarations are fully hoisted, while "var" is hoisted but initialized with "undefined". "let" and "const" are hoisted but remain in the Temporal Dead Zone until initialization. 🔹 The "this" keyword "this" is determined by how a function is called, not where it is defined. Its value depends on the call-site (method call, constructor call, explicit binding with "call/apply/bind", or arrow functions which capture "this" lexically). Once you understand these mechanics, JavaScript stops feeling "magical" - and becomes far more predictable. What JavaScript concept took you the longest to fully understand? #javascript #webdevelopment #softwareengineering #frontend
To view or add a comment, sign in
-
-
🔥 Regular Function vs Arrow Function in JavaScript — what's the real difference? This confused me when I started. Here's everything you need to know 👇 ━━━━━━━━━━━━━━━━━━━━━━━━━━ 1. The syntax is different Regular functions use the function keyword. Arrow functions use a shorter ( ) => syntax — less typing, cleaner code. 2. The "this" keyword behaves differently This is the BIG one. 📌 Regular function → has its own this. It changes depending on HOW the function is called. 📌 Arrow function → does NOT have its own this. It borrows this from the surrounding code. That's why arrow functions are great inside classes and callbacks — they don't lose track of this. 3. Arrow functions can't be used as constructors You can do new regularFunction() — works fine. You can NOT do new arrowFunction() — it throws an error. 4. Arguments object Regular functions have a built-in arguments object to access all passed values. Arrow functions don't — use rest parameters (...args) instead. ━━━━━━━━━━━━━━━━━━━━━━━━━━ ✅ When to use which? → Use arrow functions for short callbacks, array methods (.map, .filter), and when you need to keep this from the outer scope. → Use regular functions when you need your own this, use as a constructor, or need the arguments object. Understanding this = leveling up as a JavaScript developer 🚀 #JavaScript #WebDevelopment #100DaysOfCode #Frontend #CodingTips #Programming
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