Repeat a String Repeat a String am I missing something?

Repeat a String Repeat a String am I missing something?
0

#1

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/


#2

Because you defined i and newStr globally and the fact that the FCC tests run one after another using any code you have declared, these variables will retain the value they had at the end of the last call to the function. This is a great example of why not to use global variables. Try moving these declarations inside the function and see what happens.


#3

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


#4

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?


#5

did it, works great! Thank you both!


#6

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. )


#7

thank you, you guys are awesome :slight_smile: