Object disappears between Setup() and Draw()?

I’m a little perplexed. Is there anything that happens between Setup() and Draw() in the sketch?

This is my 20th or so ‘mover’ based project. No arrays on this one, but a basic Mover class (position, velocity, radius, etc).
In the code below: the first call to console.log(mover) in Setup(); shows me all the created object’s details in the console - like you would expect. It is a valid object with parameters, etc.
The second call to console.log(mover) comes back as undefined.
How could I have lost my mover object between Setup() and Draw().

I have done a variation where the class declaration is on the script.js page along with Setup() and Draw(). Same thing happens - I have an object in Setup() which is gone missing by Draw(). How could I have lost the mover object between Setup() and Draw().

Thanks, Paul

let mover;

function setup() {
  createCanvas(400, 400);
  let mover = new Mover(200, 200);
  console.log(mover);
}

function draw() {
  background(50);
  console.log(mover);
}

Hello, @pbissell, and welcome to the Processing Forum!

You have this in your setup() function definition:

  let mover = new Mover(200, 200);

With let, it defines mover as local variable in the function. Outside the function, mover refers to a global variable by that name that you declared prior to the setup() function. Though it was declared, it was not initialized with an object.

Inside draw(), you access the undefined global variable.

Edited on June 25, 2021 to clarify the explanation.

2 Likes

And to easily rectify, just delete the “let” inside setup so that line reads:
mover = new Mover(200, 200);
:nerd_face:

2 Likes

OMG. Thank you so much. I double Let!

Wow. Thank you so much. I double Let and couldn’t see it. Thank you!

1 Like

See p5.js: Variable Scope.

It is OK to have global and local variables with the same name, so long as you are careful. For example, you might write a function with many lines of code and some local variables. Make sure those variables are declared properly within the function, using let. Then, if you decide later on to use the function within a longer script, you will not need to be concerned about whether that script contains global variables with the same names as the local variables within the function.