Repeat a String repeat a string assistance

Repeat a String repeat a string assistance
0

#1

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

#2

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


#3

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 ?


#4

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.


#5

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


#6

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


#7

ok got it @kevcomedia…bumping this

could someone help me with the code?

thanks


#8

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.


#9

so i updated the return(str) w/

‘’'console.log(str)

but it doesn’t do anything. hmmmmm


#10

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.


#11

/// 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);

///