Roll a Six
Grand finale: keep rolling a dice until you get a 6.
1const rollDice = () => Math.floor(Math.random() * 6) + 1;
2
3let roll = rollDice();
4while (roll !== 6) {
5 console.log(roll);
6 roll = rollDice();
7}
8console.log("You rolled a 6!");
$ node main.js
(prints a random number, different every run)
Every line, explained
const rollDice = () => Math.floor(Math.random() * 6) + 1;- This is an arrow function: a compact, very modern way to write a function, stored in a const like any other value. () => means "a function with no inputs", and whatever follows the arrow is returned automatically. The recipe inside: Math.random() gives a random decimal from 0 up to (but not including) 1; times 6 makes it 0 to 5.999…; Math.floor rounds DOWN to 0–5; plus 1 gives a dice roll from 1 to 6.
let roll = rollDice();- Calls rollDice and stores the number it returns: our first roll. It will change, so it gets let.
while (roll !== 6) {- A while loop repeats its block for as long as the condition in the brackets is true. The condition is checked again before every trip around the loop. !== means "not exactly equal" (the partner of ===): keep looping while the roll is NOT a 6.
console.log(roll);- console.log(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. console is the terminal itself, log is the tool that writes to it, joined with a dot. Shows each roll that wasn't a 6.
roll = rollDice();- Rolls again, replacing the old number. Then the loop checks the condition again.
}- This } closes the while loop.
console.log("You rolled a 6!");- console.log(...) prints whatever is inside the round brackets to the terminal, then moves to a new line. console is the terminal itself, log is the tool that writes to it, joined with a dot. Runs once, the moment a 6 finally appears. You just used variables, an arrow function, randomness and a loop. Real JavaScript!