Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of toString in JavaScript [duplicate]

Tags:

javascript

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;
level.toString(16);

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

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

1.toString(16);

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?.

like image 429
Bob Ralian Avatar asked Jul 28 '11 03:07

Bob Ralian


People also ask

What is the use of toString in JavaScript?

The toString() method returns a string as a string. The toString() method does not change the original string. The toString() method can be used to convert a string object into a string.

Why is toString needed?

In most languages, toString or the equivalent method just guarantees that an object can be represented textually. This is especially useful for logging, debugging, or any other circumstance where you need to be able to render any and every object you encounter as a string.

What is the difference between string () and toString () in JavaScript?

The String object overrides the toString() method of the Object object; it does not inherit Object. prototype. toString() . For String objects, the toString() method returns a string representation of the object and is the same as the String.

What is toString 2 JavaScript?

toString(); Convert a number to a string, using base 2 (binary): let num = 15; let text = num. toString(2);


1 Answers

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:

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:

1.0.toString()

or

1..toString()

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

like image 113
Alnitak Avatar answered Oct 13 '22 01:10

Alnitak