Sling Academy
Home/JavaScript/Controlling Flow with Basic if and else Conditions in JavaScript

Controlling Flow with Basic if and else Conditions in JavaScript

Last updated: December 12, 2024

When you're learning to program in JavaScript, controlling the flow of your code is crucial. One of the fundamental ways to manage this control is by using if and else statements. These structures enable your program to assess conditions and execute code based on whether those conditions are met or not.

If Statement

The if statement is straightforward; it tests a condition and executes a block of code only when the condition evaluates to true. Let's see a basic example of how it works:

let temperature = 30;

if (temperature > 20) {
    console.log('It is warm outside.');
}

In this example, the condition is temperature > 20. If this condition is true, the program prints "It is warm outside." to the console.

Else Statement

An else statement can follow an if statement and will execute its block of code if the if statement's condition is false. Here’s how you can modify the previous example to handle both possible outcomes:

let temperature = 15;

if (temperature > 20) {
    console.log('It is warm outside.');
} else {
    console.log('It is chilly outside.');
}

Now, when temperature is set to 15, which does not satisfy the condition, "It is chilly outside." is logged instead.

Else If Statement

In some cases, you might want to test multiple conditions. This is where the else if statement comes in handy. You can include as many else if conditions as necessary, and JavaScript will check them sequentially:

let temperature = 18;

if (temperature > 30) {
    console.log('It is hot outside.');
} else if (temperature > 20) {
    console.log('It is pleasant outside.');
} else if (temperature > 10) {
    console.log('It is chilly outside.');
} else {
    console.log('It is cold outside.');
}

Here, the program tests each condition in sequence until it finds one that evaluates to true. Since temperature > 10 is true for our variable set to 18, it logs "It is chilly outside."

Nesting Conditions

It’s also common to nest conditions within each other to create complex logical structures. For example, consider writing a program that categorizes forest areas based on temperature and humidity:

let temperature = 25;
let humidity = 70;

if (temperature >= 25) {
    if (humidity >= 60) {
        console.log('Tropical forest conditions.');
    } else {
        console.log('Dry forest conditions.');
    }
} else {
    if (humidity >= 60) {
        console.log('Cool forest with high humidity.');
    } else {
        console.log('Temperate and dry forest.');
    }
}

This program uses nested if statements to deliver a more nuanced condition evaluation, providing distinct results based on complex interrelated criteria.

Boolean Logic and Comparisons

To elevate your script logic, you may use comparison operators in combination with boolean logic (such as AND && and OR ||) to build more elaborate conditions. For instance:

let age = 45;

if (age >= 18 && age < 60) {
    console.log('You are an adult.');
} else {
    console.log('You are not in the adult age group.');
}

This code checks if the age falls within the adult range. The && operator ensures both conditions must be true for the result to be executed as true.

Master these basic yet powerful conditional structures and boost your JavaScript programming skills by effectively controlling the flow and making your code more dynamic and interactive.

Next Article: Managing Complex Logic Branches Using Nested if Statements in JavaScript

Previous Article: JavaScript: Define a Function with Default Parameters

Series: Mastering Control Flow in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration