hobbyiscoding
hobbyiscoding

Reputation: 41

why is while loop not iterating?


function timesTable(num1) {
    var counter = 0;
    while (counter < num1) {
        counter +=1
        return (counter + ' * '  + num1 + ' = ' + counter * num1);
        
    }
}

console.log(timesTable(9));

the while loop is not iterating all it does is show 1 * 9 = 0 counter only increases once and doesn't show next line?? what do I do to fix this

Upvotes: 1

Views: 103

Answers (3)

Lalanthaw
Lalanthaw

Reputation: 19

Try putting return statement outside the while loop.

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89204

You should build a string to return at the end (outside the loop) instead of returning inside the loop.

function timesTable(num1) {
    var counter = 0, res = "";
    while (counter < num1) {
        counter += 1
        res += counter + ' * '  + num1 + ' = ' + counter * num1 + '\n';
    }
    return res;
}

console.log(timesTable(9));

Upvotes: 2

Aditya Panikkar
Aditya Panikkar

Reputation: 59

The issue here is that you are returning inside the loop, meaning that the counter variable increments once and then the statement is returned. To fix this, put the return statement outside the while loop

Upvotes: 2

Related Questions