Is there any difference between es6 map and immutable.js map?
Asked Answered
O

2

9

I am new to immutable.js. Is there any difference between map from immutable.js and map from ES6? If there is no difference, why do we need to use immutable.js?

immutable.js

const { Map } = require('immutable')
const map1 = Map({ a: 1, b: 2, c: 3 })
const map2 = map1.set('b', 50)
map1.get('b') // 2
map2.get('b') // 50

ES6

var myMap = new Map();
myMap.set(NaN, 'not a number');
myMap.get(NaN); // "not a number"
Oddson answered 26/9, 2017 at 17:52 Comment(2)
Only one of them is immutable?Idyll
Here's a clue: const map2 = map1.set('b', 50); console.log(map1.get('b')); Try that in both.Par
C
10

When you run set on an Immutable.js map, modifying the data it contains, it will have a different address in memory. That means that map1 !== map2 in your first example, whereas the same code might say that they're the same when using ES6 maps.

The reason people really care about Maps with different data coming up as !== is that tools like React, Flux, & Redux all depend on quickly checking whether anything has changed in the state. The === is the fastest check you can use for that, but it's essentially comparing the memory addresses of the references on both sides.

If you change the contents of that object, the memory address might still be the same, because Javascript uses shallow copies for performance reasons. Immutable.js guarantees, well, immutability -- an object cannot be changed. If you change the map, now it's a new map. That means the === comparison always comes up correct.

If you're not using one of those state management libraries and are just using Immutable.js because it's trendy, then you might not have to! Even if you are using those libraries, there are other ways of guaranteeing immutability --- I've found that dot-prop-immutable delivers the functionality I need and with less overhead.

Cutter answered 26/9, 2017 at 18:1 Comment(0)
W
1

Map in ES6 is not immutable.
Following is screenshot from chrome console where I am using es6 map

output for map immutability

Whosoever answered 24/4, 2020 at 10:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.