DEV Community

Discussion on: Immutability in JavaScript

Collapse
 
yvonnickfrin profile image
🦁 Yvonnick FRIN

Thank you for your question Eric!

First of all, we’re not encouraging the use of nested structures ; however if you have no choice, or if nested structures are a good fit for your needs, immutadot is here to help.

If you take this example from the article:

const animals = {
  weasels: {
    lutraLutra: {
      commonNames: ['eurasian otter'],
    },
  },
}

const newAnimals = {
  ...animals,
  weasels: {
    ...animals.weasels,
    lutraLutra: {
      ...animals.weasels.otter,
      name: 'Lutra lutra',
    },
  },
}

It can be done with immutadot like this:

import { set } from 'immutadot'

const animals = {
  weasels: {
    lutraLutra: {
      commonNames: ['eurasian otter'],
    },
  },
}

const newAnimals = set(animals, 'weasels.lutraLutra.name', 'Lutra lutra')

It results in a more concise syntax. In my opinion immutadot also brings more meaning to operations by using well-known function names. We are mostly based on ES2015+ so it’s easy to learn.

Hope it helps. Don’t hesitate to ask if you have more questions!

Collapse
 
httpjunkie profile image
Eric Bishard

That absolutely answers and yes, it is obviously more readable. I guess the next step is for me to try and apply it to some of my own code. So it, in fact, replaces the nested structure with something more declarative and moves the harder to read nested stuff out replaced with something that should be more readable and also probably reduces the possibility of syntax errors in that nested structure. I like it the syntax of set() and how it's still readable!