JS Built-ins
← String157 / 195
StringString.prototype.toStringintermediate

String.prototype.toString() β€” String object vs primitive

πŸ“– Usage Example
const str = 'Hello'
str.toString()              // β†’ 'Hello'
new String('hi').toString()  // β†’ 'hi'

Use toString() to return the primitive string value of a string or String object.

String.prototype.toString() β€” String Object

A String object created with new String("hello") is not strictly equal to the primitive "hello", but .toString() returns the primitive value.

Challenge: Implement getPrimitive(strObj) that extracts the primitive string from a String object.

getPrimitive(new String('hello')) // β†’ 'hello'
πŸ’‘ Hints (2)
  • β€’ `new String("hello") !== "hello"` β€” it is an object, not a primitive.
  • β€’ `.toString()` unwraps the object back to a primitive string.