Slide 1

Slide 1 text

practically immutable ! Immutable data in JS @sebasporto

Slide 2

Slide 2 text

I build CRUD apps, mostly

Slide 3

Slide 3 text

What? • Something that cannot change • Once created stays the same

Slide 4

Slide 4 text

var array1 = [1, 2].immutable var array2 = array1.push(3) ! array1 //=> [1, 2] array2 //=> [1, 2, 3]

Slide 5

Slide 5 text

WHY?

Slide 6

Slide 6 text

# 1 no side effects

Slide 7

Slide 7 text

var orders = [1, 2]; processOrders(orders); what is orders after this?

Slide 8

Slide 8 text

Predictability Store Comp Comp Data Data wants to sort data wants to transform data doesn't want its data to be modified externally

Slide 9

Slide 9 text

Enforces uni directional data flow React + Flux Store Comp Action

Slide 10

Slide 10 text

# 2 Easier workflows

Slide 11

Slide 11 text

Undo add(item) { history.push(items) items = items.push(item) } undo() { items = history.pop() }

Slide 12

Slide 12 text

Dirty objects Get record from store Clone record Edit record Save Replace original Yes Discard No

Slide 13

Slide 13 text

Dirty objects Get record from store Edit record Save Replace original Yes Discard No

Slide 14

Slide 14 text

HOW?

Slide 15

Slide 15 text

clojurescript immutable data for free but this talk is about plain JS

Slide 16

Slide 16 text

• In JS strings and numbers are immutable (not the case in every language) • Arrays, objects are not - so we need help here • JS and immutable data => opposing forces

Slide 17

Slide 17 text

immutable.js • Great for simple collections • [1, 2, ...] ['a', 'b' ...] • Caveats for collections with objects https://github.com/facebook/immutable-js

Slide 18

Slide 18 text

Immutable.js var record = {label: 'Sam'}; var list = Immutable.List([record]); ! console.log(list.get(0).label) // => 'Sam' http://jsbin.com/dilupu/1/embed?js,console record.label = 'Biff' ! console.log(list.get(0).label) // => 'Biff' Opps!

Slide 19

Slide 19 text

immutable.js To be fair: Immutable.js can do the right thing if you learn it really well Immutable.js != Just works™

Slide 20

Slide 20 text

Seamless immutable • Fixes Immutable.js issues with deep objects https://github.com/rtfeldman/seamless-immutable

Slide 21

Slide 21 text

var record = {label: 'Sam'}; var list = Immutable([record]); ! console.log(list[0].label) // => 'Sam' ! record.label = 'Biff' ! console.log(list[0].label) // => 'Sam' http://jsbin.com/fayupu/1/edit?js,console Seamless immutable

Slide 22

Slide 22 text

imm https://github.com/sporto/imm • Build on top of seamless-immutable • Nice CRUD API

Slide 23

Slide 23 text

imm list = list.add(record) list = list.replace(record) list = list.remove(id) ! record = list.get(id)

Slide 24

Slide 24 text

in Conclusion

Slide 25

Slide 25 text

Immutable data can make
 your application more robust

Slide 26

Slide 26 text

but play a lot with your chosen lib, 
 understand the caveats

Slide 27

Slide 27 text

Thanks