Help a poor noob - arrays

Hello there. I’m realy starting learning. I’m trying change the array I’m using but don’t work put the name in variable… How do i do?

var fase = stage1;

var stage1 = [
[‘0’, ‘1’, ‘0’, ‘1’],
[‘0’, ‘1’, ‘1’, ‘0’],
];
var stage2 = [
[‘0’, ‘1’, ‘1’, ‘1’],
[‘1’, ‘1’, ‘1’, ‘0’],
];

for (i = 0; i < fase.length; i++) {
for (j = 0; j < fase.length; j++) {
if (fase[j][i] === ‘0’) {
image(img, xPos + i * 40, yPos + j * 40, 40, 40);
}

Hi,

Welcome to the forum! :wink:

Your error comes from the fact that you are assigning stage1 to the variable fase before the variable stage1 has been initialized.

The computer reads your program from top to bottom but in JavaScript it doesn’t give you an error. You can refer to this previous thread on the subject :

This is what happens :

  1. The JavaScript engine parse your code. Because of hoisting, it moves the declaration of the stage1 variable so it’s doing :
var stage1; // Uninitialized -> undefined
  1. Then we declare and assign stage1 to fase which is undefined:
var fase = stage1; // -> undefined
  1. The stage1 variable gets initialized with the array :
var stage1 = [
  [‘0’, ‘1’, ‘0’, ‘1’],
  [‘0’, ‘1’, ‘1’, ‘0’],
];

But fase is still undefined!!

Check out this simple example :

var a = b;
console.log(a); // Prints undefined

var b = [0, 1];
console.log(a, b); // Prints undefined [0, 1]

So you need to assign stage1 to fase after stage1 has been initialized :yum:

thank you so much!! I’ll work on this!

I defined the varfase at setup and it works! Thanks

1 Like

You are welcome!

Also note that it’s preferred not to use var when declaring variables in JavaScript because it can give you some obscure errors and bugs…

Use let or const (when the variable won’t be re assigned)