Skip to main content

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 typeImmutable way
Arraymap(), filter(), concat(), spread ([...])
Object{ ...obj, key: newValue }
StringAlways immutable (strings cannot be changed in JS)

Examples of mutable operations (to avoid in pure functions)

Data typeOperation
Arraypush(), pop(), splice(), sort(), reverse()
ObjectDirect 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

PropertyImmutable function
Changes input dataNo
Creates new structuresYes
Side effectsNone
PredictabilityHigh
Examplesmap, filter, reduce

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.