skip to Main Content

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


  1. 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 returned undefined, the second log prints undefined

    The problematic line is this one:

    return console.log(roll)
    

    When you call console.log, it will print the value to the console, but then console.log returns undefined to you. You are then immediately returning that undefined from rollDie. Maybe it’s a bit clearer if you split it onto two lines, that you are not returning roll:

    const resultOfLog = console.log(roll);
    return resultOfLog; // resultOfLog is `undefined`
    

    If you want to continue logging twice, i recommend the following:

    console.log(roll);
    return roll;
    

    If you just want to log once, you can delete the console.log from the function, meaning you just do:

    return roll;
    
    Login or Signup to reply.
  2. 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.

    function rollDie () {
        roll = Math.floor(Math.random () * 6) + 1;  
        console.log (roll);
        return roll;  
    };
    
    // use a for loop to emulate multiple dice being thrown.
    
    let num = 4;
    for (let i=1; i <= num; i++) {
        console.log (rollDie());
    };
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search