EsotericRider
EsotericRider

Reputation: 127

Do while loop in JavaScript stops looping when condition is not met

I wrote a do while loop but it does not keep looping even though the condition is not met. There in an array called quotes and I am comparing the input number to the length of that array to make sure it only modifies an element already there. Even though I add a higher number, it just adds it to that array element.

function modifyQuote(){
    'use strict'

    var modifyQuoteNum = 0
    do{
        var inputModify = prompt("what quote do you want to modify?");
        modifyQuoteNum = (parseInt(inputModify) - 1); 
    }
    while ((typeof modifyQuoteNum == 'number') && 
        ((modifyQuoteNum + 1) <= quotes.length));

Figured it out, got mixed up.

function modifyQuote(){
    'use strict'

    var inputModify = prompt("what quote do you want to modify?");
    var modifyQuoteNum = (parseInt(inputModify) - 1);

    while ((typeof modifyQuoteNum != 'number') || 
        ((modifyQuoteNum + 1) > quotes.length)){

        var inputModify = prompt("what quote do you want to modify?");
        var modifyQuoteNum = (parseInt(inputModify) - 1);

    }

Upvotes: 0

Views: 266

Answers (1)

NPE
NPE

Reputation: 500227

It looks like you got your condition the wrong way round.

it does not keep looping even though the condition is not met

That's how while loops work: they only keep looping while the condition is met.

The fix is trivial, so I'll let you figure out what it is as an exercise.

Upvotes: 2

Related Questions