0

I'm trying to complete The Odin Project and saw an interesting console error

function repeat(string, number) {
  var finalst;

  for (i = 0; i < number; i++) {
    finalst += string;

  }
  return finalst;
}
console.log(repeat("hey", 3));

The result in console is "undefinedheyheyhey". How is it showing like that and why ?

padaleiana
  • 955
  • 1
  • 14
  • 23
Andre
  • 59
  • 8
  • 2
    It's probably because `finalst` is initially set to the value `undefined`. To fix this, set the initial value of `finalst` to an empty string. – Edric Jun 04 '20 at 14:10
  • 1
    [What's the difference between variable definition and declaration in JavaScript?](https://stackoverflow.com/questions/20822022/whats-the-difference-between-variable-definition-and-declaration-in-javascript#:~:text=What's%20the%20analog%20in%20JS,value%20to%20this%20allocated%20memory) – j08691 Jun 04 '20 at 14:12

2 Answers2

5

You need to initialize it like this: var finalst = "";:

function repeat(string, number) {
  var finalst = ""; //change this

  for (i = 0; i < number; i++) {
    finalst += string;

  }
  return finalst;
}
console.log(repeat("hey", 3));

If you don't, it's initial value will be undefined, which will result in undefined+hey+hey+hey in your case:

var finalst;
console.log(finalst);
for (i = 0; i < 3; i++) {
    finalst += "hey";
}
console.log(finalst);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • 1
    Instead of only providing code to OP, please also explain _how_ your code has resolved the issue. – Edric Jun 04 '20 at 14:12
4

If you don't init value, it's value = undefined.

finalst += string;: finalst.toString() + string => undefined + hey

You need init finalst:

function repeat(string, number) {
  var finalst = "";

  for (i = 0; i < number; i++) {
    finalst += string;

  }
  return finalst;
}
console.log(repeat("hey", 3));
Nikita Madeev
  • 4,284
  • 9
  • 20