liveBook · Manning

Value object

As explained in The Joy of JavaScript

An immutable object whose equality and identity are determined by its attribute values rather than by a stable external identifier.

A value object is immutable and has no external identity: its meaning, equality, and comparison come from its attributes. Changing a value creates another object or raises an error. section 4.5

Use the pattern when an object represents a value rather than a globally tracked entity:

  • Prevent modification after construction. section 4.5
  • Prevent dynamic extension, removal, or inheritance. section 4.5
  • Define equality from relevant properties instead of an identifier. section 4.5
  • Provide string and primitive representations when arithmetic or concatenation should feel natural. section 4.5

Money

Money('USD', 5) can produce new values with plus, minus, times, rounding, or negation. Thus Money('USD', 3).plus(Money('USD', 7)).equals(Money('USD', 10)) is true, while changing amount directly fails.

How The Joy of JavaScript covers it

How deep it goes
Defines design rules and demonstrates JavaScript freezing, sealing, equality, arithmetic, and primitive conversion.
Examples
Uses Money, DateTime, Point, Line, Decimal, coordinate mutation, and currency-specific arithmetic examples.
What it assumes
Assumes familiarity with immutable objects and pure-function guidelines while demonstrating the pattern through JavaScript examples.
What you can do after
Build it from scratch as a sealed, frozen JavaScript object with value-based equality and composable operations.
How it connects
Connects immutable objects, pure functions, equality, arithmetic conversion, and domain entities such as transactions and blocks.

Also explained in

Compare how 3 books explain value object →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.