How is the 'random' variable accessed?

Before I move the ‘random’ variable from its current global scope to a local scope
How is the ‘random’ variable passed into the getRandEvent() ? the function is not defined for parameters and o arguments are passed into it when it is called, yet it generates a random event.

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";

};

That explains why it isn’t passed into the function… It can still be accessed.

To make it a local variable, declare it within the function. That entire statement can be moved into the function, before the if statement.

This is a better arrangement since it generates a new random value every time the function is called.

Yup. got it. I don’t think I saw this kind of scope / accessibility dynamic in Python and / or Java.
Is it unique to JS ?

Scope is an important concept in other languages, too. It is simply the environment where objects reside. A function is its own namespace. In ES2015 and later, blocks have their own scope.

When a variable is referenced inside a block inside a function but the variable is not there, JS looks UP the scope chain to see if it can be found in the next scope up. If it is not there, then JS keeps moving up the scope chain to the next parent scope. If it is not anywhere, then an error is thrown.

Note that the direction is always UP, never down. We cannot access objects in lower scopes. You’ll work with this a lot so give it time to settle and sink in.

Is the whole thing about a variable being used simply because it is in global scope unique to JS, I mean the fact that the global variable gets passed into a function as an argument even when the function has no parameters and no variable is passed in manually, it just uses the global variable whether you like it or not.

It doesn’t get passed in. The function can see it since it is a parent scope. The issue is that the value never changes. That is why we need to move that whole statement into the function so it is re-generated on every call.

Your’e right, the variable isn’t being passed in to the function, but the value stored in the variable is being used by the function.

1 Like

and most importantly, does not change. It is a static object that soon loses its value to the program. By defining the variable inside the function we make it dynamic.