quiz/js: update mutable and immutable objects js solution (#455)

This commit is contained in:
Nitesh Seram 2024-06-05 12:27:03 +05:30 committed by GitHub
parent ef52e9b243
commit 26bb31e288
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 115 additions and 9 deletions

View File

@ -2,9 +2,95 @@
title: Explain the difference between mutable and immutable objects
---
Immutability is a core principle in functional programming and has lots to offer to object-oriented programs as well. A mutable object is an object whose state can be modified after it is created. An immutable object is an object whose state cannot be modified after it is created.
## TL;DR
## What is an example of an immutable object in JavaScript?
- **Mutable Objects**: Allow for modification of properties and values after creation. (Default behavior for most objects)
```js
const immutableObject = Object.freeze({
name: 'John',
age: 30,
});
// Attempt to modify the object
immutableObject.name = 'Jane';
// The object remains unchanged
console.log(immutableObject); // Output: { name: 'John', age: 30 }
```
- **Immutable Objects**: Cannot be directly modified after creation. Its content cannot be changed without creating an entirely new value.
```js
const immutableObject = Object.freeze({
name: 'John',
age: 30,
});
// Attempt to modify the object
immutableObject.name = 'Jane';
// The object remains unchanged
console.log(immutableObject); // Output: { name: 'John', age: 30 }
```
The key difference between mutable and immutable objects is modifiability. Immutable objects cannot be modified after they are created, while mutable objects can be.
---
Immutability is a core principle in functional programming and has lots to offer to object-oriented programs as well.
## Mutable Objects
Mutability refers to the ability of an object to have its properties or elements changed after it's created. . A mutable object is an object whose state can be modified after it is created. In JavaScript, objects and arrays are mutable by default. They store references to their data in memory. Changing a property or element modifies the original object.
Here is an example of a mutable object:
```js
const mutableObject = {
name: 'John',
age: 30,
};
// Modify the object
mutableObject.name = 'Jane';
// The object has been modified
console.log(mutableObject); // Output: { name: 'Jane', age: 30 }
```
## Immutable Objects
An immutable object is an object whose state cannot be modified after it is created.
Here is an example of an immutable object:
```js
const immutableObject = Object.freeze({
name: 'John',
age: 30,
});
// Attempt to modify the object
immutableObject.name = 'Jane';
// The object remains unchanged
console.log(immutableObject); // Output: { name: 'John', age: 30 }
```
Primitive data types like numbers, strings, booleans, null, and undefined are inherently immutable. Once assigned a value, you cannot directly modify them. Here's an example:
```js
let name = 'Alice';
name.toUpperCase(); // This won't modify the original name variable
console.log(name); // Still prints "Alice"
// To change the value, you need to reassign a new string
name = name.toUpperCase();
console.log(name); // Now prints "ALICE"
```
### What is an example of an immutable object in JavaScript?
In JavaScript, some built-in types (numbers, strings) are immutable, but custom objects are generally mutable.
@ -12,7 +98,7 @@ Some built-in immutable JavaScript objects are `Math`, `Date`.
Here are a few ways to add/simulate immutability on plain JavaScript objects.
### Object Constant Properties
#### Object Constant Properties
By combining `writable: false` and `configurable: false`, you can essentially create a constant (cannot be changed, redefined or deleted) as an object property, like:
@ -28,7 +114,7 @@ myObject.number = 43;
console.log(myObject.number); // 42
```
### Prevent Extensions
#### Prevent Extensions
If you want to prevent an object from having new properties added to it, but otherwise leave the rest of the object's properties alone, call `Object.preventExtensions(...)`:
@ -45,13 +131,13 @@ myObject.b; // undefined
In non-strict mode, the creation of `b` fails silently. In strict mode, it throws a `TypeError`.
### Seal
#### Seal
`Object.seal()` creates a "sealed" object, which means it takes an existing object and essentially calls `Object.preventExtensions()` on it, but also marks all its existing properties as `configurable: false`.
So, not only can you not add any more properties, but you also cannot reconfigure or delete any existing properties (though you can still modify their values).
### Freeze
#### Freeze
`Object.freeze()` creates a frozen object, which means it takes an existing object and essentially calls `Object.seal()` on it, but it also marks all "data accessor" properties as writable:false, so that their values cannot be changed.
@ -63,9 +149,22 @@ let immutableObject = Object.freeze({});
Freezing an object does not allow new properties to be added to an object and prevents users from removing or altering the existing properties. `Object.freeze()` preserves the enumerability, configurability, writability and the prototype of the object. It returns the passed object and does not create a frozen copy.
## What are the pros and cons of immutability?
`Object.freeze()` makes the object immutable. However, it is not necessarily constant. `Object.freeze` prevents modifications to the object itself and its direct properties, nested objects within the frozen object can still be modified.
### Pros
```js
const obj = {
user: {},
};
Object.freeze(obj);
obj.user.name = 'John';
console.log(obj.user.name); //Output: 'John'
```
### What are the pros and cons of immutability?
#### Pros
- Easier change detection: Object equality can be determined in a performant and easy manner through referential equality. This is useful for comparing object differences in React and Redux.
- Less complicated: Programs with immutable objects are less complicated to think about, since you don't need to worry about how an object may evolve over time.
@ -74,8 +173,15 @@ Freezing an object does not allow new properties to be added to an object and pr
- Less memory needed: Using libraries like [Immer](https://immerjs.github.io/immer/) and [Immutable.js](https://immutable-js.com/), objects are modified using structural sharing and less memory is needed for having multiple objects with similar structures.
- No need for defensive copying: Defensive copies are no longer necessary when immutable objects are returning from or passed to functions, since there is no possibility an immutable object will be modified by it.
### Cons
#### Cons
- Complex to create yourself: Naive implementations of immutable data structures and its operations can result in extremely poor performance because new objects are created each time. It is recommended to use libraries for efficient immutable data structures and operations that leverage on structural sharing.
- Potential negative performance: Allocation (and deallocation) of many small objects rather than modifying existing ones can cause a performance impact. The complexity of either the allocator or the garbage collector usually depends on the number of objects on the heap.
- Complexity for cyclic data structures: Cyclic data structures such as graphs are difficult to build. If you have two objects which can't be modified after initialization, how can you get them to point to each other?
## Further reading
- [Object.freeze() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)
- [Object.seal() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal)
- [Object.preventExtensions() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions)
- [Object.preventExtensions() | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/preventExtensions)