)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

30% Chance Math.random()

  1. // 30%
  2. if (Math.random() < .3) {
  3.   // 30% chance this will run
  4.   console.log('30%');
  5. } else {
  6.   console.log('nope');
  7. }

I do this all the time when creative coding. I usually use a seeded random number generator instead of Math.random. It’s very useful to have something happen X% of the time.

Let’s run this a few times and look at the results. Click/tap try it out.

  1. for (let i = 0; i < 111; i++) {
  2.   if (Math.random() < .3) {
  3.     console.log('30%');
  4.   } else {
  5.     console.log('nope');
  6.   }
  7. }

Scroll through the results of the console window.

snippet.zone ~ 2021-24 /// {s/z}