Immutability in functions
Detailed explanation
Immutability is one of the key principles of pure and predictable functions. If a function mutates the data passed to it (an array, an object, etc.), it affects external state → it becomes impure and hard to debug.
Example with mutation (not immutable)
javascript
function addItem(arr, item) {
arr.push(item); // mutates the original array
return arr;
}
const numbers = [1, 2, 3];
const result = addItem(numbers, 4);
console.log(numbers); // [1, 2, 3, 4] - the original data changed!This is a mutable approach - the function changes its arguments.
Immutable version
javascript
function addItem(arr, item) {
return [...arr, item]; // creates a new array
}
const numbers = [1, 2, 3];
const result = addItem(numbers, 4);
console.log(numbers); // [1, 2, 3] - the original data is preserved
console.log(result); // [1, 2, 3, 4]The function did not change the input data, it returned a new copy - that is immutability.
Examples of immutable operations
| Data type | Immutable way |
|---|---|
| Array | map(), filter(), concat(), spread ([...]) |
| Object | { ...obj, key: newValue } |
| String | Always immutable (strings cannot be changed in JS) |
Examples of mutable operations (to avoid in pure functions)
| Data type | Operation |
|---|---|
| Array | push(), pop(), splice(), sort(), reverse() |
| Object | Direct assignment obj.key = value |
Why immutability matters
Makes functions pure and predictable Simplifies debugging and testing Rules out side effects Allows operations to be safely parallelized Makes it easier to roll back and compare states (for example, in React, Redux)
SUMMARY
| Property | Immutable function |
|---|---|
| Changes input data | No |
| Creates new structures | Yes |
| Side effects | None |
| Predictability | High |
| Examples | map, filter, reduce |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.