Hey guys decided to use while to do this one, but it’s not working out. What am I doing wrong?
Your code so far
function repeatStringNumTimes(str, num) {
var finalResult = ""; //initialize string to hold result
while (num > 0) { //repeat finalResult.push(str) while num is positive
return finalResult.push(str);
num--; // subtract num by 1
} else {
return ""; // else return empty string
}
}
console.log(repeatStringNumTimes("abc", 3));
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36.
You should use the chain of if…else and not while…else. It simply doesn’t exist. Actually, you don’t need else block here. While loop will execute as long as the condition is true. Loop will stop when condition becomes false and nothing will happen. So, you don’t need to pass it explicitly.
return returns a value and stops any further execution. Therefore, you should use it only at the end of a function.
push method pushes element inside an array. It doesn’t work with strings. You should use string concatenation in this case.
Now, here is the solution. Compare it with your code and try to understand.
It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.
We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.
We understand that you are trying to help but if the OP wanted answers they could just look it up in the guide.
Allow the OP to digest the steps you provided them and revise their approach and if they are follow up questions then they can ask here in this thread.
It will be a better learning experience if that arrive at the answer on their own with hints instead of reading solutions.
I completely understand your point. Will definitely keep it in mind in future. I, myself, am a newbie and struggling with javascript. That was done with the intention to help only.