Logical operators
Coding with JavaScript
🕑 This lesson will take about 10 minutes
You can specify more than one condition in an if statement. You can specify whether several conditions must all evaluate to true for some instructions in your code to run, or whether at least one of several conditions needs to evaluate to true for the code to run. This involves using logical operators known as the && (and) and || (or) operators. The && operator in JavaScript means AND, and the || operator in JavaScript means OR (the | character can usually be found by holding down Shift + the \ backslash key on the keyboard). The ! (exclamation mark) operator means NOT (exclamation mark) and is used to check if a boolean value is false. These are all examples of logical operators.
Logical operators:
&& means AND
|| means OR
! means NOT
Watch the video below and then scroll down to view the examples in the code.
After watching the video, let’s recap what logical operators are all about. Using logical operators such as && and || allow a programmer to write if statements where more than one condition can be tested at once. 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 execute inside the if statement).
Check out the sample code below to see how these logical operators can be used to form if statements in JavaScript.
Sample HTML and JavaScript code
Next lesson: Switch statements