Russian roulette

Add thrill and excitement to your JavaScript with some Russian roulette. This helper calls a function you give it with a chance of 5 in 6. In the other case, it causes an infinite loop and crashes everything.

// takes a function and either calls it or crashes absolutely everything
const russianRoulette = fn => {
  // pick a random number from 0 to 5
  const randomNumber = Math.floor(Math.random() * 6)

  // crash the code with an infinite loop if the random number was 5
  while (randomNumber === 5) {}
  
  // call the function and return its result if the number wasn’t 5
  return fn()
}

// This logs the string with a chance of 5 in 6 (~83.3%). In the other case,
// everything crashes.
russianRoulette(() => console.log('You are lucky!'))

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.