Skip to content
Advertisement

JS : Why does my do … while loop is not exited?

I wanted to execute a do…while loop to try this code.

JavaScript

My goal is simply, when the user enters E when prompted, we exit the loop and meet the condition that while action is not E, we keep rolling. It does not work with the code above. I’m stuck with an infinite loop even when entered E.

I’m able to make it work if I create new if statement condition inside the loop, as if action === 'E' {break}. But then I don’t understand why the while statement is not worth anything.

all the console.log(action) are for debugging purpose…

Advertisement

Answer

Look at this condition:

JavaScript

It’ll always be true:

JavaScript

What you need is:

JavaScript

Or, less readably:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement