Although the distinction is often not apparent because of automatic type conversion, JavaScript supports a number of primitive types as well as objects:
var foo = 10;
var bar = new Number(10);
alert(foo.toString(16)); // foo is automatically wrapped in an object of type Number
// and that object's toString method is invoked
alert(bar.toString(16)); // bar is already an object of type Number,
// so no type conversion is necessary before
// invoking its toString method
var foo2 = "foo";
var bar2 = new String("foo");
alert(typeof foo2); // "string" - note the lowercase "s", not a String object
alert(typeof bar2); // "object"
alert(typeof true) // "boolean"
alert(typeof new Boolean(true)) // "object"
and something that really confuses the issue:
// the next line will alert "truthy"
alert("Boolean object with value 'false'" + (new Boolean(false) ? " is truthy" : " is falsy"));
// the next line will alert "falsy"
alert("boolean primitive with value 'false'" + (false ? " is truthy" : " is falsy"));
Although relying on automatic type conversion makes life a little easier, one should always have at the back of one's mind a good understanding of what types your primitive values and objects actually are; a surprisingly large number of JS bugs come about because of people failing to realise that, for example, something which looks like a number is actually a string, or that some operation they have carried out has resulted in something that used to contain a number having been assigned a new value that is a string, or an object.
EDIT: to more closely address the original question, which I now realise I hadn't answered explicitly: 10.foo()
will cause a syntax error as the .
is seen as a decimal point, and foo()
isn't a valid sequence of characters to be parsed as a number. (10).foo()
will work as the enclosing brackets (10)
make the entire construct before the .
into a single expression. This expression is evaluated and returns the primitive number value 10
. Then the .
is seen as treating that primitive value in an object context, so it is automatically wrapped in an object of type Number
(this is the automatic type conversion in action). Then the foo
property of that object, found on its prototype chain, is referenced; and the final ()
cause that property to be treated as a function reference and invoked in the 'this' context of the Number object that was wrapped around the primitive value at the point of encountering the .
.