First off, let's talk about why this works:
function setup(){
myVariable = 'hello';
}
function draw(){
console.log(myVariable);
}
Here, you're using the assignment operator to assign a value to a variable.
This works because when you hit the myVariable = 'hello';
line, JavaScript is going to look for a variable named myVariable
in enlarging scopes (first in the setup()
function, then in the global scope). When it doesn't find a variable with that name, it creates a new one in the global scope. More info on that here.
Now, let's talk about why this doesn't work:
function setup(){
myArray[0] = 'hello';
}
function draw(){
console.log(myArray[0]);
}
Here, you're using the index operator to index into an array named myArray
. However, that variable hasn't been created yet! You could create the array first:
function setup(){
myArray = [];
myArray[0] = 'hello';
}
function draw(){
console.log(myArray[0]);
}
This will work for the same reason your first code worked. The myArray = []
line first looks for a variable named myArray
, and then creates a new one when it can't find it.
However, all of the above is pretty hackish code, because it's relying on JavaScript to look through the various scopes. What if there's already a myVariable
variable? You're now overwriting the value, which can lead to buggy behavior. At the very least, this is an unintended side effect, so it should be avoided.
Instead, what you want to do is declare the variable yourself, using the var
keyword. Since you want to access the variable inside two functions, you'd want to do that outside of both functions, like this:
var myArray = [];
function setup(){
myArray[0] = 'hello';
}
function draw(){
console.log(myArray[0]);
}
Now this code creates a variable named myArray
and sets it equal to an empty array. Then you can use the index operator on it to set an individual index, and you can access it in multiple functions. And even better, if there is a conflict with another variable, you'll get an error warning you about that.