Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

javascript - Immutable variable and pure function updating state

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.

question from:https://stackoverflow.com/questions/65838490/immutable-variable-and-pure-function-updating-state

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...