var numOfIs = "Odin".match(/i/).length; // Outputs: 1 console.log(numOfIs); var strOfTrue = true.toString(); // Outputs: "true" console.log(strOfTrue);
Here we see two examples. First, the primitive string
"Odin" lets us treat it as if it were an object by accessing the
match method. Second, the primitive boolean value
true lets us treat it as if it were an object by accessing the
However, if we try to do the same thing with a number, we are likely to run into an error.
// SyntaxError: Unexpected token ILLEGAL var meaningOfLife = 42.toString();
var meaningOfLife = 42["toString"](); // Outputs: "42" console.log(meaningOfLife);
That works, but it's not especially nice. And it turns out that dot notation does work with some numbers.
var platform = 9.75.toString(); // Outputs: "9.75" console.log(platform);
Why does dot notation work with
9.75 but not with
In the case of
42.toString(), it raises a SyntaxError.
In the case of
9.75.toString() the first dot was unambiguously part of a floating point number, and the second dot was unambiguously object member access.
So the way to avoid problems with integers like
42 is to make sure that the parser can't mistake your dot notation for a decimal point. There are at least three ways to do that.
var meaningOfLife = 42..toString();
The double-dot approach above is syntactically equivalent to typing
var meaningOfLife = 42 .toString();
This one is confusing at first glance. There is only one dot here, so how is it working as member access? The difference is the space between
var meaningOfLife = (42).toString();
Having looked at the examples above, you'll understand why this one works. The parentheses ensure that the parser doesn't get confused. This is also by far my favorite approach for use in production code. It is highly readable, and the use of parentheses clearly communicates that
toString is being called on the value of
That's it for this week. Thanks for reading!