Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 6 - Logical Operators

Logic is the ordering that makes sense to our mind. When you are 10 and called a teenager it makes sense, but to be called "elderly", sounds strange. When you are asleep and your parents still call you, it makes sense, but to be asleep and awake at the same time does not.

This may sound like not a lot, but the truth is we do this kind of reasonning every time. Let's consider some common examples, is 4 less than 10. You may answer "yes". Is your business profitable? You may answer, Yes or No. Do you have your student ID card? you can answer, Yes or No. These statemens are called logical statements or propositions or conditions because we can answer them by YES or NO.

It's also possible to combine two or more propositions. For example, is 4 less than 10 OR 4 greater than 10? Let's decompose it:

  • is 4 less than 10? YES
  • is 4 greater than 10? NO
  • OR is called a connector or operator

The OR connects and creatse a relationship between the first part and the second of the question. It's like the operator you have when doing arithmetic. Example: 10 + 2; The + is an operator.

The operators used for logic checking in the JavaScript language are:

  • || meaning OR
  • && meaning AND
  • ! meaning NOT

Now let's see how to use them.

let isStudent = true;
let hasID = false;

if (isStudent && hasID) {
  console.log("You qualify for a student discount.");
} else {
  console.log("You do not qualify for a student discount.");
}
if(!hasID){
    console.log("You need your ID asap");
 }

Explanation:

Logical operators combine multiple conditions:

  • && (AND): All conditions must be true.
  • || (OR): At least one condition must be true.
  • ! (NOT): Negates a condition.

In the example:

Both isStudent and hasID variables must be true for the discount to apply.

Try your hand

1. Create a File:

Create a new file named lesson6-logical-operators.html.

2. Write the Code:

Copy and paste the following code into your file:

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lesson 6 - Logical Operators</title>
</head>
<body>
    <script>
        let isStudent = true;
        let hasID = false;

        if (isStudent && hasID) {
            console.log("You qualify for a student discount.");
        } else {
            console.log("You do not qualify for a student discount.");
        }
    </script>
</body>
</html>

3. Save the File:

Save the file in your folder.

4. Preview the File:

  • Open the file in your browser and access the developer console.
  • Observe the Output:
You do not qualify for a student discount.

5. Experiment

  • Change the values of isStudent and hasID to true or false and save the file.
  • Refresh the browser to see how the output changes based on the logical conditions.