Why do math random function declared in the global scope gives same value to the function that calls it?

Hi,
I am in this exercise and I am confused as to why it says here in the instruction to do this:

When the math random function is declared inside the function, it gives different values when called. But when declared on the global scope, it gives the same value when called. Why is that?

Thank you in advance!

I… can see your confusion. This isn’t so much a problem of scope as declaration and storage.

// The result of Math.floor(Math.random() * 3) is stored in variable random
const random = Math.floor(Math.random() * 3);

// once random is stored, it aint going to change.
// you can create a function that uses the value random
// but the value random still won't chnage
const showRand = () => {
    console.log("you rolled", random);
};

showRand();
showRand(); // same result as first call

Instead:

const showRand = () => {
    // function is called
    // The result of Math.floor(Math.random() * 3) is stored in variable random
    const random = Math.floor(Math.random() * 3);
    // now, to be clear, the Math.floor(Math.random() * 3) will be called again
    // every time showRand is called
    // so this can change
    console.log("you rolled", random);
};

showRand();
showRand(); // possible different result

Or, perhaps more simply:

const random = Math.random(); // result stored

const showRand = () => {
    console.log("stored", random, "fresh call", Math.random());
};

showRand();
showRand(); // possible different result
2 Likes

Thank you so much! I see now that when put in the global scope, the stored result won’t change and when put inside a function or local scope, results may change whenever the function is called.

The third example really helped differentiate the two. :smiley: