Uncaught TypeError: Cannot read property 'show' of undefined

I am having a problem with a small programme that I was making on a JavaScript framework known as p5js. All I wanted to do is to have 10 floating circles on the screen, hope you’ll help me :slightly_smiling_face:. This is the error I’m getting -
Uncaught TypeError: Cannot read property ‘show’ of undefined (sketch: line 15)

This is my code -

let b = [];

function setup() {
  createCanvas(600, 400);
  for (var i = 0; i <= 10; i++) {
    b[i] = new Bubble();

function draw() {


  for (var i = 0; i <= b.length; i++) {


class Bubble {
  constructor() {

    this.x = random(50, 550);
    this.y = random(50, 380);
    this.r = 15;

    this.show = function() {
      ellipse(this.x, this.y, this.r * 2, this.r * 2);

    this.move = function() {

      this.x = this.x + random(-1, 1);
      this.y = this.y + random(-1, 1);



Thanks for the help!! :slightly_smiling_face: :slightly_smiling_face:

Hello, and welcome back to the forums!

The issue is the conditional you’re using in the for loop.

  for (var i = 0; i <= b.length; i++) {

b.length gives the total number of elements in your array, but the array itself is zero-based.
You can either change it to

  • check if i is less than b.length
  • check if i is less or equal to b.length - 1

This is why your code currently shows 11 circles before stopping. Your first for loop also creates 1 more than you intended.

1 Like

You have created the setup function but I don’t see that you have called it anywhere in the code provided.

So as it stands the b array is still an empty array.

In this case, they’re using the p5js framework, so it takes care of calling certain functions at certain times. You can try it out here: https://editor.p5js.org/


Thanks!! It really helped, and most importantly I understood the logic behind it so thank you very very much for that!!