JavaScript Object to Primitive Conversion
In JavaScript, objects need to be converted into primitive values (like numbers, strings, or booleans) when used in operations like string concatenation or mathematical calculations. This process is called Object-to-Primitive Conversion.
1️⃣ When Does JavaScript Convert Objects to Primitives?
JavaScript automatically converts objects to primitives when:
✅ A string is expected (e.g., alert(obj)
, string concatenation)
✅ A number is expected (e.g., obj - 2
, obj * 3
)
✅ A boolean is needed (e.g., if (obj) {}
- objects are always truthy)
2️⃣ Three Types of Object-to-Primitive Conversion
JavaScript converts objects to primitive values using three hints:
1️⃣ "string" → When an object is used in a string context (e.g., alert(obj)
, obj + ""
)
2️⃣ "number" → When an object is used in math operations (e.g., obj - 1
, Number(obj)
)
3️⃣ "default" → Used in rare cases (like ==
comparison, obj + obj
)
š¹ Default falls back to number in most cases.
3️⃣ The Symbol.toPrimitive
Method (ES6)
The best way to define custom conversion logic is using the Symbol.toPrimitive
method.
š hint
values: "string"
, "number"
, "default"
š The method returns different values based on the context.
4️⃣ Using toString()
and valueOf()
Before ES6, JavaScript used toString()
and valueOf()
for conversions.
š¹ toString()
→ Converts to a string
š¹ valueOf()
→ Converts to a number
š If Symbol.toPrimitive
exists, it's used first. Otherwise, toString()
and valueOf()
are used.
5️⃣ Order of Execution
1️⃣ Check for Symbol.toPrimitive
2️⃣ Use toString()
or valueOf()
based on the hint
"string"
→ UsetoString()
, fallback tovalueOf()
"number"
→ UsevalueOf()
, fallback totoString()
"default"
→ Similar to"number"
Example:
6️⃣ Summary
✔ JavaScript converts objects to primitives when needed
✔ Use Symbol.toPrimitive
for custom conversions
✔ toString()
is used for string conversion
✔ valueOf()
is used for numeric conversion
✔ Operations like +
, -
, *
determine which method to use
š Now you know how JavaScript converts objects to primitives! Let me know if you need more examples. š