Using And/Or Operators in If Statements

Using logical operators such as and/or allow a programmer to write complex if statements. For example, you can check if a number is greater than 10 AND is also less than 20 (both conditions have to evaluate to true for the code to run inside the if statement). Or, you can check if a number is less than 5 OR greater than 10 (only one condition has to evaluate to true for the code to run inside the if statement)

Logical operators:

  • The symbols && are used for the and operator in JavaScript
  • The || symbols are used for the or operator in JavaScript
  • A single exclamation mark ! can also be used as a not operator.

Check out the sample code below to see how these logical operators can be used to form complex if statements in JavaScript, and make sure you also watch the accompanying video here.

<!DOCTYPE html>
<html lang="en"
 <meta charset="utf-8"/>
 <title>JavaScript - Nesting If Statements</title>
 <script type="text/javascript">
 // This is a better way than using nested if statements
 // You can use and/or operators in JS (known as logical operators)
 // The AND operator is &&
 // The OR operator is ||
 var firstName = "John";
 var lastName = "Smith";
 if(firstName=="John" && lastName=="Smith"){
 document.write("Hello, John Smith!");
 // The message above will only be displayed if firstName is John AND lastName is Smith.
 // Try using || instead of && and change the value of one of the variables. What happens?