Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript parentheses converts primitive type to object

Tags:

javascript

If numbers are primitive types, why I can do:

> (12345).toString()
"12345"

Is the parenthesis converting the primitive type to a Number?

like image 862
Freeman Avatar asked Apr 19 '12 09:04

Freeman


2 Answers

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.

like image 188
Dagg Nabbit Avatar answered Sep 30 '22 19:09

Dagg Nabbit


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…

like image 45
Marco Mariani Avatar answered Sep 30 '22 20:09

Marco Mariani