6

If numbers are primitive types, why I can do:

> (12345).toString()
"12345"

Is the parenthesis converting the primitive type to a Number?

Freeman
  • 5,810
  • 3
  • 47
  • 48
  • I asked a [somewhat related question](http://stackoverflow.com/questions/8581874/why-are-methods-of-string-prototype-available-to-string-literals) a while ago (about why it's possible to call string methods on a string literals). The answers may be of interest to you. – James Allardice Apr 19 '12 at 09:54
  • possible duplicate of [Why don't number literals have access to Number methods?](http://stackoverflow.com/questions/4046342/why-dont-number-literals-have-access-to-number-methods) – Alex K. Apr 19 '12 at 09:54
  • 2
    Whenever you try to use methods on a primitive JavaScript silently converts the primitive to an object with the same value and calls it for you. This is expensive. Hence if you want to use a value as an object it's generally a good idea to manually create an object rather than have JavaScript create a new object for you every time you call a method on a primitive. – Aadit M Shah Apr 19 '12 at 09:55

2 Answers2

11

No, the parentheses are just letting the parser understand that the . is not a decimal point.

12345 .toString() will also work.

Primitive numbers implicitly converted to Numbers whenever you access their properties, but the objects are temporary and immediately lost. For example:

var foo = 5;

foo.bar = "something";

console.log(foo.bar); // undefined

Same goes for strings and booleans.

Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141
4

Actually, 1 .toString() works as well.

>>> typeof(Number(1)) === typeof(1)
true
>>> var a=1; a.toString()
"1"

It's the parser: 1.x expects x to be a digit.

>>> 1.toString()
SyntaxError: identifier starts immediately after numeric literal
[Break On This Error]   

You can find further explanation here

If primitives have no properties, why does "abc".length return a value?

Because JavaScript will readily coerce between primitives and objects. In this case the string value is coerced to a string object in order to access the property length. The string object is only used for a fraction of second after which it is sacrificed to the Gods of garbage collection – but in the spirit of the TV discovery shows, we will trap the elusive creature and preserve it for further analysis…

Marco Mariani
  • 13,556
  • 6
  • 39
  • 55