Javascript in 100 bits

Course by zooboole,

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

Lesson 5 - Conditional Statements

When you write computer program, just like when we think, we tend to put in conditions. The satisfaction or not of these conditions define what step or action to take next. As an example, we usually say things like, "If I get some time tomorrow, I will give you a call. Otherewise, I will send you the parcel via the post".

The same thing can be achieved when we write programs using the JavaScript language. Let's learn how it's done.

let age = 18;

if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}

Explanation:

Conditional statements allow you to make decisions in your code. The if statement checks if a condition is true. If the condition is false, the else block will execute.

Try your hand:

1. Create a File:

Create a new file named lesson5-conditionals.html.

2. Write the Code:

Copy and paste the following code into the file. At this point I will suggest you type this code to get used to it.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Lesson 5 - Conditional Statements</title>
</head>
<body>
    <script>
        let age = 18;

        if (age >= 18) {
            console.log("You are an adult.");
        } else {
            console.log("You are a minor.");
        }
    </script>
</body>
</html>

Save the file in your folder.

3. Preview the File:

  • Open the file in your browser (e.g., Chrome or Firefox). You can double-click on it or right-click -> open with... -> choose your browser
  • Press Ctrl + Shift + J (Windows) or Cmd + Option + J (Mac) to open the browser's developer console.

Experiment:

  • Change the value of age to a number less than 18 and save the file.
  • Refresh the browser to see the updated result.