What is Immutability?

Immutability is a design pattern where something can't be modified after being instantiated. If we want to change the value of that thing, we must recreate it with the new value instead. Some JavaScript types are immutable and some are mutable, meaning their value can change without having to recreate it. Let's explain this difference with some examples:

  1. let movie = {
  2. name: 'Star Wars',
  3. episode: 7
  4. };
  5. let myEp = movie.episode;
  6. movie.episode = 8;
  7. console.log(myEp); // outputs 7

As you can see in this case, although we changed the value of movie.episode, the value of myEp didn't change. That's because movie.episode's type, number, is immutable.

  1. let movie1 = {
  2. name: 'Star Wars',
  3. episode: 7
  4. };
  5. let movie2 = movie1;
  6. movie2.episode = 8;
  7. console.log(movie1.episode); // outputs 8

In this case however, changing the value of episode on one object also changed the value of the other. That's because movie1 and movie2 are of the Object type, and Objects are mutable.

Of the JavaScript built-in types, the following are immutable:

  • Boolean
  • Number
  • String
  • Symbol
  • Null
  • Undefined
    And the following are mutable:

  • Object

  • Array
  • Function
    String's an unusual case, since it can be iterated over using for…of and provides numeric indexers just like an array, but doing something like:
  1. let message = 'Hello world';
  2. message[5] = '-';
  3. console.log(message); // writes Hello world
This will throw an error in strict mode and fail silently in non-strict mode.

原文: https://angular-2-training-book.rangle.io/handout/immutable/what_is_immutability.html