Returning recursive function as a single string? Repeat a String Repeat a String

So I decided to use recursion for this challenge. The strings repeat the correct amount of times and it loops fine. My only real issue that I can see is that instead of printing everything on a single line as required, it’s being printed in separate lines.

function repeatStringNumTimes(str, num) {
if (num <= 0) {
  return "";
} else {
  repeatStringNumTimes(str, num - 1);
  console.log(str)
  return str;
}

}

repeatStringNumTimes("abc", 3);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36

Challenge: Basic Algorithm Scripting - Repeat a String Repeat a String

Link to the challenge:

That’s because of this:

console.log(str)
return str;

You are just printing str to the console each time and then returning it, you aren’t building up str so that it returns the required value.

repeatStringNumTimes(str, num - 1);

This returns a value but you aren’t doing anything with it.

Hint: You can condense your else block into one line.

Please note by the tests that what the problem is asking is to take a string and concatenate it num times, and not to return it three times.
If you have a string ‘test’ and num = 3, you have to figure out a way to return testtesttest

I can’t figure out how to return the value plus the function again. I added str + the function but it doesn’t seem to do anything.

} else (str + repeatStringNumTimes(str, num - 1));{
  console.log(str)

}

Your formatting is very misleading. Here is your code with consistent formatting:

function repeatStringNumTimes(str, num) {
  if (num <= 0) {
    return "";
  } else
    (str + repeatStringNumTimes(str, num - 1));

  {
    console.log(str)
  }
}

repeatStringNumTimes("abc", 3);

And here are some braces added

function repeatStringNumTimes(str, num) {
  if (num <= 0) {
    return "";
  } else {
    str + repeatStringNumTimes(str, num - 1);
  }
  {
    console.log(str)
  }
}

repeatStringNumTimes("abc", 3);

You still are not returning a concatenated string anywhere.

Lets back up. Two questions

  1. Do you know how to concatenate two strings?

  2. Do you know how to use the return value of a function?

Hang on I think I figured it out.

I thought I had to return str but I actually had to just return str plus the function. So I think I was sort of on the right track originally but got confused somewhere.

function repeatStringNumTimes(str, num) {
  if (num <= 0) {
    return "";
  } else {
    return str + repeatStringNumTimes(str, num - 1);
  
  }

}

repeatStringNumTimes("abc", 3);
1 Like