#Classes#Coercion

Custom Coercion With valueOf and toString

A class that decides what it means to add two of its instances, or print one.

By Pratik RaiEasy

Build a NumberList class taking an array of numbers.

Adding two instances with + gives the sum of every number in both. Passing one to String() gives the numbers comma-separated inside square brackets.

Examples

Input:

JSfile.javascript
1const a = new NumberList([5, 10]); 2const b = new NumberList([20]); 3a + b; // 35 4String(a);

Output:

"[5,10]"

valueOf answers the numeric context, toString the string one.

Constraints

  • The array holds numbers and may be empty

Notes

  • Define only valueOf and String() prints "[object Object]"; define only toString and + uses it too, so a + b concatenates "[5,10][20]" instead of adding.

How to solve it

Teaching an object how to convert

When an object appears where a primitive is expected, JavaScript asks it to convert. Which method it asks depends on the context, and that is the whole problem.

Approach

Two methods, two contexts.

Implementation

JSfile.javascript
1class NumberList { 2 constructor(nums) { this.nums = nums; } 3 valueOf() { return this.nums.reduce((a, b) => a + b, 0); } 4 toString() { return '[' + this.nums.join(',') + ']'; } 5}

Worth knowing

+ asks for a number first, so valueOf answers it. String() and template literals ask for a string, so toString answers those.

Brackets around join(",") give "[]" for an empty array without a special case. When a class defines no Symbol.toPrimitive, the engine calls valueOf and toString itself, in an order set by the hint; defining Symbol.toPrimitive overrides both and receives the hint ("number", "string" or "default") directly.

Goal: Implement valueOf and toString so both coercion contexts behave.

Frequently asked questions

What is type coercion in JavaScript?
The automatic conversion of a value to the type an operation needs — an object to a number next to +, or to a string inside a template literal. Objects can control that conversion themselves.
When is valueOf called instead of toString?
valueOf answers numeric contexts and toString answers string ones. Arithmetic and unary + reach for valueOf first; String() and template literals reach for toString.
What happens if you define neither?
The object falls back to the default toString, which produces "[object Object]" — the string almost every JavaScript developer has seen in a UI at some point.
What is Symbol.toPrimitive?
A method that takes precedence over both and receives a hint of "number", "string" or "default". It gives you one place to handle every context explicitly, which is worth mentioning as the modern answer.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Key-Value Cache With Expiry

A key/value cache where every entry expires on its own timer — and setting a key again restarts its clock.

JavaScript · ES6 — Pratik Rai ·

JavaScript

Run a Function Only Once

A once wrapper: the first call runs, every call after it does nothing.

JavaScript · ES6 — Pratik Rai ·