Junior
Mis on peamine erine muutuvate ja muutumatute andmetüüpide vahel?
sobes.tech AI
Vastus AI-lt
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 an "immutable" object is "changed," a new object with a new value is actually created.
Examples:
Mutable types:
ArrayObject
// Mutable example (Array)
let mutableArray = [1, 2];
mutableArray.push(3); // Modifying the existing array
console.log(mutableArray); // Output: [1, 2, 3]
// Mutable example (Object)
let mutableObject = { a: 1 };
mutableObject.b = 2; // Modifying the existing object
console.log(mutableObject); // Output: { a: 1, b: 2 }
Immutable types:
StringNumberBooleannullundefinedSymbolBigInt
// Immutable example (String)
let immutableString = "привет";
immutableString = immutableString + " мир"; // A new string is created
console.log(immutableString); // Output: привет мир
// Comparing references will show the difference
let str1 = "abc";
let str2 = str1.toUpperCase();
console.log(str1 === str2); // Output: false
// Immutable example (Number)
let immutableNumber = 10;
immutableNumber = immutableNumber + 5; // A new numeric value is created
console.log(immutableNumber); // Output: 15
Comparison:
| Attribute | Mutable types | Immutable types |
|---|---|---|
| Modification | Possible after creation | Not possible after creation |
| New reference | Remains the same | A new one is created during "change" |
Understanding this difference is critical for code predictability, state management (e.g., in React with Redux), and optimization. Using immutable data simplifies debugging, makes undo functions easier to implement, and optimizes rendering in UI frameworks by simple reference comparison.