Review Algorithmic Thinking by Building a Dice Game - Step 3

Tell us what’s happening:

I’m trying to use a loop here to add a random number to the array 5 times, but the hint says that the array should contain 5 elements so something is wrong. Can someone help me identify what it is?

Your code so far

<!-- file: index.html -->

/* file: styles.css */

/* file: script.js */
// User Editable Region

  rollDiceBtn.addEventListener('click', () => {
    for (let i = 0; i < 6; i++) {
      let num = Math.floor(Math.random() * 6);
      diceValuesArr.push(num);
      listOfAllDice.innerText = num
    }
  })

// User Editable Region

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36

Challenge Information:

Review Algorithmic Thinking by Building a Dice Game - Step 3

Try adding console.log at the end of callback, to print contents of the diceValuesArr. See if that clears anything up.

Hey it looks like your for loop is close, the main issue is you need a function first then the click event to follow with that function name by calling it. In other words try to write a function with your for loop then the click event.

I’ve tried it and it looks like way more than 6 iterations of my array is being printed. I don’t understand why this is happening if I only set the loop to repeat 5 times.

I’ve refactored my code to this, and while this has fixed the issue of my array being iterated over more than 5 times, it still doesn’t pass the tests.

function fiveRandom(arr) {
    arr.length = 0;
    for (let i = 0; i < 5; i++) {
      let num = Math.floor(Math.random() * 6) + 1;
      arr.push(num);
  }
  console.log(arr)
  }
  
  rollDiceBtn.addEventListener('click', fiveRandom(diceValuesArr))

You cannot trigger an event handler like this.

The event listener function is expecting a callback function in the second parameter. You are passing the result of calling fiveRandom(diceValuesArr) which is undefined.

You must remove the calling parenthesis and just reference the name of the function.
If the function needs diceValuesArray, it is a global variable so you can use it directly.

Using your function name directly fiveRandom for the click event works, the function itself still needs work. the arr should be removed all together and replaced with the array name and assigning an empty [] instead of 0. Also you still need more function logic where the console.log()is it is going to use the array name with forEach as well. Looking at the instructions: rollDiceBtn, diceValuesArr and listOfAllDice all need to be included here.

listOfAllDice.forEach((arg1, arg2) =>{})