In JavaScript, a unique quirk exists due to the performance restriction where primitive types like string
, boolean
, and number
are immutable. This means that any property assignment made to these types will simply disappear. The exceptions are the single-inhabitant primitive types undefined
and null
, which will throw an exception when trying to assign a property. Despite being lightweight for the run-time as they are not real objects, this immutability feature is present in these primitive values.
However, there are wrapper types available for each primitive type: String
, Boolean
, and Number
. These wrapper types are actual objects and can have custom properties assigned to them.
Although unconventional, it is possible to assign custom properties to wrapper types, for example:
var s = new String("foo");
s.bar = "hello"
alert(s.bar)
Nevertheless, using wrapper types introduces several peculiar behaviors. For instance, typeof ""
will return "string", while typeof s
will return "object". Additionally, "" instanceof String
will be false, whereas s instanceof String
will be true. Notably, calling new Boolean(false)
surprisingly results in a truth-y value.
Happy coding!
*It's worth noting that this may disrupt libraries designed with assumptions such as typeof x === "string"
.