Typorithm · hard

Coercion Puzzles

coercion-puzzlesinterview-questionscoercionoperatorstype-conversion
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Coercion Puzzles

0%

Tricky Output

The + operator concatenates if EITHER operand is a string, otherwise it adds numbers; -, *, / are always numeric. That is why "5" + 1 is "51" but "5" - 1 is 4, and 1 + "2" + 3 is "123".

The binary + operator is overloaded: if either operand is a string (after ToPrimitive), it converts both to strings and concatenates; otherwise it converts both to numbers and adds. So "5" + 1 is "51".

Every other arithmetic operator (-, *, /, %) has only a numeric mode, so it coerces both sides to numbers: "5" - 1 is 4.

Objects and arrays convert via ToPrimitive: [] becomes "", {} becomes "[object Object]". Combined with left-to-right evaluation, 1 + "2" + 3 becomes "12" then "123".

01

+ concatenates if either side is a string; else it adds.

02

-, *, / are always numeric coercion.

03

[] → "", {} → "[object Object]", +"" → 0.

"5" + 1   // "51"  — string concatenation
"5" - 1   // 4     — numeric subtraction
[] + []   // ""    — both become empty strings
[] + {}   // "[object Object]"
+""       // 0     — empty string to number
1 + "2" + 3 // "123" — left to right, string wins

Read the implementation

Connect each part of the code to the concept before you type.

1. + with a string

If either operand of + is a string, both are converted to strings and concatenated, so "5" + 1 is "51".

"5" + 1   // "51"  — string concatenation

2. - is always numeric

Minus has no string mode, so both operands convert to numbers: "5" - 1 is 4.

"5" - 1   // 4     — numeric subtraction

3. Array + object

[] becomes "" and {} becomes "[object Object]", and + concatenates them.

[] + {}   // "[object Object]"

4. Unary + to number

Unary + converts its operand to a number, and an empty string becomes 0.

+""       // 0     — empty string to number

5. Left-to-right

1 + "2" is "12", then "12" + 3 is "123" — once a string appears, the rest concatenates.

1 + "2" + 3 // "123" — left to right, string wins

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Coercion Puzzles: Lesson & Practice · Typorithm | ApplyDjinn