Immutability

Bryson Reynolds

What is Mutability

  • Liable or subject to change or alteration. Objects in javascript are inherently mutable. 

Inversely, Immutability is

  • Something that cannot be changed after creation. Some languages actually have this built into them (eg. Clojure)

Immutable Types in JS (Value Types)

  • string

 

 

  • number
    • If numbers were not immutable, you could change the definition of 2 with the expression 2 + 7 and all of a sudden 2 would now equal 9. 
  • Others include
    • boolean
    • null 
    • undefined
    • symbol

var statement = "I am an immutable value"; // Returns "I am an immutable value"
var otherStr = statement.slice(8, 17);  // Returns "immutable"

mutable Types in JS (Reference Types)

  • Objects
  • Arrays
  • Danger of passing a reference type and changing elsewhere (shared state)
  • Console === comparison of strings and objects

What Happens When you modify an Immutable Value

  • Simply put, you can't. Set and other methods are convenience methods that copy values into a new instance. 
// Example

var example = Immutable.fromJS({
    foo: { content: '1' },
    bar: { content: '2' }
});

So what about Const

  • Some might call const a "gotcha"
  • A const can only be defined ONCE, but it can be changed in other ways. 
  • Important Concept: the binding itself is immutable, not the value assigned to the variable. 
  • Identifier and Value association locked in place.
// Array

const carMakes = [];

carMakes.push('Ferrari', 'McLaren');

console.log(carMakes); // ['Ferrari', 'McLaren']


// Object

const favorites = {'music': 'Diplo'};

favorites.music = 'Big Gigantic';

console.log(favorites); // {'music': 'Big Gigantic'}


// Another interesting one I found was 

const favorites = {'music': 'Diplo'};

favorites = {'music': 'Big Gigantic'}; // Throws an error because you can't rebind to a different value

How does this apply to What we work with in React with Immstruct

  • Follow me down the yellow brick road

Key Points

  • Javascript has Value Types and Reference Types
    • Value types are immutable
    • Reference types are not (shared state hazard)
  • Benefit of Immutable Objects
    • Avoid shared state and accidental mutations
    • Value Equality
  • Const is an immutable binding not an immutable value

Want to learn more?

  • http://www.sitepoint.com/immutability-javascript/

Immutability

By Bryson Reynolds

Immutability

This is a slide deck explaining immutability and how we use it at uship.

  • 379