Explain the difference between mutable and immutable objects. What is an example of an immutable object in JavaScript? What are the pros and cons of immutability? How can you achieve immutability in your own code?
let greeting = "Hello";
greeting[0] = "J"; // This will not change the string
console.log(greeting); // "Hello"
Pros of Immutability
- Thread Safety: Immutable objects are inherently thread-safe, allowing safe concurrent access.
- Simpler Debugging: With immutable objects, there’s less chance for bugs due to unexpected changes in state.
Cons of Immutability
- Memory Overhead: Using immutable objects might lead to increased memory use as modifications require creating new objects.
Achieving Immutability
To ensure immutability, you can use Object.freeze() to prevent changes to an object, create copies instead of mutating (with... premium content.
