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
JavaScript Const Behavior: Stack vs Heap Memory
More Relevant Posts
-
I used to work on a JavaScript codebase where… Every file looked like this 👇Wrapped inside a self-invoking function (IIFE). And honestly…It didn’t make sense to me at first. Why are we doing this? Then I started asking basic questions: 👉 Why do we even split code into multiple files? At a high level → separation of concerns + reusability. We write logic in one file → use it in another.That’s basically what a module system does in any language. Then the next question hit me: 👉 What does IIFE have to do with modules? Here’s the catch: JavaScript initially didn’t have a module system. No imports. No exports. So what happens? 👉 Everything runs in the global scope. Which means: My variables = global Your variables = global Third-party library variables = also global Now imagine same variable names… 💥 Collision. So how did developers deal with this? 👉 Using functions. Because functions in JavaScript create their own scope. So the idea became: Wrap everything inside a function→ invoke it immediately→ expose only what’s needed --> return statement const module = (() => { const p1 = () => {} const p2 = [] const exports = { x1: () => {}, x2: [] } return exports })() Now think about it: 👉 p1 and p2 → private👉 x1 and x2 → public Nothing leaks into global scope. That’s when it clicked for me. This is basically a manual module system. Before:→ CommonJS→ ES Modules Funny thing is… Today we just write: export const x1 = () => {} …but back then, people had to build this behavior themselves. It is not about how things work today but why they exist in the first place. BTW this pattern is called 🫴Revealing Module Pattern.👈 #JavaScript #WebDevelopment #CleanCode #DeveloperJourney #Coding #FrontendDevelopment
To view or add a comment, sign in
-
🚨 JavaScript Gotcha: Objects as Keys?! Take a look at this 👇 const a = {}; const b = { key: 'b' }; const c = { key: 'c' }; a[b] = 123; a[c] = 456; console.log(a[b]); // ❓ 👉 What would you expect? 123 or 456? 💡 Actual Output: 456 🤯 Why does this happen? In JavaScript, object keys are always strings or symbols. So when you use an object as a key: a[b] → a["[object Object]"] a[c] → a["[object Object]"] Both b and c are converted into the same string: "[object Object]" ⚠️ That means: a[b] = 123 sets " [object Object] " → 123 a[c] = 456 overwrites it → 456 So finally: console.log(a[b]); // 456 🧠 Key Takeaways ✅ JavaScript implicitly stringifies object keys ✅ Different objects can collide into the same key ❌ Using objects as keys in plain objects is unsafe 🔥 Pro Tip If you want to use objects as keys, use a Map instead: const map = new Map(); map.set(b, 123); map.set(c, 456); console.log(map.get(b)); // 123 ✅ ✔️ Map preserves object identity ✔️ No unexpected overwrites 💬 Final Thought JavaScript often hides complexity behind simplicity. Understanding these small quirks is what separates a developer from an expert. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #Coding #JavaScriptTips #JSConfusingParts #DevelopersLife #CodeNewbie #LearnToCode #SoftwareEngineering #TechTips #CodeQuality #CleanCode #100DaysOfCode #ProgrammingTips #DevCommunity #CodeChallenge #Debugging #JavaScriptDeveloper #MERNStack #FullStackDeveloper #ReactJS #NodeJS #WebDevTips #CodingLife
To view or add a comment, sign in
-
-
Most JavaScript developers think they understand equality… until this happens: {} === {} // false And suddenly… nothing makes sense. Let me show you what’s REALLY happening 👇 In JavaScript, not all data is equal. 👉 Primitives (numbers, strings…) are stored by value 👉 Objects are stored by reference (in memory) So when you compare objects, you're NOT comparing their content… You're comparing their addresses. Now here’s where things get interesting 🔥 JavaScript doesn’t just compare values… It actually transforms them behind the scenes using something called: 👉 Type Coercion Example: "5" - 1 // 4 Why? Because JS silently converts "5" → number. But what about objects? 🤔 const obj = { id: 105 }; +obj // NaN ❌ JavaScript doesn’t know how to convert it. Except… sometimes it DOES 😳 const t1 = new Date(); const t2 = new Date(); t2 - t1 // works ✅ Wait… how did that happen?! This is where things go from “JavaScript” to magic 🧠✨ Behind the scenes, JS uses: 👉 Symbol.toPrimitive A hidden mechanism that tells the engine: “Hey, if you need to convert this object… here’s how to do it.” And here’s the crazy part 👇 You can control it yourself. const user = { [Symbol.toPrimitive](hint) { return 105; } }; +user // 105 ✅ This is called: 👉 Metaprogramming You’re not just writing code… You’re controlling how the language itself behaves. 💡 Why this matters? Because: You avoid weird bugs You understand how JS REALLY works You level up from “writing code” → “engineering behavior” And now you understand why tools like TypeScript exist… 👉 To protect you from all this hidden complexity. 🚀 Final thought: Most developers try to avoid JavaScript quirks… But the best developers? They understand them… and take control. #JavaScript #Frontend #WebDevelopment #Programming #SoftwareEngineering #TypeScript #CleanCode #100DaysOfCode #MERNStack #CodingTips #LearnToCode
To view or add a comment, sign in
-
-
Here is why you will now be able to drop libraries like Moment.js and date-fns going forward For years, working with dates in JS meant dealing with absurd bugs. January was month 0. Adding a month to January 30th somehow gave you March 2nd. Because of backward compatibility, JavaScript could never fix the Date object without breaking millions of old websites. Instead, they spent almost 10 years building an entirely new API from scratch. Enter Temporal. It has reached Stage 4 of the ECMAScript standard and is actively shipping in browsers. It is widely considered the biggest addition to JS since ES2015. 1️⃣ Smart Math & Edge Cases If you add 1 month to January 30th using Temporal, it correctly returns February 28th. It understands real-world context, leap years, timezones, and daylight saving time out of the box. 2️⃣ Months Finally Start at 1 Sanity has arrived. January is month 1, not 0. You no longer have to mentally shift your numbers when reading or writing data. 3️⃣ Strict Safety Temporal refuses to participate in JavaScript's weird type coercion. If you try to compare a Temporal date with a number using >, it throws a hard error. You must use its built-in .compare() or .equals() methods, keeping your codebase extremely safe. 4️⃣ Rust Under the Hood In a historic first, the V8 engine (which powers Chrome and Edge) is using a Rust library (temporal_rs) for its core implementation instead of C++. This ensures standard, rock-solid behavior. MDN docs: https://lnkd.in/gCqkq6QA #JavaScript #WebDevelopment #FrontendEngineering #SoftwareEngineering #TemporalAPI
To view or add a comment, sign in
-
JavaScript is powerful, but also weird sometimes Some things that still surprise developers 👇 1. [] + [] → "" Reason: Arrays are converted to strings → empty string + empty string 2. [] + {} → "[object Object]" Reason: Object gets converted to string 3. {} + [] → 0 Reason: {} is treated as a block, not an object 4. typeof null → "object" Reason: Historical bug in JavaScript (never fixed) 5. NaN === NaN → false Reason: NaN is not equal to anything, even itself 6. 0.1 + 0.2 === 0.3 → false Reason: Floating point precision issue 7. false == '0' → true Reason: Type coercion converts both to number 8. [] == false → true Reason: Both become 0 after coercion 9. '' == 0 → true Reason: Empty string converts to 0 10. null == undefined → true Reason: Special equality rule in JS => Always prefer === over == to avoid surprises
To view or add a comment, sign in
-
🚀 **Day 4 – Scope Chain & Lexical Environment in JavaScript** In Day 3, we learned about Execution Context… But now the real question is: 👉 **How does JavaScript find variables when executing code?** 🤔 Let’s understand 👇 --- 💡 **What is Scope?** Scope defines **where a variable can be accessed** 👉 Simple: Scope = where is variable available ? --- 💡 **What is Scope Chain?** When JavaScript tries to access a variable: 👉 It searches in this order: * Current scope * Parent scope * Global scope 👉 This is called **Scope Chain** --- 💡 **Example:** ```js let name = "Aman"; function outer() { let city = "Indore"; function inner() { console.log(name); console.log(city); } inner(); } outer(); ``` --- 💡 **Behind the scenes:** When `inner()` runs: * looks for `name` → not in inner * goes to parent → not found * goes to global → found * looks for `city` → found in outer 👉 JavaScript climbs the **scope chain** --- 💡 **What is Lexical Environment?** 👉 It means: Scope is decided by where code is written, not where it is called --- ⚡ **Key Insight** JavaScript uses: * Scope * Scope Chain * Lexical Environment 👉 to resolve variables --- 💡 **Why this matters?** Because this is the base of: * Closures * Variable access * Debugging scope issues --- 👨💻 Continuing my JavaScript fundamentals series 👉 Next: **Hoisting (most misunderstood concept)** 👀 #JavaScript #WebDevelopment #FrontendDevelopment #Coding #SoftwareEngineer #Tech
To view or add a comment, sign in
-
-
🚀 JavaScript is finally addressing a 30-year-old problem. For decades, JavaScript’s Date object has been one of its most confusing and error-prone features. I’ve personally faced these issues multiple times while working with dates in JS: 👉 Same date string behaving differently across browsers 👉 Timezone bugs that only show up in production 👉 Unexpected mutations breaking logic 👉 And yes… months starting from 0 😅 💡 Introducing: Temporal API JavaScript is moving towards a modern date/time system designed to solve these long-standing issues. ✨ What makes Temporal better? ✔️ Immutable by default (no more accidental changes) ✔️ Clear separation of concerns (Date, Time, Timezone handled properly) ✔️ Consistent parsing across environments ✔️ First-class timezone support 🌍 ✔️ Cleaner and more readable date operations Example: Instead of: new Date() (unpredictable, mutable) We now have: Temporal.PlainDate, Temporal.PlainTime, Temporal.ZonedDateTime, and more — each with a clear purpose. 📌 Why this matters: Date bugs are among the hardest to detect and debug in real-world applications. While this is already improving things in some cases, it’s still evolving and not fully resolved everywhere yet — hoping to see complete adoption soon. 💬 Have you encountered challenges while working with dates in JavaScript? #JavaScript #WebDevelopment #Frontend #Programming #SoftwareEngineering #TemporalAPI
To view or add a comment, sign in
-
The reduce() function is one of the most powerful — and most confusing — concepts in JavaScript. But once you understand it, it becomes a game changer. In this video, I explain reduce in a simple way: • How reduce converts an array into a single value • Role of the accumulator • How values are combined step-by-step • Examples using sum and multiplication • Real-world usage in applications Example: [1,2,3,4] → 10 reduce() is widely used for: • Data transformation • Aggregation logic • Complex frontend operations Understanding reduce is essential for writing efficient JavaScript. 📺 Watch the full video: https://lnkd.in/gJpCMZKD 🎓 Learn JavaScript & React with real-world projects: 👉 https://lnkd.in/gpc2mqcf 💬 Comment LINK and I’ll share the complete JavaScript roadmap. #JavaScript #ReactJS #FrontendEngineering #WebDevelopment #SoftwareEngineering #Programming #DeveloperEducation
Why Developers Struggle with reduce()
To view or add a comment, sign in
-
💡 JavaScript Hidden Power: Arithmetic on Objects?! At first glance, applying arithmetic operators (+, -, *, /) on objects looks impossible… but JavaScript surprises us again. Take this example 👇 When we define a valueOf() method inside an object, JavaScript knows how to convert that object into a primitive number when needed. 👉 That’s exactly what’s happening here: obj1.valueOf() → returns 10 obj2.valueOf() → returns 20 So when we do: obj2 - obj1 → 20 - 10 = 10 obj2 + obj1 → 20 + 10 = 30 and so on… 🔍 Why does this work? JavaScript uses a concept called type coercion. Whenever an object is used with arithmetic operators: JS tries to convert it into a primitive value It calls: valueOf() first If not usable, then toString() 📅 What about Date objects? Date objects follow the same rule! const d1 = new Date('2026-03-25'); const d2 = new Date('2026-03-26'); console.log(d2 - d1); // 86400000 (difference in milliseconds) 👉 Why? Because Date.valueOf() returns the timestamp (milliseconds since Jan 1, 1970) 🚀 Key Takeaway JavaScript isn’t just loosely typed — it’s intelligently flexible. By customizing valueOf(): You can control how objects behave in calculations Build smarter abstractions Write more expressive code ⚠️ Pro Tip Avoid overusing this in production unless it improves clarity — unexpected coercion can confuse other developers. 🔥 JavaScript looks simple… until it isn’t. #JavaScript #WebDevelopment #MERN #Frontend #Programming #DevTips #reactjs #nodejs
To view or add a comment, sign in
-
-
"If you’re not using "map", "filter", and "reduce" in JavaScript… you're probably writing more code than needed." 😅 These 3 array methods can level up your code instantly 👇 🔹 map() 👉 Transforms each element of an array 👉 Returns a new array 💻 Example: const nums = [1, 2, 3]; const doubled = nums.map(n => n * 2); // [2, 4, 6] 🔹 filter() 👉 Filters elements based on a condition 👉 Returns a new array 💻 Example: const nums = [1, 2, 3, 4]; const even = nums.filter(n => n % 2 === 0); // [2, 4] 🔹 reduce() 👉 Reduces array to a single value 👉 Very powerful (but often misunderstood) 💻 Example: const nums = [1, 2, 3, 4]; const sum = nums.reduce((acc, curr) => acc + curr, 0); // 10 🚀 Pro Tip: Use "map" for transformation, "filter" for selection, and "reduce" for everything else. 💬 Which one do you use the most in your projects? #javascript #webdevelopment #mern #coding #developers
To view or add a comment, sign in
Explore related topics
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