Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript While Loop Conditional Abberation

I am curious as to why this while loop is not breaking as expected. It is my understanding that when using the OR operator (||), if any of the conditions are found to be false, the loop breaks.

However, I noticed in a test document (I am learning JS for the first time) that my while loop is requiring ALL conditions to be found false before breaking.

This is a stub example:

var stringName="", numhours=0, numRate=0;

document.write("Exit at any time by entering -1");
while (stringName != "-1" || numHours != -1 || numRate != -1){
    stringName = prompt("Enter name","");
    numHours = prompt("Enter num hours","");
    numHours = parseFloat(numHours);
    numRate = prompt("Enter rate per hour","");
    numRate = parseFloat(numRate);
}

I would like it so that a user can enter -1 at any stage, and once the loop completes, it will re-check the conditions again, and after finding that the it is false that the name does not equal "-1", or false that the hours does not equal -1, or that it is false that the wage does not equal -1, it will break the loop.

Instead, it seems the loop is requiring that all of those conditions are met to exit, where name == "-1" AND hours == -1 AND wage == -1, only then will it break.

Any insight would be appreciated. You guys rock!

like image 988
Matthew Ryan Avatar asked May 16 '26 01:05

Matthew Ryan


1 Answers

You have your understanding of the OR operator backwards. You're treating it like AND.

Instead of:

It is my understanding that when using the OR operator (||), if any of the conditions are found to be false, the loop breaks.

It's actually

If any of the conditions are found to be true, the loop continues.

To fix the problem you can rewrite your loop to be:

while (stringName !== "-1" && numHours !== -1 && numRate !== -1)

Also it is preferable to use !== instead of != because != does something weird called type coercion that can give you results you don't expect.

like image 53
m0meni Avatar answered May 17 '26 14:05

m0meni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!