I have finally started to understand classes and arrays (somewhat)! In the link I provided, I was trying to make at least 10 boxes with random colors in specific locations. So far, I think they are all showing, but I am lost on what I need to do for each box to be visible. Do I need to add another line of code, or is what I currently have just organized incorrectly? Thank you!!

(I appreciate how helpful everyone is in this community)

1 Like
class Max {
  constructor(x, y, d=100) {
    this.d = abs(d);
    this.x = typeof x == 'number'? abs(x) : random(width  - this.d);
    this.y = typeof y == 'number'? abs(y) : random(height - this.d);
    this.c = color('#' + hex(~~random(0x1000), 3));
  display() {
    fill(this.c).square(this.x, this.y, this.d);
1 Like

Hey there Van. You’re close, just a few lines you have to adjust.

In the setup you’re creating 10 instances of the class Max by using a for loop. The problem is that all of these get placed on top of each other, because they all get the x & y values of 100 inside the class’ constructor. You could solve this by initialising random values to x and y within the constructor (as GoToLoop shows in his code).

Another solution is to generate random numbers within setup (where you generate the instances) and pass these to the class. The video Constructor Arguments with Classes in JavaScript by Daniel shows how this is done. I think it’s fruitful to understand this approach if you want to get a basic understanding of classes.

Hope that helps!


Thanks for sharing! What does the “typeof” and “abs” represent in this situation?

abs() ->
Just a safeguard for some remote chance negative values are passed to Max’s constructor. :safety_vest:


It checks out whether numbers were passed and stores those values as property coordinates x & y. :1234:

In case those aren’t numbers (or even when nothing is passed like you actually do -> max[i] = new Max();), random values are chosen for coordinates x & y within the canvas’ width & height: :nerd_face:

this.x = typeof x == 'number'? abs(x) : random(width  - this.d);
this.y = typeof y == 'number'? abs(y) : random(height - this.d);

Also take a look at the conditional operator ?: in order to fully understand the 2 statements above: :grey_question: