KrankyCode
KrankyCode

Reputation: 451

What is the correct Syntax for "OR" condition inside "IF".?

Have an if condition like below

if ((listbox != "lhs") || (listbox != "prevnext"))

This is failing even when listbox is "lhs" or "prevnext" string.

Tried even below syntax but its failing

if ((listbox != "lhs" || listbox != "prevnext"))

Not sure of correct syntax for above condition.

Upvotes: 1

Views: 341

Answers (3)

Jaromanda X
Jaromanda X

Reputation: 1

if ((listbox != "lhs") || (listbox != "prevnext"))

This statement will always be true - because listbox will never equal both values

sorry I may have confused some people by not posting an answer ... @Light has a solution (the first snippet, the second snippet is clearly identical to the question without inner brackets)

some people just need that facepalm moment to realise the answer themselves

I'd use

if ((listbox != "lhs") && (listbox != "prevnext"))

if listbox="fred" ...

if (("fred" != "lhs") && ("fred" != "prevnext"))
           true       &&        true              result = true

if listbox="lhs" ...

if (("lhs" != "lhs") && ("lhs" != "prevnext"))
           false     &&        true              result = false

if listbox="prevnext" ...

if (("lhs" != "lhs") && ("lhs" != "prevnext"))
           true      &&        false             result = false

looks right to me

Upvotes: 6

ralh
ralh

Reputation: 2574

(listbox != "lhs" || listbox != "prevnext")

Always true - listbox can't be both lhs and prevnext at the same time, so it always IS NOT at least one of those values.

(listbox == "lhs" || listbox == "prevnext")

then:

listbox = 'lhs' // => true
listbox = 'prevnext' // => true
listbox = 'anything_else' // => false

True if listbox is lhs or prevnext.

(listbox != "lhs" && listbox != "prevnext")

then:

listbox = 'lhs' // => false
listbox = 'prevnext' // => false
listbox = 'anything_else' // => true

True if listbox is neither 'lhs', nor 'prevnext'.

(listbox == "lhs" && listbox == "prevnext")

For completeness - always false - listbox can't be equal to two values simultaneously.

Upvotes: 0

Light
Light

Reputation: 1097

Try

if (!(listbox == 'lhs' || listbox == 'prevnext')) {

or

if (listbox   != 'lhs' || listbox != 'prevnext') {

Upvotes: 0

Related Questions