Repeat a string repeat a string - part duex

Repeat a string repeat a string - part duex
0.0 0

#1

So I got one solution (attempt # 1) but now I’m trying to make it cleaner (attempt # 2).

I see that the code solution says to use REPEAT method. But I went down the += operator and now I want to see why it won’t work. I think the looping is adding a lot more repeats than I want but I can’t tell why. Can someone please review my attempt # 2 code? Thank you.

Your code so far

// Attempt # 1
function repeatStringNumTimes(str, num) {
  // repeat after me
  strungtogether = str;
  if (num < 0) {
    strungtogether = "";
  }else 
    for (i = 0; i < num-1; i++){
      strungtogether += str;
    }
  
  return strungtogether;
//   console.log(strungtogether);
}

repeatStringNumTimes("abc", 3);


// Attempt # 2
function repeatStringNumTimes(str, num) {
  // repeat after me
  if (num < 0) {
     str = "";     
     console.log(str);
  }else 
    for (i = 0; i < num-1; i++){
      str += str;
      console.log(str);
    }
//   console.log(strungtogether);
}

repeatStringNumTimes("abc", 3);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36.

Link to the challenge:


#2

Note that your attempt #1 still fails where the second parameter is 0.

As for attempt #2, there are a number of problems, the most serious being that your function lacks a return statement.

As for why it’s repeating the string too many times, consider this similar analogy:

function addStuff(val, reps) {
  for (let i = 0; i < reps; i++) {
    val += val;
  }
  return val;
}

addStuff(1, 1); //2
addStuff(1, 2); //4
addStuff(1, 3); //8