JavaScript

Lesson 04

Naming side effects

Name functions so callers can see when data will be mutated.

Good Code

reviewers.js
function addReviewerInPlace(reviewers, reviewer) {
  // The name warns callers that the array will mutate.
  reviewers.push(reviewer);
  return reviewers;
}

const reviewers = ["Ada"];
addReviewerInPlace(reviewers, "Lin");

Bad Code

reviewers.js
function withReviewer(reviewers, reviewer) {
  // The name sounds immutable while mutating the input array.
  reviewers.push(reviewer);
  return reviewers;
}

const reviewers = ["Ada"];
const nextReviewers = withReviewer(reviewers, "Lin");

Review Notes

What to review

Good Code

The good version makes the in-place mutation explicit, so the caller knows the original array changes.

Bad Code

The bad version sounds like it returns a new collection, but it mutates the array it receives and can surprise callers that keep using the original reference.

Takeaways

  • Make mutation visible in the function name or return a new value instead.