Custom Coercion With valueOf and toString

ClassesCoercion

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

Example 1
Input
const a = new NumberList([5, 10]);
const b = new NumberList([20]);
a + b;      // 35
String(a);
Output
"[5,10]"
Explanation
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.

Hints

Read the full write-up for Custom Coercion With valueOf and toString
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it