Why am I getting undefined but not abc repeated 3 times?

image

Syntax check, logic checked… I made sure we can place for loops inside if statements…
am I missing something?

Definitely make sure you are putting var i instead of just i. Currently you are declaring that on the global scope.

Secondly, num is number, it doesn’t have a built in length property. Just do i < num.

Why do you use num.length? It equals to undefined and that is why your code doesn’t work. Use num instead. Also declare var locally. And if else clause is not really needed in your code.

Hey y’all I did remove the num.length totally get its not a string, so that was my bad… however the first screenshot without the length property still did not work… totally confuses me. But the exercise did give the reference to the Global String Object.

So… what ended up working was str.repeat(num) and adding screenshot of the code that worked. Finally!

image

That’s probably a cleaner solution. However, your original code does work with the changes that @prohorova and I both suggested. If you’re trying to solve the challenge, you would have replaced console.log(str) with result += str where result is a variable declared at the top of the function:

function repeatStringNumTimes(str, num){
  var result = '';
	if (num > 0){
  	for (var i = 0; i < num; i++){
       result += str;
    	console.log(str);
    }
  }
}

repeatStringNumTimes('abc', 3);

You’re new solution could be condensed too:

function repeatStringNumTimes(str, num) {
  return num > 0 ? str.repeat(num): '';
}

The condensed code does look awesome.
thanks!

Actually if num is zero or not a number the resulting string will be empty anyway so code could be even shorter:

function repeatStringNumTimes(str, num) {
  return str.repeat(num);
}

That can’t work. If repeat gets a negative number it throws a range error, causing the last test case to fail.

Yeah you right. Weird that it works correctly with NaN and other invalid types but not negative numbers.