Why can't I call methods directly on a number in JavaScript?

Question:

A simple question, but it's making me curious.

I know that in javascript everything is warped in some object constructor, so I can call methods on strings even though the string is not an object in theory. So when I do:

"Hello World".split(' ');

I'm calling the split() method inside the String object from javascript.

My question is: why are numbers not equally 'warped'? I say:

2.toString(); // não funciona

var dois = 2;
dois.toString; // '2'

Why this behavior?

@edit

I noticed that some methods can be called directly on numbers, such as toFixed() which makes me even more curious. toString() doesn't work because it inherits from Object ?

Answer:

Yes you can! The problem is just the syntax of your test.

Realize that with just a small adjustment, it works:

console.log( (2).toString() );

What happens is that the interpreter will not understand the period followed by alphanumeric characters, as it is already used to separate decimals. By adding something that de-characterizes this usage (in the example, the parentheses), the interpreter no longer has problems with the dot.

In the case of .split() it won't work anymore, but it's because the method doesn't exist for numbers:

console.log( (432).split('') ); // Dá erro

But… check this out – converting to string, split works:

console.log( (432).toString().split('') );

Parentheses were an example, see other unambiguous situations:

 console.log( 432 .toString().split('') ); console.log( 789.0.toString().split('') ); // o segundo ponto não dá confusao

(the example with space was suggested by colleague @jsbueno in the comments)

Scroll to Top