Object to Primitive Conversion

Object to Primitive Conversion

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.

let user = { name: "John", age: 30, [Symbol.toPrimitive](hint) { console.log(`Hint: ${hint}`); return hint === "string" ? `User: ${this.name}` : this.age; } }; console.log(String(user)); // "User: John" (string hint) console.log(Number(user)); // 30 (number hint) console.log(user + 5); // 35 (default → number hint)

šŸ“Œ 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

let obj = { name: "Alice", toString() { return `Person: ${this.name}`; } }; console.log(String(obj)); // "Person: Alice" console.log(obj + " is here!"); // "Person: Alice is here!"

šŸ”¹ valueOf() → Converts to a number

let user = { age: 25, valueOf() { return this.age; } }; console.log(Number(user)); // 25 console.log(user + 5); // 30

šŸ“Œ 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" → Use toString(), fallback to valueOf()
  • "number" → Use valueOf(), fallback to toString()
  • "default" → Similar to "number"

Example:

let data = { toString() { return "Hello"; }, valueOf() { return 42; } }; console.log(data + " World"); // "Hello World" (toString used) console.log(data * 2); // 84 (valueOf used)

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. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close