Why don't we manually free() memory in JavaScript? Thank the Garbage Collector (GC). JavaScript is a garbage-collected language, meaning it automates memory management. This prevents a whole class of bugs, like memory leaks and dangling pointers, that are common in languages like C/C++. The core challenge for any GC is to determine which objects are no longer in use. The main algorithm JavaScript engines rely on is Mark-and-Sweep. Here’s a simplified view: Roots: The GC identifies a set of "root" objects that are always accessible (e.g., the global object, the current function's call stack). Mark Phase: It traverses the entire object graph starting from these roots. Every object it can reach is "marked" as in-use. Sweep Phase: The collector then scans the entire memory heap. Any object that was not marked is unreachable ("garbage") and is deallocated. Modern engines (like V8) use advanced variations like a generational collector. This optimizes the process by making an assumption: most objects "die young." It splits memory into a "New Generation" (or "Young Space") and an "Old Generation." New objects are created in the New Generation, which is scanned very frequently. Objects that survive a few collection cycles are "promoted" to the Old Generation, which is scanned less often. This "automatic" cleanup is a core feature of JS, but it's not "free"—GC pauses can impact an app's responsiveness. As developers, understanding this process helps us optimize our code to work with the GC, not against it. #JavaScript #NodeJS #WebDevelopment #MemoryManagement #GarbageCollection #MarkAndSweep #Performance #V8 #SoftwareArchitecture #CS
Why JavaScript doesn't need manual memory management
More Relevant Posts
-
😩 I changed one object... and everything else broke. Classic JavaScript moment. You think you’ve copied an object — but you’ve only cloned the surface. Here’s what happened to me recently 👇 const user = { name: "John", address: { city: "Berlin" } }; const clone = { ...user }; clone.address.city = "Paris"; console.log(user.address.city); // 😱 "Paris" Wait — what?! I just wanted a copy… not to move the entire family. 🧠 What’s going on? The spread operator { ...obj } or Object.assign() only makes a shallow copy. That means nested objects or arrays still share references with the original. So when you mutate one, the other changes too. ✅ The Fix If you need a deep copy, you have a few safe options: // 1️⃣ Simple & built-in (modern JS) const deepClone = structuredClone(user); // 2️⃣ Old-school workaround const deepClone = JSON.parse(JSON.stringify(user)); // 3️⃣ For complex cases (like Dates, Maps, etc.) import _ from "lodash"; const deepClone = _.cloneDeep(user); Now user and deepClone are fully independent. 💡 Takeaway > A shallow copy copies values. A deep copy copies the entire structure. Know which one you need — or your state bugs will come back to haunt you. 👻 🗣️ Your Turn Have you ever been burned by this shallow copy issue? What’s your go-to method for safe cloning? #JavaScript #WebDevelopment #CodingTips #FrontendDevelopment #CleanCode #ProgrammingBugs #ES6 #CodeSmarter #DevCommunity
To view or add a comment, sign in
-
-
V8 engine in Node.js Source website: geeksforgeeks.org "The V8 engine is an open-source JavaScript Engine developed by Google. It is primarily designed to execute JavaScript code. V8 is used in multiple applications, especially in Google Chrome, but later utilized to create Node.js for server-side coding. V8 compiles JavaScript directly to machine code rather than using an interpreter. This compilation process allows for the efficient execution of JavaScript, which is key to the performance benefits in both web browsers (like Chrome) and Node.js applications." Source link: https://lnkd.in/g3UW3EBq More Relevant Sources: ( medium.com ) https://lnkd.in/g2bemyms
To view or add a comment, sign in
-
JavaScript Tip of the Day: Spread & Rest Operators ( … ) The ... (three dots) in JavaScript might look simple — but it’s super powerful! It can expand or collect values depending on how you use it. 🔹 Spread Operator Used to expand arrays or objects. const nums = [1, 2, 3]; const moreNums = [...nums, 4, 5]; console.log(moreNums); // [1, 2, 3, 4, 5] You can also use it for objects: const user = { name: "Venkatesh", role: "Engineer" }; const updatedUser = { ...user, location: "India" }; console.log(updatedUser); 🔹 Rest Operator Used to collect remaining arguments into an array. function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0); } console.log(sum(10, 20, 30)); // 60 You can even use it in destructuring: const [first, ...rest] = [1, 2, 3, 4]; console.log(first); // 1 console.log(rest); // [2, 3, 4] 🔸 In Short: Spread → Expands data Rest → Collects data Same syntax, opposite purpose! 💬 Question for You Which operator do you use more often — Spread or Rest? Drop your answer 👇 and tag a friend learning JS! #JavaScript #Coding #WebDevelopment #LearnToCode #FrontendDevelopment #CodingCommunity #SoftwareEngineering #JavaScriptTips #JSDeveloper #ProgrammingLife #TechLearning #CodeNewbie #WebDevJourney #100DaysOfCode #ES6 #DeveloperCommunity #CodingInPublic #FullStackDeveloper #JSConcepts
To view or add a comment, sign in
-
🚀 Deep Clone an Object in JavaScript (the right way!) Most of us have tried this at least once: const clone = JSON.parse(JSON.stringify(obj)); …and then realized it breaks when the object has functions, Dates, Maps, or undefined values 😬 Let’s fix that 👇 ❌ The Problem with JSON.parse(JSON.stringify()) >It’s quick, but it: >Removes functions >Converts Dates into strings >Skips undefined, Infinity, and NaN >Fails for Map, Set, or circular references ✅ Option 1: Use structuredClone() (Modern & Fast) Available in most modern browsers and Node.js (v17+). It can handle Dates, Maps, Sets, and even circular references — no errors, no data loss. const deepCopy = structuredClone(originalObject); Simple, native, and reliable 💪 ✅ Option 2: Write Your Own Recursive Deep Clone Useful for older environments or if you want to understand the logic behind cloning. 💡 Pro Tip: If you’re working with complex or nested data structures, always prefer structuredClone(). It’s the modern, built-in, and safest way to deep clone objects in JavaScript. 🔥 Found this useful? 👉 Follow me for more JavaScript deep dives made simple — one post at a time. #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #LearnJavaScript #Programming #DeveloperCommunity #WebDev #ES6 #JSDeveloper #JavaScriptTips #JavaScriptObjects #JavaScriptClone #JavaScriptCloneObject
To view or add a comment, sign in
-
Reading JavaScript Parameters in Rust: Why Napi.rs Exists JavaScript functions pass parameters loosely typed, Rust expects strongly typed data, and C's N-API forces you to manually bridge this gap with 50+ lines of error-prone conversion code per function. Napi.rs solves this by letting you write normal Rust function signatures—it handles the type conversion automatically, eliminating the tedious glue code that makes FFI (Foreign Function Interface) development painful. You want to call fast Rust code from JavaScript. Sounds simple, right? Just pass some parameters and get a result back. But you're working across three fundamentally incompatible type systems JavaScript thinks everything is flexible: myFunction("42") // String? Sure. myFunction(42) // Number? Also fine. myFunction({value: 42}) // Object? Why not? Rust demands precision: fn my_function(value: u32) { // Must be an unsigned 32-bit integer. Period. } C's N-API speaks in raw memory: napi_value argv[1]; // Is this a string? A number? An object? // You must manually https://lnkd.in/gx4pxTAg
To view or add a comment, sign in
-
JavaScript Simplified: Destructuring & Spread Operator Ever noticed how JavaScript lets you write cleaner and shorter code? That’s where Destructuring and the Spread Operator (...) come in! What is Destructuring? Destructuring means “unpacking” values from arrays or objects into variables— instead of accessing each one manually. const user = { name: "Sameer", age: 22 }; const { name, age } = user; console.log(name, age); // Sameer 22 You can even rename or set default values: const { country: location = "India" } = user; What is the Spread Operator (...)? The spread operator helps you copy, merge, or expand arrays and objects effortlessly. const fruits = ["apple", "banana"]; const moreFruits = ["orange", "grapes"]; const allFruits = [...fruits, ...moreFruits]; console.log(allFruits); // ["apple", "banana", "orange", "grapes"] It also works great with objects: const user = { name: "Sameer", age: 22 }; const updatedUser = { ...user, age: 23 }; console.log(updatedUser); // { name: "Sameer", age: 23 } In short: Destructuring → Pull out values easily Spread → Copy or merge effortlessly #JavaScript #WebDevelopment #Frontend #CodingTips #Destructuring #SpreadOperator #LearnJS
To view or add a comment, sign in
-
Why 0.1 + 0.2 0.3 in JavaScript: The Truth About Floating-Point Numbers Why 0.1 + 0.2 ≠ 0.3 in JavaScript If you’ve ever typed this into your console: 0.1 + 0.2 === 0.3 // false console.log(0.1 + 0.2) // 0.30000000000000004 …and felt confused, you’re not alone. This tiny difference has confused developers for years, but once you understand floating-point numbers, it all makes sense. JavaScript stores every number (except BigInt) as a 64-bit IEEE 754 floating-point value. That means numbers are represented in binary, not decimal. And here’s the problem: Some decimal numbers simply can’t be represented exactly in binary form. For example: 1/3 is an infinite repeating decimal in base 10: 0.333333... Similarly, 0.1 is an infinite repeating fraction in base 2 (binary). JavaScript can’t store infinite digits, so it rounds the value slightly. That’s why when you add 0.1 + 0.2, you get 0.30000000000000004. Every floating-point number is stored as three parts: Sign bit (positive or negative) Exponent (how large or small the number is) Mantissa (the precis https://lnkd.in/gTu_5jpP
To view or add a comment, sign in
-
🚀 Deep Clone an Object in JavaScript (without using JSON methods!) Ever tried cloning an object with const clone = JSON.parse(JSON.stringify(obj)); and realized it breaks when you have functions, Dates, Maps, or undefined values? 😬 Let’s learn how to deep clone an object the right way - without relying on JSON methods. What’s the problem with JSON.parse(JSON.stringify())? t’s a quick trick, but it: ❌ Removes functions ❌ Converts Date objects to strings ❌ Skips undefined, Infinity, and NaN ❌ Fails for Map, Set, or circular references So, what’s the alternative? ✅ Option 1: Use structuredClone() (Modern & Fast) Available in most modern browsers and Node.js (v17+). structuredClone() handles Dates, Maps, Sets, and circular references like a champ! structuredClone() can successfully clone objects with circular references (where an object directly or indirectly references itself), preventing the TypeError: Converting circular structure to JSON that occurs with JSON.stringify(). ✅ Option 2: Write your own recursive deep clone For learning purposes or environments without structuredClone(). ⚡ Pro Tip: If you’re working with complex data structures (like nested Maps, Sets, or circular references), use: structuredClone() It’s native, fast, and safe. Final Thoughts Deep cloning is one of those "simple but tricky" JavaScript topics. Knowing when and how to do it properly will save you hours of debugging in real-world projects. 🔥 If you found this helpful, 👉 Follow me for more JavaScript deep dives - made simple for developers. Let’s grow together 🚀 #JavaScript #WebDevelopment #FrontendDevelopment #CodingTips #LearnJavaScript #Programming #DeveloperCommunity #AkshayPai #WebDev #ES6 #JSDeveloper #JavaScriptTips #JavaScriptObjects #JavaScriptClone #JavaScriptCloneObject
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