Basic Algorithm Scripting - Repeat a String Repeat a String

Tell us what’s happening:
I am not able to pass this problem
why was I not able to use the push method
please let me know, where mistake lies in my code??

I’m getting this error
TypeError: str1.push is not a function
Your code so far

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

console.log(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/110.0.0.0 Safari/537.36

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

Link to the challenge:

push is a method on arrays. The str1 variable you’ve made is not an array (it’s a string), so you can’t use push on it.

You may want to review how to concatenate strings.

oh, yes!
But still I’m getting an error to pass the tests…
what should I do?

Please share your updated code.

function repeatStringNumTimes(str, num) {
let str1 = (“”);
if (num === +num) {
for (let i=0; i<=num; i++) {
str1[i].concat(’ , ’ , str);
}
} else {
return “”
}
return str1;
}

console.log(repeatStringNumTimes(“abc”, 3));

Did you check out the link I posted above? It has the lesson on combining strings with the + operator. I think that you should try to use that to solve this problem.

yeah Sorry, I didn’t noticed it!
I tried that method…
This is the updated code

still, I’m not able to pass the test cases

function repeatStringNumTimes(str, num) {
let str1 = [“”];
if (num === +num) {
for (let i=0; i<=num-1; i++) {
str1[i] = [str];
}
} else {
return “”
}
return str1;
}

console.log(repeatStringNumTimes(“abc”, 3));

It is returning [‘abc’, ‘abc’, ‘abc’] without adding ’ , ’ to it
how to pass it without using array
I need to get plain abcabcabc

I don’t think you should use an array here.

let result = "";
result += "cat";
result += "dog";
console.log(result);

What do you think this logs out?

1 Like

yeah, the result will be catdog!!

Oh yes!!, it worked
Thanks a lot!!

Please use a new topic for a new Challenge. Thanks

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