0

Why I could not declare variable in setup and it still work and fine?

Where I could skip declaration, what is negative part of that skiping? - Main question

Here is example of code without declaration and it work fine:

   function setup(){
     canvas = createCanvas(innerWidth, innerHeight);
   }
   function mouseClicked(){
      canvas.style('margin-top', '5px');
   }

Here is same code with declaration how should it be:

   let canvas;
   function setup(){
     canvas = createCanvas(innerWidth, innerHeight);
   }
   function mouseClicked(){
      canvas.style('margin-top', '5px');
   }

and I have also code in console that shows as it should be and I understand why it is so : declaration variables in console

It is working on any of DOM element (not only canvas)

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107

1 Answers1

0

This is a JavaScript thing. See here for more info:

Basically, if you don't use var or let or const, then the variable is put in the global scope. In this case it doesn't really matter, since you're putting the variables in the global scope no matter what.

But it's a good idea to always use var or let or const to declare a variable, even if you don't technically need it.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107