Course contentsShow
← JavaScript
Lesson 283 of 2,7238. Type CoercionFree lesson

Object-to-String Coercion

The sequence toString() then valueOf() when objects are coerced to strings.

Object-to-String Coercion

What you'll learn: How JavaScript decides which method to call when converting an object to a string.

When JavaScript needs to coerce an object to a string (for example, when you use the + operator with a string and an object), it follows a specific sequence. First, it tries to call the object's toString() method. If that doesn't return a primitive value, then it tries valueOf(). If neither works, JavaScript throws an error.

This is the opposite order from object-to-number coercion, where valueOf() comes first!

The toString() → valueOf() Sequence

Think of it like asking someone for directions: first you ask them to describe the location in words (toString()), and only if they can't do that, you ask them to point to a number on a map (valueOf()).

let obj = {
  toString() {
    return "Custom string";
  },
  valueOf() {
    return 42;
  }
};

console.log(String(obj)); // "Custom string" — toString() wins
console.log("Result: " + obj); // "Result: Custom string"

If toString() returns a non-primitive, JavaScript moves to valueOf():

let obj2 = {
  toString() {
    return {}; // Not primitive, skip to valueOf()
  },
  valueOf() {
    return 99;
  }
};

console.log(String(obj2)); // "99" — valueOf() used as fallback

Without custom methods, objects use the default toString() which returns "[object Object]":

let plain = {};
console.log("Value: " + plain); // "Value: [object Object]"

Key Takeaway: When coercing objects to strings, JavaScript tries toString() first, then valueOf() as a fallback—the reverse of number coercion.