JS Built-ins
← String189 / 195
StringString.prototype.valueOfbeginner

String.prototype.valueOf() β€” in arithmetic context

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

Use valueOf() to return the primitive string value, useful when working with String wrapper objects.

String.prototype.valueOf() β€” Arithmetic

JavaScript calls valueOf() implicitly when an object is used in an arithmetic expression.

Challenge: Implement strLength(str) that returns the number of characters using valueOf().

strLength('hello') // β†’ 5
πŸ’‘ Hints (1)
  • β€’ `str.valueOf()` returns the string itself, so `.valueOf().length` is the same as `.length`.