Let/var behaviour inside function vs outside

Probably a dumb question, but in this example:

var angle = 0.0;
function setup() {
createCanvas(120, 120);
background(204);
}
function draw() {
translate(mouseX, mouseY);
rotate(angle);
rect(-15, -15, 30, 30);
angle += 0.1;
}

everything works fine, but as soon as I move the var angle = 0.0; inside function draw() the rectangle will not spin. Why is that?
Why only global variable? Do built in functions/objects like rotate require global variables?

Hi @ADG

I advise you to look for variables scope.

When you declare you variable inside draw() it only exists inside of it.
Also, keep in mind that draw is just a function that is called over and over during the execution of your program.
So when the program arrive at the end of your first call of draw(), it doesn’t need the variables created in it anymore and get rid of them.
During the second call, your variable angle is created again and thus, even if in your code it seems to be the same variable, it is not for the program.

3 Likes

Thank you @jb4x.

I think I understand. So because there isn’t a global variable to hold the change it gets discarded at the end of the loop is that correct? I’m sure I’ll get a better understanding once I read into variable scope.

That’s it.

When you enter a function, some space in memory is allocated to the variables defined in that function. When you exit that function, the memory allocated is freed allowing other program to use that part of the memory.

So in your, case, what is happening is:

  1. The draw() function is called
  2. A variable called angle is created and set to 0
  3. 0.1 is added to the variable angle that now holds 0.1
  4. The end of the function draw() is reached
  5. The memory is freed so angle does not exist anymore
  6. The draw() function is called for an (n+1)th time
  7. Go back to 2.

I hope it makes it clearer.

3 Likes