Course contentsShow
← JavaScript
Lesson 1747 of 2,72337. Functional Programming PatternsFree lesson

Avoiding Mutation of Arguments

Learn to return new values instead of modifying objects or arrays in place.

Avoiding Mutation of Arguments

You'll learn how to write pure functions that return new values instead of modifying their input data.

When a function receives an object or array as an argument, JavaScript passes a reference to that data structure—not a copy. If your function changes properties or elements of that argument directly, you're mutating data that exists outside the function. This is a side effect that violates the principles of pure functions.

The Problem with Mutation

Imagine lending someone your notebook. If they erase your notes and write their own, your original information is gone. Instead, you'd want them to make a copy and modify that.

Similarly, when a function modifies an argument, it affects the original data:

// Impure: mutates the argument
function addItem(arr, item) {
  arr.push(item); // modifies the original array
  return arr;
}

const original = [1, 2, 3];
const result = addItem(original, 4);
console.log(original); // [1, 2, 3, 4] — original changed!

The Solution: Return New Values

Instead, create and return a new structure with the desired changes:

// Pure: returns a new array
function addItem(arr, item) {
  return [...arr, item]; // spread creates a new array
}

const original = [1, 2, 3];
const result = addItem(original, 4);
console.log(original); // [1, 2, 3] — unchanged!
console.log(result);   // [1, 2, 3, 4]

For objects, use the spread operator or techniques that copy first, modify second:

// Pure: returns a new object
function updateName(user, newName) {
  return { ...user, name: newName };
}

Key Takeaway: Pure functions treat arguments as read-only, always returning new values instead of modifying the originals—this prevents side effects and makes your code predictable.