I just wanted a simple dice roll

let diceArray = [1, 2, 3, 4, 5, 6];

function diceRoll(diceArray) {
  result = diceArray[Math.floor(Math.random() * diceArray.length)];
  return result;
}

if (console.log(diceRoll) == [1, 2, 3]) {
  console.log("Better luck next time!");
} else {
  console.log("Wowza!")
}

Hello! I was wondering what went wrong in this snippet? This is my first time trying to build something simple on my own, and I was wondering what went wrong. I tested in in code pen and it doesn’t show anything. Is it because it’s bare JavaScript and won’t show unless attached to HTML? I’m just overall very confused.

Not sure what you mean by show, but if you mean on the page then yes nothing in your code would add anything to the DOM (the page).

Also, this console.log(diceRoll) == [1, 2, 3] won’t work.

  1. diceRoll is a function definition, if you want to use it’s return value you have to invoke it (call it using (), i.e. diceRoll())

  2. Don’t wrap the function in a console.log call if you want to use the function return value.

function one() {
  return 1;
}

if(console.log(one()) === 1) {
  console.log('true'); // nothing get logged
}

if(one() === 1) {
  console.log('true'); // true
}
  1. Just so you know, this will not work [1,2,3] === [1,2,3] <- is false. You can’t compare arrays like.

Okay, so I took your advice and looked around, and ended with this…but it still doesn’t output anything…I’m sorry if these are stupid questions. I’m really trying to understand.

<DOCTYPE! html>
<html>
<body>
  <script>
let diceArray = [1, 2, 3, 4, 5, 6];
function diceRoll() {
  result = diceArray[Math.floor(Math.random() * diceArray.length)];
 if (diceRoll() == diceArray.slice(1, 2, 3)) {
  return result + "Better luck next time!";
} else {
  return result + "Wowza!";
}}
diceRoll();
    document.getElementById("roll").value
  </script>
  <div id="roll"></div>
  </body>
  </html>

Let’s look at just your JavaScript:

RangeError: Maximum call stack size exceeded often means that you created an infinite recursion. Can you see where you did that? Your logical condition doesn’t do anything like what you think it does.

1 Like

Thank you so much!!
I put way too many returns on result!
Here’s my new code, fully improved:

function diceRoll() {
  const diceArray = [1, 2, 3, 4, 5, 6];
  result = diceArray[Math.floor(Math.random() * diceArray.length)];
 if (result <= 3) {
 	var failure = "Better luck next time! "
  result = failure + result;
 } else {
 	var success = "Wowza! "
  result = success + result;
 }
 return result;
}
console.log(diceRoll());

I’ll leave learning how to have this output into my DOM for later though, haha! Thank you again, that was super helpful.

repl.it is pretty great. I’m happy to have helped.

1 Like