Usage of toString in JavaScript [duplicate]

I'm reading through Douglas Crockford's JavaScript: The Good Parts, and I'm at the point where he defines a fade function. Part of this code boils down to this:

var level = 1;
var hex = level.toString(16);

So I run this in my browser's console to see what I get....

var level = 1;

Hey, it returns "1"... Fabuloso! Wunderbar!

Then to be cheeky, I try this to see what I get...


And I get

SyntaxError: Unexpected token ILLEGAL

What the what? If level is a variable equal to 1, and running this method on level works fine, then why doesn't running this method on the actual number 1 work? I tried a similar experiment with the toPrecision() method and that worked fine in both cases. What's the issue here? Is this another one of those inherent flaws in the JavaScript implementation, or am I missing something? I am testing in Google Chrome.

Related: Stack Overflow question Why don't number literals have access to Number methods?.



It's just a language grammar limitation.

Since 1. is a legal literal number (and 1.t is not) the tokeniser will split this into the following tokens:


And that's an illegal sequence of tokens. It's object method, instead of object . method.

In the working versions in @Joey's answer, the braces prevent the tokenizer from treating the dot as part of the number literal instead of as a separate token, as does writing:




since the tokenizer knows that the second dot must be a token on its own, and not part of the number literal.


You need 1..toString or (1).toString to get the number literal


level is a variable (and thus an object).

1 is a literal. They are not objects and the interpreter thinks about them completely differently.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.