Javascript Mindf*k: toString()

Chedy
Nerd For Tech
Published in
2 min readFeb 15, 2021

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:

  1. Create a wrapper String object from 'foo', equivalent to using new String('foo')
  2. Call the substring() method with the appropriate parameters on the String object returned by step 1
  3. Dispose of the String object
  4. 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.

--

--

Chedy
Nerd For Tech

Backend Developer in Pursuit of Happiness | Entrepreneur in the making