Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!