3

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.

4
  • 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 english.stackexchange.com
    – Rob W
    Nov 2, 2011 at 17:48
  • 14
    This is the first time I've seen a question that is answered by its syntax highlighting.
    – SLaks
    Nov 2, 2011 at 17:49
  • 1
    See this question for integer division in JavaScript Nov 2, 2011 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 Nov 2, 2011 at 18:03

5 Answers 5

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);

6
  • 2
    +1, only answer that mentions what // does and how to do integer division. Nov 2, 2011 at 17:55
  • what are extra parentheses for in the last line? Mar 12, 2012 at 16:27
  • @AntonyHatchkins whatever are you talking about?
    – Naftali
    Mar 12, 2012 at 17:18
  • @AntonyHatchkins that is perfectly fine ^_^
    – Naftali
    Mar 16, 2012 at 13:00
  • I've fixed it. Syntax of javascript is too clumsy in my opinion (eg +a to convert string to number) to use excess symbols in simple answers. Mar 16, 2012 at 13:48
2

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

1

// is used for commenting in JavaScript.

1

// 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.

0

You want to use ~~ 5/2 to get 2. NO need to download math. library

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.