Junior
What is the key difference between mutable and immutable data types?
sobes.tech AI
Answer from AI
The key difference is the ability to modify the value of an object after its creation. Mutable types allow direct modification, while immutable types do not. When "modifying" an immutable object, a new object with the new value is actually created.
Examples:
Mutable types:
ArrayObject
// Mutable example (Array)
let mutableArray = [1, 2];
mutableArray.push(3); // Modifies the existing array
console.log(mutableArray); // Outputs: [1, 2, 3]
// Mutable example (Object)
let mutableObject = { a: 1 };
mutableObject.b = 2; // Modifies the existing object
console.log(mutableObject); // Outputs: { a: 1, b: 2 }
Immutable types:
StringNumberBooleannullundefinedSymbolBigInt
// Immutable example (String)
let immutableString = "hello";
immutableString = immutableString + " world"; // Creates a new string
console.log(immutableString); // Outputs: hello world
// Comparing references shows the difference
let str1 = "abc";
let str2 = str1.toUpperCase();
console.log(str1 === str2); // Outputs: false
// Immutable example (Number)
let immutableNumber = 10;
immutableNumber = immutableNumber + 5; // Creates a new numeric value
console.log(immutableNumber); // Outputs: 15
Comparison:
| Attribute | Mutable | Immutable |
|---|---|---|
| Modification | Possible after creation | Not possible after creation |
| New reference | Remains the same | A new one is created upon "modification" |
Understanding this difference is critical for predictable code, working with states (for example, in React with Redux), and optimization. Using immutable data simplifies debugging, makes implementing undo functions easier, and optimizes rendering in UI frameworks through simple reference comparisons.