Lesson 6
Reference, value & copying
Build a practical mental model for reference, value & copying and use it in working JavaScript.
By the end, you will be able to…
- Explain reference, value & copying in your own words
- Use reference, value & copying in a small program
- Recognize and debug a common failure mode
Build the mental model
Primitives are copied by value, but objects and arrays are copied by reference: userB doesn't get its own object, it gets a second pointer to the very same one. Mutating through either name mutates the one shared object.
Syntax and working example
Read the code from inputs to output. Predict what it prints, then run it and change one value.
Why this matters
This is the single most common source of 'I changed one thing and something unrelated also changed' bugs in real applications.
Real-world example
A bug where editing one item in a UI list mysteriously changes another is almost always two variables sharing one object by reference.
Common mistakes
- Assuming const userB = userA creates an independent copy
- Mutating a shared object when a fresh copy (via spread) was needed
- Comparing two structurally-equal objects with === and being surprised it's false (reference equality, not deep equality)
Try it yourself
Challenge
Fix renameCopy so it renames a copy without mutating the original user.
Knowledge check
After `const b = a;` where a is an object, what is true of b?
Summary
Objects and arrays are copied by reference; use spread or structuredClone to create an independent copy when needed.