Sliders in For Loops

Hello, I am currently working on a small idea here. It involves ellipses that move across the canvas and are put in an array. A constructor function makes the ellipses with random x, y, and speed. I am trying to adjust the amount of stars that are on the screen with a slider. The amount of stars are controlled by a variable called “starAmount”. I am trying to set the value of star amount to a slider value, but it gives me errors:

Uncaught TypeError: Cannot read property ‘value’ of undefined (sketch: line 8)
Uncaught ReferenceError: starAmount is not defined (sketch: line 12)

Can I not assign a variable to have the value of a slider that is located in a for loop?

I am new to the javascript language and p5js, so if you could keep the terminology lite it would be much appreciated.

// This array holds our points (stars)
let stars = [];
// Slider for background color
let bgSlider;
// Slider for Star Amount
let saSlider;
// Declare an slider varaible;
let starAmount = saSlider.value();

function setup() {
  createCanvas(400, 400);
  for (let i = 0; i < starAmount; i++) {
    stars[i] = new StarConst();
  // Slider for star amount
  saSlider = createSlider(0, 1000, 0);
  saSlider.position(200, 410);
  // Slider for background color
  bgSlider = createSlider(0, 255, 0);
  bgSlider.position(0, 410);

function draw() {
	let bgColorSL = bgSlider.value();
  // starObj.placement();
  for (let i = 0; i < starAmount; i++) {

function StarConst() {
  this.x = Math.random() * 100 - 100;
  this.y = Math.random() * height;
  this.sp = Math.random() * 5 + 2; = (Math.random() * 20) + 5;

  this.movement = function() {
    this.x += this.sp;
    if (this.x > width + 50) {
      this.x = Math.random() * 100 - 100;
  } = function() {
    fill(255, 255, 0);
    ellipse(this.x, this.y,;
1 Like

Read through your code line by line to understand what it’s doing. Start here:

let saSlider;

At this point you’ve declared a variable, but you haven’t set it to any value. So its value is undefined. You can confirm this by printing its value to the console:


Then you do this:

let starAmount = saSlider.value();

You’re trying to call the value() function on a variable that doesn’t have a value yet. That’s why you’re getting an error.

I think you probably want to change your code so starAmount has some default value. Then you’d want to add a listener to your slider, or somehow redraw your scene when the user adjusts the slider.