Repeat a String repeat a string assistance

Hello,

I have written this code, and as simple as it seems, i can’t find what’s wrong with it. thanks.

function repeatStringNumTimes(str, num) {
  if (num > 0) {
    for (var i=num; i > 0; i--) {
    return(str);
  }
  }
    else
      return "";
  
  // repeat after me
  
}

repeatStringNumTimes("abc", 4);

What does the standard output look like?
Right now you’re returning on the first decrement in the loop body. The return keyword actually will exit your function call when it’s interpreted. Check this reference out. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return

1 Like

In your for loop.
you do this “return(str)”.
What would be in the str at this point ?
What do you expect to happen here ?
What happens in a function when you call the return statement ?

ok, so great news, the return exits the loop, thereby causing the output to only read once. I have to figure out what to do next.

and why does console.log(str) not work?

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

ok got it @kevcomedia…bumping this

could someone help me with the code?

thanks

just thinking out loud…since you have to repeat the string, why don’t you write a for loop inside your function with num and just console.log the string.

so i updated the return(str) w/

‘’'console.log(str)

but it doesn’t do anything. hmmmmm

Instead of using console.log, try using a variable to “accumulate” the repeated string using concatenation. Then after you’re done with the loop, return the value of that variable.

/// testing
function chunkArrayInGroups(arr, size) {
var array = [];
var len = arr.length;

for (i = 0; i < len/size; i++){

array.push(arr.slice(0, size));

}

// Break it up.
return array;
}

chunkArrayInGroups([“a”, “b”, “c”, “d”], 2);

///