Web development 101 - JavaScript Fundamentals part 4 - repeatString exercise


#1

Hello everyone,

I am a little stuck on the repeatString assignment. My repeatString variable should say “heyheyhey”, but returns undefined. What is wrong with my code?

let repeatString = function() {
    for (let i = 0; i < 3; i++) {
        repeatString += "hey";
    }
}

Of course I could figure out another way to do it, but then I won’t know what’s wrong with this code: I also had problems like this during the Rock Paper Scissors project, so it might be nice to know what I should pay attention to.

Thanks!


#2

You have named the string the same name as the function, that is not a good idea.

Secondly you don’t initialise an empty string anywhere

Thirdly you don’t return anything from the function.

Hope that helps :slight_smile:


#3

Oh wow, that’s actually a few things :blush: thanks!

I changed it into this and now it works :wink:

let addString = "hey"
let repeatString = function() {
    for (let i = 0; i < 2; i++) {
        addString += "hey";
    }
    return addString;
}

#4

If you declare the string outside the function then it’s going to be that string whenever that file is imported.

You can declare an empty string inside the function let addString = '' then inside the for loop you can add to the string.

let repeatString = function() {
    let addString = '';
    for (let i = 0; i < 3; i++) {
        addString += "hey";
    }
    return addString;
}