So what you’re doing is, you’re confusing the global and local namespaces.
When we run script right in the console window, or we write script that executes without being in a function, we’re working in the context (or namespace) of the window
object, the container javascript uses for everything. Any variable created is created somewhere within that space.
BUT, you won’t see them all in the window
. Why not? Because that would very quickly get all clutter-y. Different developers and packages and frameworks and libraries would all likely crash, sharing variable names and stuff. Ugly and messy. Fortunately, while I say that all variables are in that space, some are nested. What do I mean by that?
If we write a function, let’s call it countdown()
just for fun, there is something that happens when that function is executed. It creates its own little variable name ‘sandbox’. Its own namespace. The function countdown
exists in the window
namespace, sure - but any variables defined within countdown
can’t be seen outside that sandbox.
It’s weird, because anything inside countdown
can see all the namespaces of those containing elements, but not the other way around.
Why does this matter? Because, when you create your countdown
function, like so:
function countdown(myArray, n){
//
}
you have created a namespace, a private sandbox for your variables within that function, and created two new variables inside that sandbox! Yup. You created myArray
and n
in that local space. BUT!! Those are totally different from any variables of the same name outside that sandbox.
So, when you write countdown(myArray, 5);
, you’re trying to run the function in the window
or the global namespace, but you haven’t defined a variable myArray
in the window’s collection of variables.
You don’t NEED to pass in a defined variable named myArray
- it’s simply telling the javascript engine "hey, when you get inside my function, that first parameter? I want to refer to it locally by the name myArray
.
So you could do
// Both of these do the same thing...
const emptyArrayOfEmptiness = [];
const anotherEmptyArray = new Array(0);
// While we call it emptyArrayOfEmptiness HERE, inside the function it's myArray
console.log(countdown(emptyArrayOfEmptiness, 10) );
// Same same
console.log(JSON.stringify(countdown(anotherEmptyArray, 25) ) );
// or even this - we pass in an empty array literal, and our myFullArray will hold
// the return value from countdown which will be a FULL array.
const myFullArray = countdown([], 100);
But in each case, we aren’t referring to a global myArray
, we are referring to the local variable of that name. So the name we use to pass the variable in? Doesn’t matter.
… and I apologize in advance for my wordiness. I don’t really tend to self-edit. 