Why doesn't JavaScript let you call methods on numbers directly? [duplicate]

In Ruby, you can do this:

3.times { print "Ho! " } # => Ho! Ho! Ho!

I tried to do it in JavaScript:

Number.prototype.times = function(fn) {
    for (var i = 0; i < this; i++) {
        fn();
    }
}

This works:

(3).times(function() { console.log("hi"); });

This doesn't

3.times(function() { console.log("hi"); });

Chrome gives me a syntax error: "Unexpected token ILLEGAL". Why?


The . after the digits represents the decimal point of the number, you'll have to use another one to access a property or method.

3..times(function() { console.log("hi"); });

This is only necessary for decimal literals. For octal and hexadecimal literals you'd use only one ..

03.times(function() { console.log("hi"); });//octal
0x3.times(function() { console.log("hi"); });//hexadecimal

Also exponential

3e0.times(function() { console.log("hi"); });

You can also use a space since a space in a number is invalid and then there is no ambiguity.

3 .times(function() { console.log("hi"); });

Although as stated by wxactly in the comments a minifier would remove the space causing the above syntax error.