Repeat a String Repeat a String- logic question

Repeat a String Repeat a String- logic question
0

#1

Tell us what’s happening:
I want to know why its not working as setting str equal to an empty string when its less than zero and just returning str in the last curly braces, and why it only works when we write return a blank string after the first if statement and then dont have a return str in the last curly braces.

i thought the below code would read like so:
if num is less than zero set str equal to an empty string and then it would skip all the other logic statements and go to the last curly brace to return str. I understand that this is the wrong solution. however If someone can explain in detail why i messed it up.

Your code so far


function repeatStringNumTimes(str, num) {
  // repeat after me
 if (num<0){
    str= "";
  } if (num===1){
    return str;
  } else {
    return str+ repeatStringNumTimes(str,num-1);
  }
  return str;
}
repeatStringNumTimes("abc", 3);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/repeat-a-string-repeat-a-string


#2

You are failing this test case.

repeatStringNumTimes(“abc”, -2) should return “”.

When -2 is passed in, it does indeed go through the first if statement and setting it to an empty string. It goes down the next if statement and since this condition is false else statement will execute.

I would just return empty string in the first if statement.


#3

If you properly indented your code, you would be able to see that the first if statement is not connected to the second if statement. The else statement is connected to the second if statement.

function repeatStringNumTimes(str, num) {
  // repeat after me
  if (num < 0) {
    str = "";
  } // this defines the end of the first if statement
  if (num === 1) {
    return str;
  } else {
    return str + repeatStringNumTimes(str, num - 1);
  }
  return str;
}
repeatStringNumTimes("abc", 3);