How is the 'random' variable accessed?

Before I move the ‘random’ variable from its current global scope to a local scope, how is it being passed into the 'getRandEvent() ? that function is defined with no parameters and when it is called no arguments are passed into it. yet when the code is run, the function does return a random event.

Here is the code:

const random = Math.floor(Math.random() * 3);

const getRandEvent = () => {

    if (random === 0) {

        return "Marathon";
    } else if (random === 1) {                                                 

        return "Triathlon";
    } else if (random === 2) {

        return "Pentathlon";

    return "Error";


Hey @paulgureghian1, from what I see in your code, random is a global scope variable and that is exactly the very reason why it’s accessible inside your getRandEvent method. A variable does not necessarily need to be passed into a method as an argument to be accessible inside that method. If a variable has global scope, it will be accessible inside any other method of the same scope block.

That’s what I was thinking was the case. I don’t think I saw this kind of scoping in Python.
Is it unique to JS ? in Python the scope determined whether something was accessible or not, but it still had to be passed in. it might have also been in Java.

Well Python is definitely not my thing but I do have some background in Java. So, in Java you have the access modifiers for the instance variables, also called global variables, but these modifiers only make sense outside of the class scope because no matter what modifier you give to an instance variable, it will still be accessible anywhere inside of that class. Java does have local variables too and as far as I know, they work exactly the same way in JavaScript. Basically, local means inside of a method, a loop block, try/catch block etc and global means outside of all that. :wink:

The access modifier thing sounds familiar, I used Java a few years ago for Android.
I think in Python there are no modifiers but placement in the code determines accessibility, but they still have to be accessed programmatically .

1 Like