Immutability

Immutability means not changing the state (the value of its properties). Also, not adding new properties to the state.

By copy the object, The state is not changing.

const object = { name: "Tim" };

function copyObject(a) {
  return { ...a }
}

console.log(copyObject(object));
console.log(object);
{ name: 'Tim' }
{ name: 'Tim' }

The idea of immutability that is not changing the state but instead making copies of the state and returning a new state every time.

Update Copied Object

const object = { name: "Tim" };

function copyObject(a) {
  return { ...a }
}

function updateObject(a){
  const newObject = copyObject(a);
  newObject.name = "Mike";
  return newObject;
}

console.log(updateObject(object));
console.log(object);
{ name: 'Mike' }
{ name: 'Tim' }

The original data is never changed.

Leave a Reply

Your email address will not be published.

ANOTE.DEV