Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I prevent a JavaScript function from modifying its input object?
Asked on Feb 10, 2026
Answer
To prevent a JavaScript function from modifying its input object, you can create a shallow copy of the object using Object.assign or the spread operator. Here's a simple example using the spread operator.
<!-- BEGIN COPY / PASTE -->
function processObject(input) {
const copy = { ...input };
// Modify the copy as needed
copy.newProperty = 'newValue';
return copy;
}
const original = { key: 'value' };
const result = processObject(original);
console.log(original); // { key: 'value' }
console.log(result); // { key: 'value', newProperty: 'newValue' }
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The spread operator `{ ...input }` creates a shallow copy of the input object.
- The original object remains unchanged, as modifications are applied to the copy.
- For deep cloning (nested objects), consider using libraries like Lodash or structured cloning methods.
- Always test your code to ensure the copy behaves as expected.
Recommended Links:
