Course contentsShow
← JavaScript
Lesson 52 of 2,7232. Values and TypesFree lesson

Pitfall: Unintended Shared State

Recognize common bugs caused by accidentally sharing object references across different parts of your code.

Pitfall: Unintended Shared State

You'll learn: How accidentally sharing object references can create confusing bugs where changing data in one place unexpectedly affects another.

The Problem

Because objects are passed by reference (not by value), multiple parts of your code can unknowingly point to the same object. When one part mutates it, all references see the change—even if you didn't intend that connection.

Think of it like multiple people sharing one Google Doc instead of each having their own copy. If someone edits it, everyone sees the changes immediately. Sometimes that's what you want, but other times you expected everyone to have independent copies.

Common Scenario

const userSettings = { theme: 'dark', notifications: true };

// You think you're creating a "copy" for a test
const testSettings = userSettings;
testSettings.theme = 'light';

console.log(userSettings.theme);  // 'light' — Oops! Original changed too

You assigned userSettings to testSettings, but that only copied the reference. Both variables point to the same object, so mutating through either name affects the shared data.

Why It's Dangerous

  • Hard to debug: Changes appear in unexpected places
  • Breaks assumptions: You think variables are independent when they're not
  • Silent failures: No error occurs—your code just behaves strangely

Spotting the Issue

Watch for assignment between objects, passing objects to functions, or storing objects in arrays. Remember: these operations share references, they don't create copies.

Key Takeaway: Unintended shared state happens when multiple references point to the same object—mutating through any reference affects all of them, often causing subtle bugs.