Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test if a variable does not equal either of two values?

People also ask

How do you find if a not equal condition in an if statement?

Equality operators: == and != The result type for these operators is bool . The equal-to operator ( == ) returns true if both operands have the same value; otherwise, it returns false . The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .

What is === operator in Javascript?

The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.

Can a variable have two values?

A variable holds more than one value if you declare it to be of a composite data type. Composite Data Types include structures, arrays, and classes. A variable of a composite data type can hold a combination of elementary data types and other composite types. Structures and classes can hold code as well as data.

How do you write not equal in Javascript condition?

The strict inequality operator ( !== ) checks whether its two operands are not equal, returning a Boolean result. Unlike the inequality operator, the strict inequality operator always considers operands of different types to be different.


Think of ! (negation operator) as "not", || (boolean-or operator) as "or" and && (boolean-and operator) as "and". See Operators and Operator Precedence.

Thus:

if(!(a || b)) {
  // means neither a nor b
}

However, using De Morgan's Law, it could be written as:

if(!a && !b) {
  // is not a and is not b
}

a and b above can be any expression (such as test == 'B' or whatever it needs to be).

Once again, if test == 'A' and test == 'B', are the expressions, note the expansion of the 1st form:

// if(!(a || b)) 
if(!((test == 'A') || (test == 'B')))
// or more simply, removing the inner parenthesis as
// || and && have a lower precedence than comparison and negation operators
if(!(test == 'A' || test == 'B'))
// and using DeMorgan's, we can turn this into
// this is the same as substituting into if(!a && !b)
if(!(test == 'A') && !(test == 'B'))
// and this can be simplified as !(x == y) is the same as (x != y)
if(test != 'A' && test != 'B')

ECMA2016 Shortest answer, specially good when checking againt multiple values:

if (!["A","B", ...].includes(test)) {}

In general it would be something like this:

if(test != "A" && test != "B")

You should probably read up on JavaScript logical operators.


I do that using jQuery

if ( 0 > $.inArray( test, [a,b] ) ) { ... }

var test = $("#test").val();
if (test != 'A' && test != 'B'){
    do stuff;
}
else {
    do other stuff;
}