Repeat a String Repeat a String am I missing something?

Tell us what’s happening:
when I run the specified arguments through sublime text I get the results that the challenge is looking for. Yet when I run in codecamp some challenges will not pass. Since the arguments (‘abc’, 3) results in a correct solution, then shouldn’t the arguments (’*’, 8), logically also work? What am I missing?

Your code so far


<spoiler>
let i=0;
let newStr = '';
function repeatStringNumTimes(str, num) {
if(num>0){
while(i<num){
  newStr += str;
  i++;
}
return newStr;
}else{
  return '';
}
}
repeatStringNumTimes("abc", 3);
</spoiler>

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/repeat-a-string-repeat-a-string/

ok so this is the problem
just move these global variables so they are local to the function and your code should pass

I see, so after calling the first time with args (“abc”, 3) the global variables will be set to newStr = “abcabcabc” and i would e set to 2 when the function is called again?

is it generally better practice to avoid global variables when possible when coding in general?

did it, works great! Thank you both!

1 Like

just to answer your question: yes you should avoid changing global variables.
(if you need to change it, you should require it as a parameter and then make a local copy inside your function and change only that. This would then allow your code to stay flexible in case the global variable is moved or deleted. )

thank you, you guys are awesome :slight_smile:

1 Like