Variable not found

I have a problem with my code. At line 105, it doesn’t find p1 and I don’t know why, so can you help me please?
Here’s the link:

You’re declaring your p1 variable inside the setup() function, so it’s only in scope inside the setup() function. Try to put together a simpler example:

function setup(){
  let x = 'hello';

function draw(){
  console.log(x); // won't work

If you want to reference a variable in multiple functions, you need to declare your variable outside of the functions:

let x;

function setup(){
  x = 'hello';

function draw(){
function setup () {
  let p1 = new Player ('z', 's', 50, 1);
  let p2 = new Player ('p', 'm', 425, 2);

Variables declared inside a function cease to exist when that function quits. :skull_and_crossbones:

Unless they become a closure to another inner function. :money_mouth_face:

Thanks, I totally forgot that.

if you declare the variable without the datatype/var/let thing it will be globally scoped
extremely useful for declaring within setup():

function setup(){
  p1 = new Player (loremipsum);
  p2 = new Player (loremipsum);


However, if "strict mode"; is active, accessing undeclared variables throws an exception: :scream:

Assignments, which would accidentally create global variables, instead throw an error in strict mode:

'use strict';
                       // Assuming a global variable mistypedVariable exists
mistypeVariable = 17;  // this line throws a ReferenceError due to the 
                       // misspelling of variable
1 Like