tags:

views:

157

answers:

4
100['toString'] //does not fail
100.toString //fails

why?

100.toString is not same as 100.toString() . So why in the second case I am not getting the function as returned value?

+4  A: 

Use (100).toString instead.

Gumbo
+16  A: 

The second line fails because it is parsed as a number "100.", followed by "toString".

To use the dot notation, Any of the following will work:

(100).toString
100.0.toString
100..toString
var a = 100;
a.toString

If you are trying to call the toString function , you will also need to include the parentheses:

(100).toString()
100.0.toString()
100..toString()
var a = 100;
a.toString()

I prefer using parentheses (or a variable, if I already have one obviously), because the alternatives could be confusing and unintuitive.

Matthew Crumley
Another example: `100..toString()` works as well since the first period is counted as part of the number, and the second as part of the property access syntax.
Max Shawabkeh
Note that `100` and `100.0` are not the same.
Gumbo
@Max, good point. It looks kind of funny, but I'll add that too.
Matthew Crumley
@Gumbo, all numbers in JavaScript are floating point, so they are exactly the same.
Matthew Crumley
A: 

Parens is the best way to go. You've got the same issue w/ function definitions as well.

function () {}.call() => fails
(function () {}).call() => succeeds
KZ
A: 

Two more...

String(100);

100+='';

kennebec
`100+='';` is not legal javascript btw. `op=`'s only work for variables. You want `""+100`.
trinithis