JS Dot literals

2009-11-20

There are subtle things about Javascript one usually misses out on. I like these things so try to investigate whenever I see one.

This particular one had to do with casting a number literal to it's "parent" object and apply a method through the dot operator. Observe:

Code: (JS)
100.toString();

This fails...

Code: (JS)
(100).toString();

This returns "100". Now let me give you a hint...

Code: (JS)
100.0.toString();

This will return "100" again. Got the clue?

The javascript parser is parsing a number. Numbers can have dots in them. Dots have multiple usages. In this case, the parser is parsing a number so it assumes that a dot is the decimal separator of the number. It doesn't backtrack when an error occurs to check for disambiguation, it just throws the error. When applying the decimal separator first and dot notation later, the second dot is parsed as the dot operator because it's not expecting another decimal seperator. :)

Probably won't help you, but I like these small facts :)