---
title: "Object mutability in JavaScript"
description: "Object mutability in JavaScript is a fundamental concept that directly affects how data is manipulated and shared in applications. JavaScript objects are…"
url: https://www.danny.engineering/answer/javascript/object-mutability-in-javascript
author: Danny
published: 2025-02-04T00:00:00.000Z
updated: 2025-02-04T20:02:00.000Z
tags: ["Javascript"]
---

# Object mutability in JavaScript

Object mutability in JavaScript is a fundamental concept that directly affects how data is manipulated and shared in applications. JavaScript objects are mutable by default, meaning their properties can be changed even when the object itself is declared as a `const`. While this behaviour provides flexibility, it can lead to unintended side effects in larger applications. Understanding object mutability is crucial for maintaining predictable and reliable code, especially when working with shared objects or implementing immutable data patterns in state management.

## Problem

By default, JavaScript objects are mutable, which means you can change their properties after they've been created. This introduces potential issues in scenarios like:

1. **Shared References**: When multiple variables reference the same object, changes made in one part of the code can unexpectedly reflect elsewhere.
   ```javascript
   const obj = { key: 1 };
   const ref = obj; // Both variables point to the same object

   ref.key = 2; // Modifying ref also changes obj
   console.log(obj.key); // Outputs: 2
   ```

2. **Unintended Mutations**: During function calls, if objects are passed as arguments, the function can alter the original object, leading to difficult-to-trace bugs.
   ```javascript
   const updateKey = (inputObj) => {
       inputObj.key = 3;
   };

   const myObj = { key: 1 };
   updateKey(myObj);
   console.log(myObj.key); // Outputs: 3 (unexpected mutation)
   ```

These issues make debugging, reasoning about code, or implementing functional programming patterns challenging.

## Solution

To mitigate problems caused by object mutability, several approaches can be adopted.

### **Deep Copying Objects To Avoid Shared References**

A deep copy creates a complete clone of an object or array, ensuring no reference is shared between the original and the new object. This eliminates unintended side effects.



Use techniques like `structuredClone`, libraries like [Lodash](https://lodash.com/), or manual recursion to ensure nested objects are fully copied rather than referenced.

```javascript
// Option 1: Using structuredClone (native method)
const originalObj = { key: 1, nested: { innerKey: "value" } };
const copiedObj = structuredClone(originalObj);

copiedObj.nested.innerKey = "newValue";

console.log(originalObj.nested.innerKey); // Outputs: "value" (original remains unchanged)

// Option 2: Using Lodash
const _ = require("lodash");
const lodashDeepCopy = _.cloneDeep(originalObj);
```

- Deep copies can be slow for large, deeply nested structures.
- Avoid shallow copying (e.g. `Object.assign` or spread operator) for nested objects, as they don’t prevent mutations of inner properties.

### **Object Freezing to Guard Against Mutations**

Object freezing makes an object immutable, preventing any changes to its properties. This is useful for enforcing immutability when sharing objects across functions or modules.

**How it works**: Use `Object.freeze()` to make the object immutable, or `Object.seal()` to restrict the addition/removal of properties (though values can still change).

```javascript
const obj = { key: 1 };

// Freezing the object
Object.freeze(obj);

// Attempt to mutate the object
obj.key = 2; // Fails silently in non-strict mode, or throws an error in strict mode

console.log(obj.key); // Outputs: 1 (unchanged)
```

- `Object.freeze()` is shallow, meaning nested objects remain mutable. Use recursive freezing or explicit deep handling.
- Frozen objects cannot be used in situations where updates are genuinely required.

### Further Considerations

1. **Performance**: 
   - Creating deep copies frequently can significantly impact performance, particularly for complex or large objects.
   - Use selective copying or freezing only where immutability is critical.

2. **Functional Programming**:
   - Tools like [Immutable.js](https://immutable-js.github.io/immutable-js/) or [Immer](https://immerjs.github.io/immer/) make dealing with immutable data structures easier, especially when working with state in React or Redux.

3. **Application in State Management**:
   - Enforcing immutability is a core principle in libraries like React and Redux, where predictable state transitions are necessary.

4. **Security Implication**:
   - Freezing objects or avoiding shared references can help prevent unwanted data mutations in sensitive applications, like APIs or shared library modules.

## Related Resources

For more on object mutability and immutability in JavaScript, check out the following:
- [MDN Web Docs on Objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)
- [Structured Clone API](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone)
- [Immutable.js Documentation](https://immutable-js.github.io/immutable-js/)
- [Introduction to Immutable Data in Redux](https://redux.js.org/usage/structuring-reducers/immutable-data)
