Javascript Mindf*k: toString()
Not everything is an object in JavaScript.
Many things that you interact with regularly (strings, numbers, booleans) are primitives, not objects. Unlike objects, primitive values are immutable.
The situation is complicated by the fact that these primitives do have object wrappers (String
, Number
and Boolean
); these objects have methods and properties while the primitives do not, but the primitives appear to have methods because JavaScript silently creates a wrapper object when code attempts to access any property of a primitive
BEHIND THE SCENES:
- Create a wrapper
String
object from'foo'
, equivalent to usingnew String('foo')
- Call the
substring()
method with the appropriate parameters on theString
object returned by step 1 - Dispose of the
String
object - Return the string (primitive) from step 2.
BUT WHY IS THIS NOT WORKING?
You might think “number” type isn’t wrapped like the other primitive types.
It’s a common misconception that number literals cannot be used as objects.
That is because of a flaw in JavaScript’s parser. It tries to parse the dot notation on a number as a floating-point literal.
HERE ARE A COUPLE OF WORKAROUNDS:
NOTE:
THIS IS NOT LIMITED TO toString().
toString() IS ONLY USED AS AN EXAMPLE
Connect with me on Linkedin for more interesting tech stuff!
Thank you very much for your attention.