JavaScript has seven primitive types and one object type. Every conversion you'll ever need — explicit, implicit, boxed, unboxed — is covered here.
1. Primitive → Object (Boxing)
Object() wraps any primitive in its object equivalent. JavaScript does this automatically when you call a method on a primitive (e.g. "hi".toUpperCase()).
Loading editor...
Use Object() in polyfills to handle primitive this contexts — this is what native call/apply do internally.
2. Object → Primitive (Unboxing)
Unwrap an object wrapper back to its primitive using .valueOf(), or let coercion do it implicitly.
Loading editor...
3. → String
Loading editor...
Gotcha: null.toString() throws — String(null) never does.
4. → Number
Loading editor...
| Method | Stops at non-digit | Handles floats | Handles hex | Handles "" |
|---|---|---|---|---|
Number() | No (→ NaN) | Yes | No | → 0 |
parseInt() | Yes | No (truncates) | Yes (with radix) | → NaN |
parseFloat() | Yes | Yes | No | → NaN |
Unary + | No (→ NaN) | Yes | No | → 0 |
5. → Boolean
Loading editor...
Interview pattern: Use !!value when you need a boolean for a condition. Use Boolean(value) when readability matters.
6. Character ↔ Number (ASCII / Unicode)
Loading editor...
7. Array ↔ String
Loading editor...
8. Object ↔ Array
Loading editor...
9. JSON Conversions
Loading editor...
10. Implicit Coercion — The Hidden Rules
Loading editor...
11. Symbol.toPrimitive — Custom Conversion
Override how an object converts with Symbol.toPrimitive:
Loading editor...
Without Symbol.toPrimitive, JS calls valueOf() first, then toString().
Quick Reference
| From → To | Method | Edge case |
|---|---|---|
| any → string | String(x) or `${x}` | String(Symbol()) works; Symbol().toString() works; template literal throws |
| string → number | Number(x) | Number("") → 0, Number(" ") → 0 |
| string → integer | parseInt(x, 10) | Always pass radix 10 |
| string → float | parseFloat(x) | Stops at first non-numeric char |
| any → boolean | Boolean(x) or !!x | [] and {} are truthy |
| any → object | Object(x) | null/undefined → {} |
| char → code | str.charCodeAt(0) | Use codePointAt for emoji |
| code → char | String.fromCharCode(n) | Use fromCodePoint for emoji |
| array → string | arr.join(sep) | Default sep is "," |
| string → array | str.split("") | Or [...str] or Array.from(str) |
| object → entries | Object.entries(obj) | Keys are always strings |
| entries → object | Object.fromEntries(arr) | Also accepts Map |
| object/array → JSON | JSON.stringify(x) | Drops functions, symbols, undefined |
| JSON → object/array | JSON.parse(str) | Throws on invalid JSON |