2

Is there a // operator in JavaScript?

Because in Python we have:

5 // 2.0 # => 2.0
5 / 2.0  # => 2.5

So I tried in JavaScript:

5.0//2.0 

and I got 5! What's going on there?

I read that there is no such a thing as a // operator in JavaScript. In this case, why didn't I get an exception or, better, an error from the lexer?

I used this line:

document.write(eval("5.0//2.0"));

In Firefox 3.6.23.

Michael
  • 7,248
  • 5
  • 56
  • 81
Yksin
  • 31
  • 1
  • 3
    As you might have seen by looking at the syntax highlighting, `// ..` are the markers of a comment in JavaScript. Also, if you need tips for your English, visit http://english.stackexchange.com/ – Rob W Nov 02 '11 at 17:48
  • 13
    This is the first time I've seen a question that is answered by its syntax highlighting. – SLaks Nov 02 '11 at 17:49
  • See [this question](http://stackoverflow.com/questions/4228356/integer-division-in-javascript) for integer division in JavaScript – Alex Turpin Nov 02 '11 at 17:54
  • 2
    I think Yksin was ashamed of coming back to SO after he saw what his mistake was. @Yksin: come back, choose an answer, we all make silly mistakes – Juan Mendes Nov 02 '11 at 18:03

4 Answers4

7

// is a comment in javascript.

Try:

   5 / 2; //yields 2.5
   Math.floor(5/2); //yields 2

Also do not use eval.

Just do document.write(5/2);

Antony Hatchkins
  • 28,884
  • 9
  • 105
  • 105
Naftali
  • 142,114
  • 39
  • 237
  • 299
2

In JavaScript, // is not an operator, it denotes a comment.

John Hartsock
  • 82,242
  • 22
  • 125
  • 144
1

// is used for commenting in JavaScript.

Fatih Acet
  • 27,197
  • 9
  • 50
  • 57
0

// starts a comment. To do integer division, first perform a regular division using / and then round it. This can be done with &-1, ^0, |0 or ~~, in order from fast to slow as measured on my laptop. There is a measurable difference between the first three but it's small. The last one is really slow in comparison.

Putting it all together, 5/2&-1 will yield 2. It rounds towards zero.