Search code examples
javascriptfunctionfor-loopoutputundefined

for loop calling a function; output works but also shows undefined


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

Solution

  • 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());
    };