13

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?

Alex Coplan
  • 13,211
  • 19
  • 77
  • 138

1 Answers1

37

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.

Musa
  • 96,336
  • 17
  • 118
  • 137
  • Ah, thanks. Interesting that it can also represent a decimal point in Ruby but it still works. – Alex Coplan Sep 04 '12 at 23:21
  • 5
    I go against doing 2 dots since it is very likely to create confusion for the reader. Parantheses are more self descriptive. – Umur Kontacı Sep 04 '12 at 23:27
  • 3
    @AlexCoplan I'm guessing because Ruby has integer and float types, but JavaScript just has Number – Musa Sep 04 '12 at 23:30
  • 2
    The last example utilizing a space is interesting to know, but unsafe to rely on... When you run that code through a minifier, BAM your syntax error shows up again. – wxactly Dec 29 '13 at 21:05