0

I'm learning about immutability and pure functions. As a newbie, I'm struggling and I don't understand if the following code mutates or not the state or data.

This is the code

let state = [];

const updateState = (state, data) => {
  return [...state, data];
}

state = updateState(state, 1);


console.log(state);

I want to use a pure function that receives a state and data and updates the original state.

This line state = updateState(state, 1); feels like a mutation for me, but I'm not sure. Am I mutating the state?

Thanks for your help. I'm trying to learn.

Peter
  • 2,004
  • 2
  • 24
  • 57
  • 1
    How about writing `const newState = updateState(oldState, 1)`? It's really just a naming thing. And yes, the mutation of the `state` variable is impure in this example, but the focus should be on the `updateState` function - its purity is what actually matters. – Bergi Jan 22 '21 at 02:31
  • Thanks a lot! But if I'm using the state to persist data, how would that work? The first time I invoke the function the new state should have [1], the next time should have 1 plus the new piece of state [1,2] and so on. I don't know if I'm expressing well – Peter Jan 22 '21 at 02:35
  • Yeah, you're doing it right. Like @Bergi said the important thing is that the way you're calculating the new state is pure. – Zac Anger Jan 22 '21 at 02:38
  • 1
    @Peter Persisting data (in whatever way you mean exactly) is a side effect and ultimately cannot be done with pure functions only. – Bergi Jan 22 '21 at 02:43
  • So, if I want to use `state` to store data I cannot use pure functions and I have to mutate it, correct? Like `state.push(1)` then `state.push(2)` etc etc etc – Peter Jan 22 '21 at 02:45

1 Answers1

1

Yes, your code mutates state exactly where you think it does. updateState is a pure function because it performs no side effects, doesn't mutate anything, and will always have the same return values given the same inputs, but reassigning state is a mutation. This is also what libraries like Redux do under the hood, for example here. Note that the important thing is that the current state isn't being mutated in place, it's being completely reassigned to the value of the new state as computed by a pure function. JS isn't a great language for purity and immutability, but if your whole app was just composed of functions and immutable data (with some IO at the edges), it would be possible to never need to reassign or mutate anything (see also this question and the top answer).

Zac Anger
  • 6,983
  • 2
  • 15
  • 42
  • Thanks! I thought I was mutating. Now I will try to understand how to persist data in a functional way. – Peter Jan 22 '21 at 02:36