JavaScript Const Behavior: Stack vs Heap Memory

Many developers think `𝑐𝑜𝑛𝑠𝑡` means “𝐭𝐡𝐢𝐬 𝐯𝐚𝐥𝐮𝐞 𝐜𝐚𝐧’𝐭 𝐜𝐡𝐚𝐧𝐠𝐞.” In JavaScript, that’s only half the story. The behavior of `𝑐𝑜𝑛𝑠𝑡` depends on 𝐡𝐨𝐰 𝐦𝐞𝐦𝐨𝐫𝐲 𝐰𝐨𝐫𝐤𝐬—specifically the difference between 𝐬𝐭𝐚𝐜𝐤 𝐚𝐧𝐝 𝐡𝐞𝐚𝐩 𝐦𝐞𝐦𝐨𝐫𝐲. When `𝑐𝑜𝑛𝑠𝑡` is used with 𝐩𝐫𝐢𝐦𝐢𝐭𝐢𝐯𝐞 𝐯𝐚𝐥𝐮𝐞𝐬 (numbers, strings, booleans), the value is stored directly in stack memory. Both the variable and its value become locked. Attempting to reassign it results in a `TypeError`. But objects behave differently. When you declare an object with `𝑐𝑜𝑛𝑠𝑡`, the 𝐫𝐞𝐟𝐞𝐫𝐞𝐧𝐜𝐞 (stored in the stack) is locked—but the 𝐨𝐛𝐣𝐞𝐜𝐭 𝐢𝐭𝐬𝐞𝐥𝐟 𝐥𝐢𝐯𝐞𝐬 𝐢𝐧 𝐡𝐞𝐚𝐩 𝐦𝐞𝐦𝐨𝐫𝐲. This means you can still modify its internal properties, add new ones, or delete existing ones. What you cannot do is reassign the variable to a new object. If true immutability is required, `𝙊𝙗𝙟𝙚𝙘𝙩.𝙛𝙧𝙚𝙚𝙯𝙚()` can lock the object's internal structure as well. Understanding this difference is critical for writing predictable applications—especially in modern frameworks like React where state management relies heavily on immutability. 𝐀 𝐟𝐞𝐰 𝐩𝐫𝐚𝐜𝐭𝐢𝐜𝐚𝐥 𝐡𝐚𝐛𝐢𝐭𝐬 𝐈 𝐟𝐨𝐥𝐥𝐨𝐰: ✔ Use `const` by default for safer variable declarations ✔ Treat objects as immutable in state-driven applications ✔ Use `Object.freeze()` for configuration objects that should never change Strong fundamentals in memory behavior lead to more predictable code. How do you usually enforce immutability in your JavaScript projects? #JavaScript #WebDevelopment #FrontendEngineering #MemoryManagement #Immutability #JSFundamentals #ReactJS #CleanCode

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories