How JavaScript Handles Type Conversion and Wrapper Objects Internally
JavaScript offers three explicit conversion functions — Number(), String(), and Boolean() — that return primitive values, while their constructor counterparts (new Number(), new Boolean(), etc.) return objects instead. This distinction matters in practice: a Boolean object wrapping a false value still evaluates as truthy, since all objects are treated as truthy by the engine. During implicit type coercion, the JavaScript engine uses a 'hint' derived from context to decide whether to apply valueOf() or toString() when converting an object to a primitive. If valueOf() does not return a primitive, the engine falls back to toString(), and if neither works, a TypeError is thrown. Special cases exist for Dates, which default to string conversion, and for Boolean checks, which simply return true for any object regardless of its wrapped value.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in