Trivia Questions1 min readPremium

Mutable VS Immutable

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?

When programming in JavaScript, understanding the difference between mutable and immutable objects is crucial. Mutable objects can change their state or content over time, while immutable objects cannot be modified once they are created.
An example of an immutable object in JavaScript is a string. Strings cannot be altered once they have been created; any string method that seems to modify a string actually returns a new string. MDN’s glossary entries on mutable and immutable values are a quick refresher.

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.

Premium

Keep reading with Premium

Get the rest of this guide plus every premium question, solution, and system design deep dive.

  • All premium solutions
  • System design deep dives
  • Company-specific prep

4.9/5 from our users