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; level.toString(16);
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
Related: Stack Overflow question Why don't number literals have access to Number methods?.
It's just a language grammar limitation.
1. is a legal literal number (and
1.t is not) the tokeniser will split this into the following tokens:
1. toString ( )
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.
©2020 All rights reserved.