1

just learning JS and am going through Algorithm challenges.

The below code should repeat a string (str) x (num) times.

So for example repeatStringNumTimes('*', 3) should be '***'. The below code does that... but there is an 'undefined' word that appears in the beginning of the output. Why is that?! I've defined all variables...

function repeatStringNumTimes(str, num) {

    let len = str.length;
    let string;

for (let i = 0; i < num; i++) {

    for (let x = 0; x < len; x++) {

        string += str[x];

    }

}
return string;
}

console.log(repeatStringNumTimes('*', 10));
2
  • change let string; to let string = ""; as string is undefined initially Commented Jun 20, 2019 at 3:54
  • think of let string; as being let string = undefined; Commented Jun 20, 2019 at 3:54

4 Answers 4

3

I've defined all variables

Yes you define it, but not initialize.

Default initalization in javascript is undefined.

So, let a; equals to let a = undefined;
You should initialize your strings with empty string:

let string = '';  

Just a note:

Modern javascript engines have String.prototype.repeat method for that task:

console.log('*'.repeat(10)); // **********
Sign up to request clarification or add additional context in comments.

Comments

0

Ok so, in order to make this work I added

let string = "";

I'm not sure why that works though. Any insight from someone more experienced would be greatly appreciated.

1 Comment

String is initially undefined (never initialized). Then string += str[x] in the first loop, expands to string = undefined + str[x]
0

You probably need to declare string:

let string = "";

UPDATE:

That is because of this line:

string += str[x];

Which equates to:

string = string + str[x]; 
// equivalent to string = undefined + str[x]

You are assigning an undefined string to itself (+ str[x]), if that makes sense.

2 Comments

Can you elaborate as to why you need to specify that? I ask only because of my lack of knowledge in JS.
Because of this line: string += str[x];You are basically adding the value of an undefined string + str[x] to itself.
0

Traditional approach using while

const repeatStringNumTimes = (str, num) => {
  let res = str
  while (--num) res += str
  return res
}

console.log(repeatStringNumTimes('*', 10))

Using String.prototype.repeat

const repeatStringNumTimes = (str, num) => str.repeat(num)

console.log(repeatStringNumTimes('*', 10))

Using String.prototype.padStart() or String.prototype.padEnd()

const repeatStringNumTimes = (str, num) => ''.padStart(num, str)

console.log(repeatStringNumTimes('*', 10))

Using Array.prototype.join()

const repeatStringNumTimes = (str, num) => Array(num).join(str)

console.log(repeatStringNumTimes('*', 10))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.