Using AND/OR operators in ‘If’ statements with JavaScript.

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 evaluates to true for code to run. This involves using AND and OR operators. The AND operator in JavaScript is && and the OR operator in JavaScript is II (two vertical bar characters usually typed in by holding down Shift + the \ backslash key on the keyboard). The NOT operator is a single ! (exclamation mark) and is used to check if a boolean variable 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 /or 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 run 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.

Here is the HTML code:

<html>
    <head>
        <title>Using logical operators</title>
        <script src="script.js"></script>
    </head>
        
    <body>

    </body>
</html>

Here is the JavaScript code:

var spend = 150;
var premium = false;

/*
Logical operators:
    && means AND
    || means OR
*/

if(spend < 20 && premium == false){
    console.log("Shipping is $10");
}
else if((spend >= 20 && spend < 50) && premium == false){
    console.log("Discounted shipping is $7.50");
}
else if((spend >=50 && spend <100) && premium == false){
    console.log("Discounted shipping is $5");
}
else if(spend >= 100 || premium == true){
    console.log("Shipping is free!");
}

Next tutorial: Switch statements

Leave a Reply