Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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);

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda