# Trying to get a better understanding of array loops

**URL:** <https://discourse.processing.org/t/trying-to-get-a-better-understanding-of-array-loops/32779>\
**Category:** Beginners\
**Created:** [October 12, 2021, 2:37pm UTC](https://discourse.processing.org/t/trying-to-get-a-better-understanding-of-array-loops/32779 "2021-10-12T14:37:14Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![ADG](https://avatars.discourse-cdn.com/v4/letter/a/f0a364/32.png) [@ADG](https://discourse.processing.org/u/ADG)\
**Post date:** [October 12, 2021, 2:37pm UTC](https://discourse.processing.org/t/trying-to-get-a-better-understanding-of-array-loops/32779/1 "2021-10-12T14:37:15Z")

</div>

Hi, I’m trying to get a better understanding of arrays at a basic level before I advance to using them with functions & classes, but I am struggling a little.

I wrote this:

```auto
let r;
let g;
let b;

let x;
let y;
let w;
let h;

let max = 60;
let colourB;
let colourC;
let rgb;
let s;

function setup() {
  frameRate(60);
  createCanvas(windowWidth, windowHeight);
  r = floor(random(40, 100));
  g = floor(random(40, 255));
  b = floor(random(40, 255));

  x = mouseX;
  y = mouseY;
  s = random(15, 25);
}

let history = [];
let points = [];

function draw() {
  r = floor(random(40, 100));
  g = floor(random(40, 255));
  b = floor(random(40, 255));
  background(150, 150, 150);

  fill(r, g, b);
  stroke(0);
  max = 10;
  x = mouseX;
  y = mouseY;
  s = random(15, 25);
  for (let i = 0; i < max; i++) {
    points.push(i);
    if (mouseIsPressed) {

      [i] = circle(x, y, s);
    }

  }
}

```

This only creates one circle, before giving the error `Uncaught TypeError: undefined is not a function in Line 50 / Column 11`

Why does this loop break?  
Can you give me any tips for writing loops with arrays, or maybe some rules of thumb when writing loops with arrays? I’m trying to get my loops to work before incorporating them into functions and classes.

Thank you.

---

<div class="post-metadata">

**Author:** ![micuat](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/micuat/32/19407_2.png) [@micuat](https://discourse.processing.org/u/micuat)\
**Post date:** [October 12, 2021, 5:41pm UTC](https://discourse.processing.org/t/trying-to-get-a-better-understanding-of-array-loops/32779/2 "2021-10-12T17:41:25Z")

</div>

hi! I think this line is a very specific syntax in recent Javascript (ES6)

```auto
      [i] = circle(x, y, s);

```

this means you unpack the array returned from `circle` and assign to `i`. For example, if circle were to return an array like `[1, 2, 3]`, then `i` becomes 1

```auto
let [i] = [1, 2, 3]
console.log(i) // outputs 1

```

But I guess that’s not what you need here… (`circle` does return an object but not an array, and you rarely need this object) If you can share with us what you want to achieve with the code, perhaps we can give a better suggestion.

By the way,

```auto
  points.push(i);

```

will keep adding elements to the array every frame. So after some time, it will blow up 🤯 You need to empty the array once in a while (e.g., `points = []`) but again this is up to what you want to do.

What you can do with iteration is, for example

- draw several shapes next to each other
- draw a star
- draw the trace of the mouse

and more.

[![](https://img.youtube.com/vi/cnRD9o6odjk/maxresdefault.jpg "4.1: while and for Loops - p5.js tutorial") ](https://www.youtube.com/watch?v=cnRD9o6odjk)

---

<div class="post-metadata">

**Author:** ![ADG](https://avatars.discourse-cdn.com/v4/letter/a/f0a364/32.png) [@ADG](https://discourse.processing.org/u/ADG)\
**Post date:** [October 12, 2021, 6:08pm UTC](https://discourse.processing.org/t/trying-to-get-a-better-understanding-of-array-loops/32779/3 "2021-10-12T18:08:41Z")

</div>

Hi @micuat,

I’m just trying to build my intuition with array loops at a very basic level without additional functions, & classes.

For me, once I have a good understanding of array loops at a basic level, incorporating loops in functions, and classes of various complexity should be easier.

This is probably not the best way but what I’m trying to do is make a different coloured circle at each mouse click up to a maximum number. `max = 10;`

Another constraint is that `background()` is called in `function draw()` and not in `function setup()`

in terms of the shape, using `ellipse(x,y,s,s)` would give me the same result.

I assumed that I need an array to hold the number of ellipse objects, that will go up by one on each mouse click to a max of 10.

but because I’m not that good with arrays yet, I’m writing it out incorrectly, and I’m trying to find out why.

---

<div class="post-metadata">

**Author:** ![micuat](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/micuat/32/19407_2.png) [@micuat](https://discourse.processing.org/u/micuat)\
**Post date:** [October 12, 2021, 6:18pm UTC](https://discourse.processing.org/t/trying-to-get-a-better-understanding-of-array-loops/32779/4 "2021-10-12T18:18:07Z")

</div>

You have a good intuition of what loops are, but I feel you are trying to do something rather complex. I recommend you to start with Dan’s tutorial, in which he explains how to draw shapes in a loop. It’s always good to start with something simple as it’s more rewarding and fun 🙂

---

<div class="post-metadata">

**Author:** ![ADG](https://avatars.discourse-cdn.com/v4/letter/a/f0a364/32.png) [@ADG](https://discourse.processing.org/u/ADG)\
**Post date:** [October 12, 2021, 11:20pm UTC](https://discourse.processing.org/t/trying-to-get-a-better-understanding-of-array-loops/32779/5 "2021-10-12T23:20:15Z")

</div>

> I recommend you to start with Dan’s tutorial, in which he explains how to draw shapes in a loop.

I have watched those videos and I’m past those. I understand working with functions, and objects, but when I introduce arrays things get messy and I think it’s because I don’t understand arrays top to bottom.

> I feel you are trying to do something rather complex.

So to be clear, I’m not trying to make this code work.

I’m just trying to understand _why_ it breaks down. I’m going to assume it would work smoothly if additional functions were created

Either way, I appreciate the response. I guess this is one of those things you improve your understanding of as you code.

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [October 13, 2021, 2:31am UTC](https://discourse.processing.org/t/trying-to-get-a-better-understanding-of-array-loops/32779/6 "2021-10-13T02:31:51Z")

</div>

> [@ADG](#):
>
> Can you give me any tips for writing loops with arrays,

In Processing arrays are generally used to store objects we instantiate from a class.

In **setup()** we can use a `for ( ; ; )` loop to fill an array w/ instances of a class if we know how many we’re gonna need.

And in **draw()** we use a `for ( of )` loop to access those stored objects’ properties & methods.

The sketch below use a `for ( of )` loop to invoke the method **display()** for each Ball object in the array _balls[]_:

https://OpenProcessing.org/sketch/1306831/embed/

It also calls back function **createBall()** every time we click the mouse inside the canvas and **push()** a `new` Ball instance into array _balls[]_ until its _length_ is 8.

Once the array is full each click now recycles a Ball instance from the head of the array back to its tail.

2 more sketch examples to check out:

> <https://gist.github.com/GoSubRoutine/60b154e52336f7fee7c5f1fe817ceb22>
>
> There are more than three files. show original

> <https://gist.github.com/GoSubRoutine/d0b7d3058d84970e83cf8685f8e69777>

---

<div class="post-metadata">

**Author:** ![ADG](https://avatars.discourse-cdn.com/v4/letter/a/f0a364/32.png) [@ADG](https://discourse.processing.org/u/ADG)\
**Post date:** [October 16, 2021, 9:40pm UTC](https://discourse.processing.org/t/trying-to-get-a-better-understanding-of-array-loops/32779/7 "2021-10-16T21:40:42Z")

</div>

@GoToLoop I have a few questions regarding the example if you don’t mind. I noticed you created the function for the array outside of draw, and you created a class.

My questions are:

1. When making multiple instances of a shape, do you have to make a class/object? I assume it is easier to work with, but is it not possible with functions alone?

In terms of my beginner workflow, I start with generic shapes, and I try to build on them and expand them into functions. I feel like this is causing me difficulties, because I don’t have the complex structure of functions and classes in place. should I just start with a class from the beginning?

1. In **createBall()** you create a constant **b** make it equal to **MAX\_BALLS** & you shift the array or create a new ball. Could you expand on the logic as it looks a little advanced.

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [October 16, 2021, 10:29pm UTC](https://discourse.processing.org/t/trying-to-get-a-better-understanding-of-array-loops/32779/8 "2021-10-16T22:29:26Z")

</div>

> [@ADG](#):
>
> , do you have to make a class/object? I assume it is easier to work with,

That’s the easiest approach. Having a class to represent both the properties (data) and all the actions (methods) we can do w/ those props. encapsulated inside the same structure makes things much easier & organized.

> [@ADG](#):
>
> , but is it not possible with functions alone?

Well, you surely can! However, you’re gonna need multiple containers, like 1 array for each shape property; and have to track down the current index for those containers.

> [@ADG](#):
>
> Should I just start with a class from the beginning?

If you know you’re gonna need multiple copies of a shape, starting creating a class for it from the beginning makes sense.

> [@ADG](#):
>
> Could you expand on the logic as it looks a little advanced.

Indeed it’s written in advanced style. But let’s try to simplify it.

The statement below:  
`const b = balls.length == MAX_BALLS && balls.shift() || new Ball;`

is closely equivalent to:  
`const b = balls.length == MAX_BALLS? balls.shift() : new Ball;`

which is called the conditional operator btW:

> **[Conditional (ternary) operator - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)**
>
> The conditional (ternary) operator is the only JavaScript operator that takes three operands:
> a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression...

That statement can be further transformed into an `if () / else` structure like this:

```auto
var b;
if (balls.length == MAX_BALLS) b = balls.shift();
else b = new Ball;

```

> [@ADG](#):
>
> In **createBall()** you create a constant **b** , make it equal to **MAX\_BALLS** & you shift the array or create a new ball.

As you can notice by now, MAX\_BALLS isn’t the actual value being assigned to variable _b_.

Instead it’s either an already existing Ball object returned by the Array::**shift()** method:

> **[Array.prototype.shift() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift)**
>
> The shift() method of Array instances removes the first
> element from an array and returns that removed element. This method changes the length
> of the array.

Or a completely `new` Ball object:

> **[new - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new)**
>
> The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

Depending on whether the Array::_length_ reached value MAX\_BALLS:

> **[Array: length - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length)**
>
> The length data property of an Array instance represents the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

Either way, variable _b_ stores a Ball object, which is then initialized/reset via method Ball::**setXY()** and then Array::**push()** back to the _balls[]_ array:

> **[Array.prototype.push() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)**
>
> The push() method of Array instances adds the specified elements to the end of
> an array and returns the new length of the array.

In short, _balls[]_ never gets bigger than MAX\_BALLS.

An oldest Ball object is continuously being removed from the beginning (head) of _balls[]_ and re-inserted back to its end (tail).

---

<div class="post-metadata">

**Author:** ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)\
**Post date:** [October 17, 2021, 10:22am UTC](https://discourse.processing.org/t/trying-to-get-a-better-understanding-of-array-loops/32779/9 "2021-10-17T10:22:28Z")

</div>

> [@ADG](#):
>
> array loops

I don’t like the phrase.

I mean there are arrays and there are loops (for example while loop or for-loop).

There are also loops you can use to work with arrays. But array loops…? No…

**Links**

Tutorial see [Arrays / Processing.org](https://processing.org/tutorials/arrays) for Arrays

Tutorial see [Two-Dimensional Arrays / Processing.org](https://processing.org/tutorials/2darray) for Two-Dimensional Arrays (grid / chess board)

Reference: see [for / Reference / Processing.org](https://processing.org/reference/for.html) for FOR (there are other loops)

reference page also has an array section for commands like append: [Reference / Processing.org](https://processing.org/reference/#data)

---

<div class="post-metadata">

**Author:** ![ADG](https://avatars.discourse-cdn.com/v4/letter/a/f0a364/32.png) [@ADG](https://discourse.processing.org/u/ADG)\
**Post date:** [October 19, 2021, 6:00am UTC](https://discourse.processing.org/t/trying-to-get-a-better-understanding-of-array-loops/32779/10 "2021-10-19T06:00:19Z")

</div>

Sorry. I’m figuring it out as I go. I meant loops which contain arrays.

---

<div class="post-metadata">

**Author:** ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)\
**Post date:** [October 19, 2021, 6:28am UTC](https://discourse.processing.org/t/trying-to-get-a-better-understanding-of-array-loops/32779/11 "2021-10-19T06:28:31Z")

</div>

Hello @ADG,

Nothing to be sorry for! Nothing at all…

[Google search for “Array Loops”](https://www.google.com/search?q=%22array+loops%22&rlz=1C1CHBF_enCA973CA973&tbs=li:1&ei=g2NuYayNGerBytMPlq2MwA0&start=60&sa=N&ved=2ahUKEwjs2s-v6tXzAhXqoHIEHZYWA9g4MhDw0wN6BAgBEEk&biw=1536&bih=854&dpr=1.25)

`:)`

---

<div class="post-metadata">

**Author:** ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)\
**Post date:** [October 19, 2021, 7:22pm UTC](https://discourse.processing.org/t/trying-to-get-a-better-understanding-of-array-loops/32779/12 "2021-10-19T19:22:37Z")

</div>

No apologies needed……
