#Classes#Coercion

Array Wrapper

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

By Pratik RaiEasy

Build an ArrayWrapper 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 ArrayWrapper([1, 2]); 2const b = new ArrayWrapper([3, 4]); 3a + b; // 10 4String(a);

Output:

"[1,2]"

valueOf answers the numeric context, toString the string one.

Constraints

  • 0 <= nums.length <= 1000

Notes

  • Define only one of the two and the other context falls back to "[object Object]".

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

Source

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

Cache With Time Limit

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

JavaScript · ES6Pratik Rai ·

JavaScript

Function Composition

Fold an array of functions into one, applied right to left.

JavaScript · ES6Pratik Rai ·

JavaScript

Allow One Function Call

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

JavaScript · ES6Pratik Rai ·