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

let i=0;
let newStr = '';
function repeatStringNumTimes(str, num) {
  newStr += str;
return newStr;
  return '';
repeatStringNumTimes("abc", 3);

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:

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.

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