JavaScript if/else Explained in Plain English

So far in our journey, we’ve built the skeleton of a webpage with HTML and styled it with CSS. Our page looks good, but it’s not “smart.” It can’t make decisions or react to changes. To do that, we need to use the third core language of the web: JavaScript.

If HTML is the skeleton and CSS is the clothes, JavaScript is the brain and nervous system. It’s what allows a webpage to be interactive.

In this guide, we’ll learn the most fundamental building block of programming logic: the if/else statement. This is how you tell your code: “If this condition is true, do this action. Otherwise, do that action.”

Setting Up Your First Script

Just like with CSS, we need to create a separate file for our JavaScript and link it to our HTML. This keeps our project organized.

Step 1: Create Your JavaScript File

  1. In your My First Website folder, create a new file.
  2. Save it as script.js.

You should now have three files: index.html, style.css, and script.js.

This is a crucial step. We need to tell our HTML file to load and run our JavaScript code. We do this by adding a <script> tag.

Important: Unlike the <link> tag for CSS which goes in the <head>, the <script> tag should go at the very bottom of your <body> section.

Why? Because we want the browser to load all the visible HTML content first. This ensures our JavaScript has elements to interact with and doesn’t slow down the initial page load.

Open your index.html file and add the <script> tag like so:

    ...
    <p>You can follow my progress on my (soon to be built) blog or find me on <a href="https://www.linkedin.com/">LinkedIn</a>.</p>

    <script src="script.js"></script>
  </body>
</html>

The Logic of “If”

Think about real life. You make if decisions constantly:

  • If I’m hungry, I will eat.
  • If it’s raining outside, I will take an umbrella.

JavaScript uses the exact same logic. The syntax looks like this:

if (condition) {
  // code to run if the condition is true
}

The condition inside the parentheses () must be something that results in either true or false.

Let’s Write Some Code

Open your script.js file. We’re going to write a simple program that checks if a person is old enough to vote.

// script.js

// Let's create a variable to hold an age.
// A variable is just a container for a piece of information.
let age = 20;

// Now, let's check if the age is 18 or greater.
// The >= operator means "greater than or equal to".
if (age >= 18) {
  // This code will only run if the condition (age >= 18) is true.
  console.log("You are old enough to vote!");
}

How to see the result?
The console.log() function is a developer’s best friend. It prints messages to the browser’s developer console.

  1. Save your script.js and index.html files.
  2. Open index.html in your browser.
  3. Right-click on the page and choose “Inspect”.
  4. A new panel will open. Click on the “Console” tab.

You should see the message “You are old enough to vote!” printed there. Now, try changing the age variable in your code to 15, save it, and refresh the browser. The message will be gone, because the condition is now false.

What if It’s False? Using else

This is where else comes in. It gives us an alternative path to run when the condition is false.

Let’s improve our code:

let age = 15;

if (age >= 18) {
  // Runs if the condition is true
  console.log("You are old enough to vote!");
} else {
  // Runs if the condition is false
  console.log("You are not yet old enough to vote.");
}

Now when you run this code with age set to 15, you’ll see the second message in the console.

Putting It All Together: A “Good Morning” Message

Let’s do something more practical. We’ll change the main <h1> on our webpage to say “Good Morning!” or “Good Day!” depending on the time.

Step 1: Add an ID to Your <h1>

First, we need a way for our JavaScript to uniquely identify the <h1> tag. We do this by giving it an id attribute in our index.html.

<h1 id="greeting">Your Name</h1>

Step 2: Write the JavaScript Logic

Now, replace all the code in your script.js with this:

// Get the current hour of the day (from 0 to 23)
const currentHour = new Date().getHours();

// Find the h1 element on our page using its ID
const greetingElement = document.getElementById("greeting");

// Now, let's set the message based on the time
if (currentHour < 12) {
  // If it's before 12 PM (noon)
  greetingElement.textContent = "Good Morning!";
} else {
  // If it's 12 PM or later
  greetingElement.textContent = "Good Day!";
}

Now, save the files and refresh your webpage. The main heading should have changed based on your local time! You’ve just made your first dynamic, “smart” webpage.

What’s Next? Repetition

You’ve learned how to make your code make a single decision. But what if you need to perform an action over and over again? For that, we need loops.

In our next guide, we’ll dive into the for loop, one of the most powerful tools for handling repetitive tasks in JavaScript. Stay tuned

Related posts

The Magic of Repetition: A Beginner’s Guide to the JavaScript for Loop

What is CSS? A Beginner’s Guide to Styling the Web

What is HTML? The Ultimate Beginner’s Guide to Building Your First Webpage

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Read More