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.
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.
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.