JavaScript AcademyProfessional Engineering

Learning object 26 of 100

Reference versus value laboratory

Step through assignments of numbers, objects and arrays and see which variables share one value and which have their own copy.

Loading…

What it shows

Primitive values (numbers, strings, booleans) are copied when assigned. Objects and arrays are not: assigning one copies a reference, so both variables point to the same object and a change through one is visible through the other. === on objects compares references, not contents.

Guided experiment

  1. In Primitives, step until both variables exist. Does changing b change a?
  2. In Shared object, find the step where the original changes.
  3. In Function argument, explain why the caller's array changed.

Predict

const a = [1]; const b = a; b.push(2); What is a?

Related

Lessons: Lesson 39: Object copying and reference behavior

Projects: Project 9: Shopping Cart Price Calculator

Source: web/assets/js/objects/object-026.js in the companion repository.