Submodule 6.2: Making Decisions

  • Comparison operators
  • If statements
  • Logical operators

Logical operators

Logical operators are typically used together with logic (true/false) values.

These operators are very helpful when we want to do something based on the value of more than one variables.

In the below example, we have the variables x and y which are 6 and 3 respectively. The first console.log is : 

console.log( (x < 5 && y > 2) );

The && operator used says that this will be true only if both 6<3 and 3>2. Else, if none or only one of them is true, it returns false.

If instead of && we have used ||, then the console.log will return true if one of these expressions is true even if the other expression is false.

Lastly, the ! operator returns true if our expression is false. In case of 6<3, if we use the ! we will have : !6<3. This actually says: If 6 is NOT smaller than 3 then return true.

Operator   Description
&&           logical and : returns true if both operands are true
||           logical or : returns true if either operand is true
!            logical not : returns false if its single operand can be converted to true; otherwise, returns true.
Example
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Logical operators </title>
  </head>
  <body>
    <h3> Logical operators </h3>
    <script>
        var x = 6;
        var y = 3;
        console.log( (x < 5 && y > 2) );
        console.log( (x < 5 || y > 2) );
        console.log( !(x < 5 || y > 2) );
    </script>
  </body>
</html>

Exercise

  1. Open your editor, create a new file and save it as exersice06.2.05logical.html in the folder "yourNameWEB2JS".
  2. Copy the above code and paste it into the new file.
  3. Save the file and preview it in your console.
  4. Experiment by adding new statements.