-1

I'm referring to this question: Pick random property from a Javascript object

In the marked answer, the author is using the following code:

if (Math.random() < 1/++count)
       result = prop;

My questions:

  1. What exactly is the function of the slash?
  2. Is there a name for this syntax?

Thank you!

Community
  • 1
  • 1
SVSchmidt
  • 6,269
  • 2
  • 26
  • 37

2 Answers2

6

It's a division :) Here's a few more parentheses to show what's going on:

if (Math.random() < (1) / (++count) )
    result = prop; 

The ++count operator means "increment the value of count, save it as count, and then return it". count++ means "return the value of count, then increment and save it as count":

val count = 0
val b = ++count //increment count, then set b to count (so b=1, count=1)
val c = count++ // set c to count and then increment count (so c=1, count=2)
jkgeyti
  • 2,344
  • 18
  • 31
1

That is simple division. That is same as

var comparator = 1/++count;
if (Math.random() < comparator)
       result = prop;

Don't think / is doing some magic here.

Mritunjay
  • 25,338
  • 7
  • 55
  • 68