And it is a great thing to practice with complex expressions like that. They take some getting used to. As @Johongirmirzo mentioned, the way the logical OR (||) or the logical AND (&&) evaluate can take some getting used to.
In the case of the logical or statement, which might look like this:
if (userName.length < 8 || userName.toLowerCase().indexOf('john') !== -1 || password.length < 8 ){...}
… each piece is evaluated, left to right, until the first TRUE evaluation occurs. So if userName = john and password = foo|3bar, then the first simple expression, userName.length < 8, will return false, causing the next expression to be evaluated. In our case, userName.toLowerCase().indexOf('john') would NOT be equal to -1 (which says that ‘john’ is in our userName), and that expression would evaluate to true. When that happens, then the entire complex expression reads as true, and the if statement is processed.
In the case of a logical and statement, like
if ( userName.toLowerCase().indexOf('john') !== -1 && password.toLowerCase().indexOf('john') === -1 && password.length < 8 )
… it will also evaluate, left to right, each simple expression. This time, though, the statement will return false for the FIRST FALSE we encounter. If we again had userName = 'john' and `password = ‘13John47aC’, just to be funky, what would happen?
-
userName.toLowerCase().indexOf('john') is NOT equal to -1, so that would be true. The complex expression would continue to test.
-
password.toLowerCase().indexOf('john') **is NOT** equal to -1 (the wordjohnis in the password), so this would returnfalse`. As soon as the if statement encountered this, the entire expression is read as false. The if statement will not execute.
- In our case, the third option wouldn’t even be hit. At this point, it wouldn’t matter. True or false for that one, the entire expression has already read as
false.
Note, too, that you can group them:
if (userName.length > 8 || password.length > 8 && Number(userAge) > 18 ) {...}
But the order of operations becomes a thing. The AND is tested before the OR, and if the AND evaluates as true, then the whole thing is true.
To read more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators