Reputation:
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));
Upvotes: 1
Views: 129
Reputation: 20039
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))
Upvotes: 0
Reputation: 1630
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.
Upvotes: 0
Reputation: 14982
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)); // **********
Upvotes: 3
Reputation:
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.
Upvotes: 0