JavaScript Immutable vs Mutable Explained

Mutable vs Immutable in JavaScript is one of those concepts that seems simple, but interviewers love to twist it. • Immutable means the value itself cannot be directly modified • Mutable means the value itself can be modified In JavaScript, all primitive types are immutable: String, Number, Boolean, Null, Undefined, Symbol, BigInt So when you do: let a = 10; a = 20; - It may look like 'a' changed, but what actually happens is that a new value is created and the variable is reassigned. - The old value remains untouched and may later be garbage-collected. - This is also why strings behave the way they do. - You can read characters using an index, but you can’t modify them. - Any “change” to a string actually creates a new string behind the scenes. - Strings are not mutable arrays — they’re immutable primitives. let str = "immutable"; str[0] = "i"; // nothing happens Objects are different. Objects are mutable, and arrays are objects in JavaScript: arr[0] = 10 → works arr.push(4) → modifies the same array in memory Here’s an important distinction: • Mutation (same object, same memory) let obj = { x: 1 }; obj.x = 2; • Reassignment (new object, new reference) let obj = { x: 1 }; obj = { x: 2 }; Even with const, this rule stays the same. const obj = { x: 1 }; obj.x = 2; // allowed → mutation obj = { x: 2 }; // error → reassignment not allowed const prevents reassignment, not mutation. You can’t point the variable to a new object, but you can change the existing object’s properties. Because objects are mutable by default, JavaScript gives us: • Object.seal() → cannot add/remove properties, but values can change • Object.freeze() → cannot add, remove, or change anything (also applies to arrays) Takeaway : • Primitives are immutable. Reassignment creates a new value. • Objects and arrays are mutable. Mutation changes the same value in memory. #FrontendDevelopment #JavaScript #JavaScriptInterview #InterviewPrep #WebDevelopment #Mutability

To view or add a comment, sign in

Explore content categories