If numbers are primitive types, why I can do:
> (12345).toString()
"12345"
Is the parenthesis converting the primitive type to a Number
?
If numbers are primitive types, why I can do:
> (12345).toString()
"12345"
Is the parenthesis converting the primitive type to a Number
?
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.
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…