I am new to programming and am currently working in JavaScript. I am trying to put together a simulation of rolling dice using a for loop. The program works but output also outputs undefined after the generated number every time. I don’t know what is causing the undefined output.
I worked through a few of my bugs, but I was not expecting to see an undefined in my output.
**Below is my program: **
function rollDie () {
roll = Math.floor(Math.random () * 6) + 1;
return console.log (roll);
};
// use a for loop to emulate multiple dice being thrown.
let num = 4;
for (let i=1; i <= num; i++) {
console.log (rollDie());
};
Output I get is below:
6
undefined
6
undefined
2
undefined
4
undefined
2
Answers
You’re logging twice per roll: once inside the function, and once outside the function (in the for loop). The log inside the function is logging the number, but then you are returning
undefined
from the function. Since you returnedundefined
, the second log printsundefined
The problematic line is this one:
When you call
console.log
, it will print the value to the console, but then console.log returnsundefined
to you. You are then immediately returning thatundefined
fromrollDie
. Maybe it’s a bit clearer if you split it onto two lines, that you are not returningroll
:If you want to continue logging twice, i recommend the following:
If you just want to log once, you can delete the console.log from the function, meaning you just do:
Man you never return a console.log(), as a function return; If you want to double check a value – do console.log() inside the function and then return a value. The scope of variable
roll
is inside rollDie() function – how do you think you’ll be able to access it outside this function. Its value naturally will be undefined.