coe
coe

Reputation: 291

Loop - How to add onto a variable each loop

I am trying to add onto a variable each time a loop is ran. In this loop I want each loop to add hey to hey. So that hey is added 13 times. My loops is only adding it once which is confusing me. I am only trying to get this to show up in the console at the moment. Thank you!

const repeatString = function() {

    let test = 'hey';
    let add = 'hey';

    for (let i = 0; i < 13; i++) {
        return test += add;
    }
}

console.log(repeatString());

Upvotes: 0

Views: 738

Answers (1)

Mamun
Mamun

Reputation: 68933

You are returning from the function in the first iteration. You should return from outside of the loop (after the completion of the loop):

const repeatString = function() {

    let test = 'hey';
    let add = 'hey';

    for (let i = 0; i < 13; i++) {
        test += add;
    }
    return test;
}

console.log(repeatString());

Upvotes: 3

Related Questions