JAVASCRIPT

JavaScript If Statement: Syntax, Usage, and Examples

In JavaScript, an if statement is a control structure that executes (or skips) blocks of code based on specified conditions.

How to Use the If Statement in JavaScript

JavaScript If Statement

The syntax for the if statement in JavaScript involves the if keyword followed by a condition enclosed in parentheses and a block of code enclosed in curly braces that executes if the condition is true.

if (condition) {
    // Code to execute if condition is true
}
  • if: The keyword that initiates an if statement.
  • condition: A boolean expression to evaluate to true or false. If the condition evaluates to true, the if statement’s body executes. If the condition evaluates to false, the if statement’s body gets skipped.

JavaScript If-Else Statement

You can expand the if statement to include an else clause. An if-else statement’s else block executes if the condition evaluates to false.

if (condition) {
    // Code executes if condition is true
} else {
    // Code executes if condition is false
}
  • if: The keyword that initiates an if statement.
  • condition: A boolean expression to evaluate to true or false.
  • else: The keyword that initiates an else clause.

JavaScript If-Else-If-Else Statements

Finally, an if statement can also include else if and a condition in parentheses to check for another condition. As soon as a condition evaluates to true, the block of code below the condition executes.

A conditional statement can have an infinite number of else if clauses. The else clause at the end executes if none of the conditions evaluate to true.

if (condition) {
    // Code executes if condition is true
} else if (anotherCondition) {
    // Code executes if the first condition is false and another condition is true
} else {
    // Code executes if all conditions are false
}
  • if: The keyword that initiates an if statement.
  • condition: A boolean expression to evaluate to true or false.
  • else if: The keywords that initiate an else if clause.
  • anotherCondition: A boolean expression to evaluate to true or false if the previous condition evaluated to false.
  • else: The keyword that initiates an else clause.

When to Use the If Statement in JavaScript

If statements and other conditional statements are useful whenever you need to make decisions based on conditions. This decision-making capability is key to creating dynamic and interactive applications in JavaScript.

Making Decisions

You can use a conditional statement to decide which code to execute based on dynamic conditions at runtime.

let hour = new Date().getHours();
if (hour < 12) {
    console.log("Good morning!");
} else {
    console.log("Good day!");
}

Handling User Input

Also, you can use a conditional statement to validate user input, checking for correctness or completeness before processing.

let email = "user@example.com";
if (email.includes("@")) {
    console.log("Email is valid.");
} else {
    console.log("Please enter a valid email.");
}

Handling Scenarios

If statements enable programs to handle different scenarios, like the success or failure of an operation.

// Handling success or failure
let operationSuccessful = false
if (operationSuccessful) {
    console.log("The operation was successful.");
} else {
    console.log("The operation failed.");
}

Examples of the If Statement in JavaScript

Here are some examples of real-world scenarios for using a conditional statement:

Age Checks

A video platform might use an if statement to check a user’s age and recommend age-appropriate content.

let age = 20;
if (age >= 18) {
    showAdultContent();
} else {
    showChildContent();
}

Feature Toggling

An application like Mimo might use if statements to control the visibility or functionality of features in applications. Feature toggles are especially useful during development or for A/B testing.

let featureEnabled = true;
if (featureEnabled) {
    console.log("New feature is now available.");
} else {
    console.log("Feature is currently disabled.");
}

Login Processes

Applications with user accounts might use conditional statements to authenticate users. This typically involves comparing a stored password hash with the hashed user input.

// Authenticating a user
let storedPasswordHash = "5994471abb01112afcc18159f6cc74b4f511b99806da59b3caf5a9c173cacfc5";  // Example hash
let inputPassword = "12345";

if (hashFunction(inputPassword) === storedPasswordHash) {
    console.log("Access granted.");
} else {
    console.log("Access denied. Incorrect password.");
}

Learn More About the If Statement in JavaScript

Nested If Statements and Nested If-Else Statements

Nested if statements and nested if-else statements provide a way to make more detailed checks. Nesting conditional statements is useful when decisions need several layers of logic.

let score = 85;
if (score >= 50) {
    if (score >= 80) {
        console.log("Grade: A");
    } else {
        console.log("Grade: B");
    }
} else {
    console.log("Failed");
}

Logical Operators and Multiple Conditions

In JavaScript, combining multiple conditions within an if statement is often necessary to handle complex decision-making processes. Often, logical operators such as && (and), || (or), and ! (not) can help evaluate multiple boolean expressions in a single line.

let temperature = 30, sunny = true;
if (temperature > 25 && sunny) {
    console.log("Let's go to the beach!");
} else {
    console.log("It's not a good day for the beach.");
}

Short-circuit Evaluation

In JavaScript, short-circuit evaluation utilizes logical operators to check conditions more efficiently. This technique stops the evaluation of expressions as soon as the outcome is clear, optimizing performance.

let loggedIn = true;
if (loggedIn && user.hasAccess()) {
    console.log("User has access.");
} else {
    console.log("Access denied.");
}

Conditional (Ternary) Operator

The conditional (ternary) operator is a concise way to express simple if-else statements. It takes requires a condition followed by a question mark (?), the expression to execute if the condition is true, and a colon (:) followed by the expression to execute if the condition is false.

let age = 20;
let status = (age >= 18) ? "adult" : "minor";
console.log(status);
Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2023 Mimo GmbH