In the continuing saga of operators, we need to discuss multiple conditions. Thus far, we have only compared two items, but what if we needed to compare more than two? We can do this with and (&&) and or (||). Here is how they work…

# And (&&)

If you wish to compare multiple items (more than two), you can use and if you need them all to be true. For example…

[code lang=”js”]

// Using && to compare multiples

var x = 5;

var y = 3;

if(x < 10 && y > 1){

// Do something

}

[/code]

In the aforementioned code, the condition statement reads, “If x is less than ten AND y is greater than 1″. Since x has a value of 5 and 5 is less than 10, this side of the equation is true. Since y has the value of 3 and 3 is greater than 1, that side of the equation is true. So you could say that it is true and true, thus true. What I am getting at is that by using &&, both sides of the equation have to be true or the entire statement is false…i.e. true AND true = true…true AND false = false. Here is a false example…

[code lang=”js”]

// Using && to compare multiples

var x = 5;

var y = 3;

if(x > 10 && y > 1){

// Do something

}

[/code]

Notice I switch the comparison operator on the left side of the equation. This would be false and because I am using &&, the entire equation would return false.

# OR (||)

An alternative is to use or (||). We designate or by using double pipes…||. By using the or operator, we can compare the two equations, but the big difference is how the condition statement returns true/false. As I stated above, both sides of the condition statement need to be true. If one piece is false the entire statement is false. With or (||), it can return true even if one side is false. Here is an example…

[code lang=”js”]

// Using || to compare multiples

var x = 5;

var y = 3;

if(x < 10 || y > 1){

// Do something

}

[/code]

As you can see, the left side of the equation is false, while the right side is true. By using the or operator, this condition statement would return true. We would read this statement as, “If x is less than ten OR y is greater than 1.”

Which one of these operators you select depends on the logic of your program and what you are trying to achieve. Note that you can even use more than two pieces. You could ‘chain’ together multiple equations within the condition statement and even mix-and-match the && and || operators.

Happy Coding!

Clay Hess