if Statement

Introduction

The if statement is one of the most fundamental decision-making statements in JavaScript. It allows a program to execute a block of code only when a specified condition evaluates to true.

In real-world applications, programs constantly make decisions based on user input, API responses, database values, and business rules. The if statement provides the ability to control the flow of execution based on these conditions.

For automation engineers, the if statement is extensively used to validate UI elements, verify API responses, check test results, handle exceptions, and perform conditional actions in Selenium, Playwright, and API automation frameworks.


What is an if Statement?

An if statement evaluates a condition.

  • If the condition is true, the block of code inside the if statement executes.

  • If the condition is false, the block is skipped.

It is the simplest form of conditional statement in JavaScript.


Syntax

if (condition) {

    // Code to execute if condition is true

}

Flow of Execution

Start
   │
   ▼
Check Condition
   │
 ┌─┴─────────────┐
 │               │
True          False
 │               │
 ▼               ▼
Execute      Skip Block
 Code           │
   │            │
   └──────┬─────┘
          ▼
         End

Why Do We Use if Statements?

The if statement helps developers:

  • Make decisions in programs.

  • Execute code only when required.

  • Validate user input.

  • Handle different scenarios.

  • Improve application logic.


Basic Example

let age = 20;

if (age >= 18) {

    console.log("Eligible to vote.");

}

Output

Eligible to vote.

Since the condition is true, the message is displayed.


Condition Evaluates to False

let age = 15;

if (age >= 18) {

    console.log("Eligible to vote.");

}

Output

No Output

Since the condition is false, the code inside the if block is skipped.


Using Comparison Operators

let marks = 80;

if (marks > 50) {

    console.log("Test Passed");

}

Output

Test Passed

Using Equality Operator

let username = "admin";

if (username === "admin") {

    console.log("Administrator Login");

}

Output

Administrator Login

Using Logical Operators

let age = 25;
let citizen = true;

if (age >= 18 && citizen) {

    console.log("Eligible to vote");

}

Output

Eligible to vote

Checking Boolean Values

let isLoggedIn = true;

if (isLoggedIn) {

    console.log("Welcome User");

}

Output

Welcome User

Using Expressions

let number = 12;

if (number % 2 === 0) {

    console.log("Even Number");

}

Output

Even Number

Real-World Example

Suppose an online shopping website allows checkout only if the cart contains items.

let cartItems = 3;

if (cartItems > 0) {

    console.log("Proceed to Checkout");

}

Output

Proceed to Checkout

Another example:

let accountBalance = 5000;

if (accountBalance >= 1000) {

    console.log("Transaction Allowed");

}

Output

Transaction Allowed

Automation Testing Example

Automation engineers frequently use if statements to verify application behavior.

Example with Playwright:

const isVisible = await page.locator("#loginButton").isVisible();

if (isVisible) {

    console.log("Login button is visible.");

}

Output

Login button is visible.

Example with Selenium:

let pageTitle = await driver.getTitle();

if (pageTitle === "Dashboard") {

    console.log("Navigation Successful");

}

Output

Navigation Successful

Example with API Testing:

let statusCode = 200;

if (statusCode === 200) {

    console.log("API Request Successful");

}

Output

API Request Successful

Example with Form Validation:

let password = "admin123";

if (password.length >= 8) {

    console.log("Password is valid.");

}

Output

Password is valid.

Using Multiple Conditions

let username = "admin";
let password = "admin123";

if (username === "admin" && password === "admin123") {

    console.log("Login Successful");

}

Output

Login Successful

Truthy and Falsy Values

JavaScript automatically converts values into true or false when evaluating conditions.

Falsy Values

  • false

  • 0

  • "" (empty string)

  • null

  • undefined

  • NaN

Example:

let username = "";

if (username) {

    console.log("Username Entered");

}

Output

No Output

Because an empty string is a falsy value.


Truthy Values

Most other values are considered truthy.

let username = "John";

if (username) {

    console.log("Username Entered");

}

Output

Username Entered

Common Mistakes

Using Assignment Instead of Comparison

Incorrect:

let age = 18;

if (age = 20) {

    console.log("Eligible");

}

The assignment operator (=) changes the value of age instead of comparing it.

Correct:

if (age === 20) {

    console.log("Eligible");

}

Forgetting Curly Braces

Although JavaScript allows a single statement without braces, using braces improves readability.

Instead of:

if (age >= 18)
    console.log("Eligible");

Prefer:

if (age >= 18) {

    console.log("Eligible");

}

Comparing Different Data Types

Incorrect:

let age = "18";

if (age === 18) {

    console.log("Eligible");

}

The comparison is false because one value is a string and the other is a number.

Convert the value first if necessary.


Best Practices

Use Strict Equality (===)

Prefer:

if (status === 200)

Instead of:

if (status == 200)

Strict equality avoids unexpected type conversions.


Keep Conditions Simple

Avoid writing long and complex conditions.

Instead of:

if (a > 10 && b < 20 && c === true && d !== null)

Break complex logic into smaller, meaningful variables if needed.


Use Descriptive Variable Names

Instead of:

if (x)

Use:

if (isUserLoggedIn)

This makes the code easier to understand.


Add Comments for Complex Logic

If a condition involves complicated business rules, include a brief comment explaining the purpose.


Conclusion

The if statement is the foundation of decision-making in JavaScript. It enables programs to execute code only when specific conditions are met, making applications dynamic and interactive.

For automation engineers, if statements are essential for validating UI elements, verifying API responses, handling test scenarios, checking conditions before performing actions, and building reliable automation frameworks.


Frequently Asked Questions (FAQs)

What is an if statement in JavaScript?

An if statement is a conditional statement that executes a block of code only if a specified condition is true.


What is the syntax of an if statement?

if (condition) {

    // Code to execute

}

What happens if the condition is false?

The code inside the if block is skipped, and execution continues with the next statement.


Can an if statement contain multiple conditions?

Yes.

Example:

if (age >= 18 && citizen) {

    console.log("Eligible");

}

Why are if statements important in automation testing?

Automation engineers use if statements to validate UI elements, verify API responses, check test conditions, perform conditional actions, and handle different execution scenarios.


Key Takeaways

  • The if statement executes code only when a condition is true.

  • It is the simplest decision-making statement in JavaScript.

  • Conditions are written inside parentheses ().

  • Code blocks are enclosed in curly braces {}.

  • Comparison and logical operators are commonly used with if statements.

  • JavaScript evaluates truthy and falsy values in conditions.

  • Use strict equality (===) instead of loose equality (==) whenever possible.

  • Keep conditions simple and readable.

  • if statements are widely used in web development and automation testing.

  • Mastering the if statement is essential before learning if...else, switch, and loops.