Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 359
Alex Coplan Avatar asked Sep 04 '12 23:09

Alex Coplan


People also ask

Can you call a function multiple times in JavaScript?

In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.

Is JavaScript number a double?

The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value, like double in Java or C#. This means it can represent fractional values, but there are some limits to the stored number's magnitude and precision.


1 Answers

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.

like image 156
Musa Avatar answered Oct 30 '22 09:10

Musa