Basic Algorithm Scripting - Repeat a String Repeat a String

Tell us what’s happening:
Describe your issue in detail here.

Hello! I understand the problem, but I just wanted to know what is wrong with my code? I’m I using “concat” in the wrong way?

Your code so far

function repeatStringNumTimes(str, num) {
   let newStr = " ";
  if ( num < 0) {
    return str = " ";
  } else {
    for (let i = 0; i < num; i++) {
      newStr.concat(str);
    }
  }
    return newStr;

  
}

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/118.0.0.0 Safari/537.36

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

Link to the challenge:

this is not an empty string, it is a string which contains space

What if num equals 0. Instruction is Return an empty string if num is not a positive number.

Consider to read this, if you haven’t yet

Look at this part
The concat() function concatenates the string arguments to the calling string and returns a new string. Changes to the original string or the returned string don't affect the other.

If we add some logs to your code:

function repeatStringNumTimes(str, num) {
   let newStr = " ";
  if ( num < 0) {
    return str = " ";
  } else {
    for (let i = 0; i < num; i++) {
      console.log(`i equals ${i} for current iteration`)
      console.log(`newStr is ${newStr}`)
      console.log(`length of newStr now is ${newStr.length}`)
      newStr.concat(str);
    }
  }
  console.log(newStr)
    return newStr;

  
}

repeatStringNumTimes("abc", 3);

we will see that newStr value is not changing as loop keeps going.

minor note: it is up to you - to use concat() or not, but it is worth mentioning, that some non-english versions of MDN article about .concat() recommend using + or += operators instead when it is possible due to perfomance

Thanks for your help :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.