trying to generate array using recursion in javascript but getting undefined value

Viewed 20

I am trying to generate an array of 3 random numbers representing the 3 RGB values using recursion, but getting undefined in the console can you please explain what is the problem and how can I solve it.

const randomColor = (currColor = []) => {
  let color = currColor;
  color.push(Math.floor(Math.random() * 255 + 1));
  if (color.length === 3) return color;
  else {
    randomColor(color);
  }
};

const rc = randomColor();
console.log(rc);

1 Answers

You need to return on your recursion call.

const randomColor = (currColor = []) => {
  let color = currColor;
  color.push(Math.floor(Math.random() * 255 + 1));
  if (color.length === 3) return color;
  else {
    return randomColor(color);
  }
};

const rc = randomColor();
console.log(rc);

Another option would be to send the initial array as an param and then use that. Something like this

const randomColor = (currColor = []) => {
  let color = currColor;
  color.push(Math.floor(Math.random() * 255 + 1));
  if (color.length === 3) return color;
  else {
    randomColor(color);
  }
};

const colors = []

randomColor(colors);
console.log(colors);

But the first option is probably what you want.

Related