Back to Blog
Lesson 6 of the JavaScript: From Zero to Interactive Web Pages course
JavaScriptJuly 17, 20264 min read

Introduction to Conditionals: Controlling Logic in JavaScript

Learn how to use if statements and comparison operators in JavaScript to make your code react dynamically to user input and application state.

javascriptprogrammingconditionalslogicweb-development
Close-up of colorful programming code displayed on a computer screen, showcasing modern coding concepts.

Previously in this course, we learned how to capture user input with browser dialogs, which allows us to get data from our users. However, simply capturing data isn't enough; to build a truly interactive dashboard, your program needs to "think" about that data. This lesson introduces the if statement, the fundamental tool for controlling your application's logic.

Understanding Logic with Comparison Operators

At its core, programming logic is about asking a question and getting a "yes" or "no" answer. In JavaScript, we use comparison operators to evaluate data and return a boolean (either true or false), which we covered in our guide to primitive data types.

Here are the most common operators you'll use to compare values:

OperatorDescriptionExample
===Strict Equality5 === 5 (true)
!==Strict Inequality5 !== 3 (true)
>Greater than10 > 5 (true)
<Less than2 < 8 (true)
>=Greater than or equal to5 >= 5 (true)

Note: Always use === instead of ==. The triple-equals checks both value and type, preventing common bugs where JavaScript accidentally converts your data types.

Writing Your First If Statement

Scrabble tiles spelling 'Own Your Error' on a white background.

An if statement allows you to execute a block of code only when a condition evaluates to true. Think of it as a gatekeeper: if the condition inside the parentheses is met, the code inside the curly braces runs. If not, the program simply skips it.

Here is the basic syntax:

JAVASCRIPT
if (condition) {
  // This code runs only if the condition is true
}

Worked Example: Basic Weather Logic

In our running project, we want to give the user a quick alert if it's hot outside. Let’s simulate capturing a temperature and checking it:

JAVASCRIPT
let currentTemp = 85;

if (currentTemp > 80) {
  console.log("ItCE9178">'s a hot day! Don't forget your water.");
}

console.log("Program execution continues...");

In this example, the engine evaluates 85 > 80. Since this is true, the browser logs the message about water. If currentTemp were 70, the engine would evaluate 70 > 80 as false, skip the console.log inside the braces, and proceed immediately to the next line.

Advancing the To-Do Dashboard

We are building a to-do and weather dashboard. Let's use our new logic to validate that a user actually typed something into their to-do list before we "add" it.

JAVASCRIPT
let taskInput = ""; // Imagine this comes from a prompt or input field

if (taskInput === "") {
  console.log("Error: You must enter a task!");
}

if (taskInput.length > 0) {
  console.log("Adding task to list...");
}

By checking the state of taskInput before acting, we prevent our application from adding empty items to our dashboard. This is a fundamental pattern for mastering logic testing foundations in any professional project.

Hands-on Exercise

Open your browser console and try the following:

  1. Declare a variable userAge and assign it a number.
  2. Write an if statement that checks if userAge is 18 or greater.
  3. If true, log "You are eligible to vote."
  4. Change the value of userAge to 16 and confirm that nothing is logged to the console.

Common Pitfalls

Close-up of a rusty sewer manhole cover in a grassy Boston park.

  • Assignment vs. Equality: A common mistake is using a single equals sign = (assignment) instead of === (comparison). if (x = 5) will actually set x to 5 and always result in true!
  • Missing Curly Braces: While JavaScript sometimes allows omitting {} for single-line statements, it is considered bad practice. Always use curly braces to keep your code readable and prevent bugs when you inevitably add more logic later.
  • Comparing Different Types: Always be mindful of whether you are comparing a string or a number. '5' === 5 is false because one is a string and the other is a number.

FAQ

Q: Can I put an if statement inside another if statement? Yes! This is called "nesting." You can have as many levels as you need, though keeping your code flat is usually better for readability.

Q: Does the computer care about whitespace? No, but you should. Proper indentation makes it clear which code belongs inside your if block.

Q: What happens if I make a typo in the variable name? JavaScript will throw a ReferenceError, and your script will stop running. Always check your console for errors if your logic isn't triggering.

Recap

Wooden Scrabble tiles spelling 'RECAP' on a brown textured background. Text concept image.

You’ve learned the building blocks of program flow:

  • Comparison operators return true or false.
  • if statements define paths for your code to take.
  • Conditional logic allows your dashboard to react to specific input, like preventing empty to-do items.

Up next, we will expand our control flow by learning how to handle the "otherwise" scenarios using else and else if statements.

Similar Posts