Ask any question about JavaScript here... and get an instant response.
How can I ensure a function in JavaScript remains pure when dealing with objects that need modification?
Asked on Dec 07, 2025
Answer
To ensure a function remains pure when dealing with objects, you should avoid modifying the original object and instead return a new object with the desired changes. This can be achieved using techniques like object spread syntax or `Object.assign`.
<!-- BEGIN COPY / PASTE -->
function updateObject(original, changes) {
return { ...original, ...changes };
}
const original = { a: 1, b: 2 };
const updated = updateObject(original, { b: 3 });
console.log(original); // { a: 1, b: 2 }
console.log(updated); // { a: 1, b: 3 }
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The function "updateObject" uses the object spread syntax to create a new object.
- The original object remains unchanged, ensuring the function is pure.
- The function returns a new object with the modifications applied.
- This approach helps maintain immutability in your code.
Recommended Links:
