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

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

#1

image

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


#2

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.


#3

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.


#4

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


#5

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): '';
}

#6

The condensed code does look awesome.
thanks!


#7

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

#8

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


#9

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