Chapter 14: Mastering Conditions, Math and Control Flow in JavaScript

Chapter 14: Mastering Conditions, Math and Control Flow in JavaScript

Table of contents

Introduction

In programming, decision-making is a cornerstone of writing dynamic and responsive applications. JavaScript, being a versatile and widely-used language, provides a variety of tools to handle conditions and control the flow of logic in your code.

This chapter will take you on a comprehensive journey through conditional statements and control flow mechanisms in JavaScript. From the basics of if-else constructs to more advanced tools like switch cases and ternary operators, we will cover it all with detailed explanations, practical examples, and real-world applications.

But before diving deep into conditions, we’ll take a brief detour to explore foundational concepts like arrays, objects, and dates, which often play a pivotal role in decision-making processes. Additionally, you’ll learn about JavaScript's Math utilities and various looping constructs to manage repetitive tasks effectively.

By the end of this chapter, you will:

  • Understand how to use if-else, switch, and ternary operators effectively.

  • Develop logic for dynamic applications using arrays and objects.

  • Master the art of working with dates, math operations, and loops for conditional logic.

Whether you are building a simple weather app or managing user authentication in a complex system, the knowledge in this chapter will provide the foundation for handling decisions with confidence and precision in JavaScript.

Let’s get started! 🚀

Introduction to Conditional Statements in JavaScript

Conditional statements are the backbone of decision-making in programming. They enable developers to execute specific blocks of code based on whether a given condition evaluates to true or false. Without them, programs would have to run sequentially without any logical branching, which is often impractical in real-world scenarios.

In JavaScript, conditional statements allow us to control the flow of our program dynamically. This flexibility is achieved using constructs like if, if-else, else-if, switch, and ternary operators.


Why Are Conditional Statements Important?

  1. Decision-Making: Conditional statements help the program decide which path to take based on user input, data, or events. For instance:

    • Redirecting users based on their roles (e.g., Admin, Guest).

    • Showing personalized content or offers.

  2. Error Handling: Conditions are essential for validating input or handling exceptions.

  3. Logic Implementation: Every logic-heavy application—from e-commerce platforms to games—relies heavily on conditions.

  4. Dynamic User Interactions: Conditional statements are pivotal in providing responsive and adaptive user experiences.


Types of Conditional Statements in JavaScript

JavaScript offers a variety of conditional constructs to handle different use cases:

  1. If Statements:
    Used to execute code only when a specific condition is true.

  2. If-Else Statements:
    Provides an alternative code block to run when the condition is false.

  3. Else-If Statements:
    Allows checking multiple conditions sequentially.

  4. Switch Statements:
    Simplifies the process of comparing a variable against multiple values.

  5. Ternary Operator:
    A concise, one-line alternative for simple conditional expressions.


How Conditional Statements Work

At the heart of conditional statements is the concept of boolean logic. JavaScript evaluates conditions to true or false:

  • Truthy Values: Any value considered true in a logical context, such as non-zero numbers, non-empty strings, objects, and arrays.

  • Falsy Values: Values like 0, "", null, undefined, NaN, and false.

Example of Truthy and Falsy Evaluation:

if (1) {
    console.log("This will run because 1 is truthy.");
}

if (0) {
    console.log("This will not run because 0 is falsy.");
}

The Anatomy of a Conditional Statement

1. If Statement

The if statement checks a condition and executes the block of code inside it if the condition evaluates to true.

Syntax:

if (condition) {
    // Code to execute if the condition is true
}

Example:

let age = 18;
if (age >= 18) {
    console.log("You are eligible to vote.");
}

2. If-Else Statement

The if-else statement provides an alternative code block for when the condition is false.

Syntax:

if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}

Example:

let temperature = 30;
if (temperature > 25) {
    console.log("It's hot outside.");
} else {
    console.log("It's cool outside.");
}

3. Else-If Statement

The else-if statement lets you evaluate multiple conditions sequentially.

Syntax:

if (condition1) {
    // Code for condition1
} else if (condition2) {
    // Code for condition2
} else {
    // Default code if no conditions match
}

Example:

let rating = 3;
if (rating === 5) {
    console.log("Excellent");
} else if (rating === 4) {
    console.log("Good");
} else if (rating === 3) {
    console.log("Average");
} else {
    console.log("Poor");
}

Comparison Operators in Conditional Statements

Conditional statements often rely on comparison operators. Here's a list of commonly used operators:

OperatorDescriptionExampleOutput
==Equal to5 == "5"true
===Strict equal to5 === "5"false
!=Not equal to5 != "6"true
!==Strict not equal to5 !== "5"true
>Greater than5 > 3true
<Less than5 < 3false
>=Greater than or equal to5 >= 5true
<=Less than or equal to5 <= 3false

Logical Operators in Conditions

Logical operators combine multiple conditions for complex decision-making.

OperatorDescriptionExampleOutput
&&Logical ANDtrue && falsefalse
``Logical OR
!Logical NOT!truefalse

Example:

let isAdult = true;
let hasID = true;

if (isAdult && hasID) {
    console.log("You can enter the club.");
} else {
    console.log("Access denied.");
}

2. Switch Case in JavaScript

The switch statement is a control-flow construct used to handle multiple conditions based on the value of a single variable. It acts as an alternative to chaining multiple if-else statements and is often more readable and efficient in scenarios where you compare a variable against multiple values.


When to Use Switch Statements?

  • When you have multiple values to compare.

  • When all comparisons are based on a single variable or expression.

  • When you want to improve readability and reduce the complexity of nested if-else chains.


Syntax of Switch Case

switch (expression) {
    case value1:
        // Code to execute if expression === value1
        break;

    case value2:
        // Code to execute if expression === value2
        break;

    default:
        // Code to execute if no cases match
}
  • expression: The value to be tested against the cases.

  • case value: A condition to match the expression.

  • break: Terminates the current case to prevent "fall-through."

  • default: An optional block that executes when no cases match.


Example 1: Basic Switch Statement

let day = 2;

switch (day) {
    case 1:
        console.log("Monday");
        break;

    case 2:
        console.log("Tuesday");
        break;

    case 3:
        console.log("Wednesday");
        break;

    default:
        console.log("Invalid day");
}

Output:

Tuesday
  • Here, the value of day is compared against each case.

  • When day === 2, the corresponding block runs, and the break prevents further execution.


Example 2: Handling Multiple Cases

You can group cases together to handle multiple values with the same logic.

let fruit = "apple";

switch (fruit) {
    case "apple":
    case "banana":
    case "orange":
        console.log("Fruit is available.");
        break;

    default:
        console.log("Fruit is unavailable.");
}

Output:

Fruit is available.

Here, the code handles all three fruits (apple, banana, orange) similarly.


Example 3: Fall-Through Behavior

When break is omitted, the execution "falls through" to the next case(s).

let level = 1;

switch (level) {
    case 1:
        console.log("Beginner");
    case 2:
        console.log("Intermediate");
    case 3:
        console.log("Advanced");
        break;

    default:
        console.log("Invalid level");
}

Output:

Beginner
Intermediate
Advanced

Without a break after case 1, all subsequent cases execute until the break or default.


Example 4: Using Default

The default block runs when no case matches the expression.

let role = "viewer";

switch (role) {
    case "admin":
        console.log("Redirect to Admin Dashboard.");
        break;

    case "editor":
        console.log("Redirect to Editor Page.");
        break;

    default:
        console.log("Redirect to Home Page.");
}

Output:

Redirect to Home Page.

3. Ternary Operators in JavaScript

The ternary operator is a concise way to write conditional statements in JavaScript. It's often used as a shorter alternative to if-else for simple conditions.


When to Use Ternary Operators?

  • When you need a compact syntax for simple conditions.

  • When readability won't suffer due to the shorthand notation.

  • For assigning values based on conditions or inline logic.


Syntax of Ternary Operator

condition ? expression1 : expression2;
  • condition: A boolean expression to evaluate.

  • expression1: The code or value to execute if the condition is true.

  • expression2: The code or value to execute if the condition is false.


Example 1: Basic Usage

let age = 20;
let canVote = age >= 18 ? "Yes, you can vote." : "No, you cannot vote.";
console.log(canVote);

Output:

Yes, you can vote.

Here, the ternary operator checks if age is greater than or equal to 18. If true, it assigns "Yes, you can vote." to canVote; otherwise, it assigns "No, you cannot vote.".


Example 2: Inline Logging

let isRaining = true;
console.log(isRaining ? "Bring an umbrella." : "Enjoy the sunshine!");

Output:

Bring an umbrella.

Example 3: Nested Ternary Operators

You can nest ternary operators for multiple conditions, but be cautious as this can reduce readability.

let score = 85;

let grade = score >= 90
    ? "A"
    : score >= 80
    ? "B"
    : score >= 70
    ? "C"
    : "F";

console.log(`Your grade is: ${grade}`);

Output:

Your grade is: B

Example 4: Assigning Default Values

The ternary operator can assign a default value based on a condition.

let username = null;
let displayName = username ? username : "Guest";
console.log(displayName);

Output:

Guest

Here, if username is falsy (e.g., null), "Guest" is assigned to displayName.


Comparison: Ternary Operator vs. If-Else

Using If-Else:

let age = 16;
let status;

if (age >= 18) {
    status = "Adult";
} else {
    status = "Minor";
}
console.log(status);

Using Ternary:

let age = 16;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status);

Both achieve the same result, but the ternary operator provides a more concise alternative.


Best Practices for Ternary Operators

  1. Avoid Nesting:
    Nested ternaries can become difficult to read. Use if-else for complex conditions.

  2. Maintain Readability:
    Ensure the condition and expressions are straightforward.

  3. Use for Short Logic:
    Limit ternary operators to scenarios where they enhance clarity.


Conclusion

Both switch cases and ternary operators are powerful tools for handling conditional logic in JavaScript.

  • Switch statements shine when dealing with multiple cases for a single variable.

  • Ternary operators are best for concise and straightforward conditions.

6. Working with Dates in JavaScript

JavaScript provides a built-in Date object that allows you to work with dates and times easily. It supports creating, manipulating, and formatting dates, making it a powerful tool for handling time-related operations.


Creating a Date Object

The Date object can be created in several ways:

1. Current Date and Time

const now = new Date();
console.log(now); // Outputs the current date and time

2. Specific Date

You can specify the year, month (0-based), day, hours, minutes, seconds, and milliseconds.

const specificDate = new Date(2025, 0, 4, 10, 30, 0);
console.log(specificDate); // Outputs: Sat Jan 04 2025 10:30:00

3. From a Date String

const fromString = new Date("2025-01-04T10:30:00");
console.log(fromString); // Outputs: Sat Jan 04 2025 10:30:00

4. From Milliseconds

The Date object can also be created from the number of milliseconds since January 1, 1970 (Unix Epoch).

const fromMilliseconds = new Date(1672527600000);
console.log(fromMilliseconds); // Outputs a date based on the timestamp

Date Methods

Once a Date object is created, you can use various methods to get or set specific parts of the date.

1. Getting Components of a Date

const now = new Date();
console.log(now.getFullYear()); // Year (e.g., 2025)
console.log(now.getMonth()); // Month (0-11, where 0 is January)
console.log(now.getDate()); // Day of the month (1-31)
console.log(now.getDay()); // Day of the week (0-6, where 0 is Sunday)
console.log(now.getHours()); // Hours (0-23)
console.log(now.getMinutes()); // Minutes (0-59)
console.log(now.getSeconds()); // Seconds (0-59)
console.log(now.getMilliseconds()); // Milliseconds (0-999)
console.log(now.getTime()); // Timestamp in milliseconds since Unix Epoch

2. Setting Components of a Date

You can modify the date and time using setter methods:

const myDate = new Date();
myDate.setFullYear(2030);
myDate.setMonth(5); // June (0-based)
myDate.setDate(15);
myDate.setHours(14);
myDate.setMinutes(45);
console.log(myDate); // Outputs the updated date and time

Formatting Dates

Formatting dates often requires breaking them into components and combining them as needed.

Example: Custom Date Formatting

const date = new Date();
const formattedDate = `${date.getDate()}-${date.getMonth() + 1}-${date.getFullYear()}`;
console.log(formattedDate); // Outputs: 4-1-2025

Performing Calculations with Dates

1. Adding Days to a Date

const date = new Date();
date.setDate(date.getDate() + 7);
console.log(date); // Outputs a date 7 days from now

2. Difference Between Two Dates

const date1 = new Date("2025-01-01");
const date2 = new Date("2025-01-10");
const difference = (date2 - date1) / (1000 * 60 * 60 * 24); // Convert milliseconds to days
console.log(difference); // Outputs: 9

7. Math Operations in JavaScript

JavaScript’s Math object provides methods and properties for performing mathematical operations. From basic arithmetic to advanced calculations, Math simplifies working with numbers.


Math Constants

  • Math.PI – The value of π (approximately 3.14159).

  • Math.E – The base of natural logarithms (approximately 2.718).

console.log(Math.PI); // 3.141592653589793
console.log(Math.E);  // 2.718281828459045

Basic Math Methods

1. Rounding Numbers

  • Math.round(x) – Rounds to the nearest integer.

  • Math.floor(x) – Rounds down to the nearest integer.

  • Math.ceil(x) – Rounds up to the nearest integer.

console.log(Math.round(4.7)); // 5
console.log(Math.floor(4.7)); // 4
console.log(Math.ceil(4.1)); // 5

2. Absolute Value

  • Math.abs(x) – Returns the absolute value.
console.log(Math.abs(-42)); // 42

3. Power and Roots

  • Math.pow(base, exponent) – Calculates the base raised to the power of the exponent.

  • Math.sqrt(x) – Calculates the square root.

console.log(Math.pow(2, 3)); // 8
console.log(Math.sqrt(16)); // 4

Advanced Math Methods

1. Trigonometric Functions

  • Math.sin(x), Math.cos(x), Math.tan(x) – Calculate the sine, cosine, and tangent.
console.log(Math.sin(Math.PI / 2)); // 1
console.log(Math.cos(0));          // 1

2. Logarithmic Functions

  • Math.log(x) – Returns the natural logarithm (base e).

  • Math.log10(x) – Returns the base-10 logarithm.

console.log(Math.log(Math.E));   // 1
console.log(Math.log10(1000));   // 3

3. Random Numbers

  • Math.random() – Generates a random number between 0 (inclusive) and 1 (exclusive).
console.log(Math.random());        // Random number (e.g., 0.534)
console.log(Math.random() * 10);   // Random number between 0 and 10
console.log(Math.floor(Math.random() * 10)); // Random integer between 0 and 9

Finding Minimum and Maximum

  • Math.min(a, b, ...) – Finds the smallest value.

  • Math.max(a, b, ...) – Finds the largest value.

console.log(Math.min(3, 5, 1, 9)); // 1
console.log(Math.max(3, 5, 1, 9)); // 9

Combining Math Operations

Example: Calculate Hypotenuse

Use the Pythagorean theorem (c=a2+b2c = \sqrt{a^2 + b^2}):

let a = 3, b = 4;
let c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
console.log(c); // Outputs: 5

Example: Generate a Random Integer in a Range

let min = 1, max = 10;
let randomInt = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomInt); // Outputs a random integer between 1 and 10

Conclusion

  • The Date object is essential for working with time-related data in JavaScript, allowing you to manipulate and format dates easily.

  • The Math object provides robust tools for calculations, from rounding and logarithms to random number generation and trigonometric operations.

Loops in JavaScript

Loops are a fundamental programming construct used to execute a block of code repeatedly based on a specific condition. They help automate repetitive tasks, making your code more efficient and concise. JavaScript provides several types of loops, each suited for different use cases.


Why Use Loops?

  1. Automation: Perform repetitive tasks without writing the same code multiple times.

  2. Dynamic Iteration: Process arrays, objects, or data structures dynamically.

  3. Conditional Execution: Repeat code as long as a condition is true.


Expanding on for and while Loops in JavaScript

1. for Loop

The for loop is a versatile and commonly used looping structure in JavaScript. It allows you to repeat a block of code a specific number of times by explicitly defining the initialization, condition, and increment or decrement in a single statement.


Structure of a for Loop

for (initialization; condition; increment/decrement) {
    // Code to execute
}
  • Initialization: This is where you initialize a variable (usually a counter). It runs only once, at the beginning of the loop.

  • Condition: This is a boolean expression. The loop executes as long as this condition is true.

  • Increment/Decrement: This updates the loop variable after each iteration.


Basic Example: Counting from 1 to 5

for (let i = 1; i <= 5; i++) {
    console.log(`Current number: ${i}`);
}

Output:

Current number: 1
Current number: 2
Current number: 3
Current number: 4
Current number: 5

Example: Printing Squares

for (let i = 1; i <= 5; i++) {
    console.log(`${i} squared is ${i * i}`);
}

Output:

1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25

Iterating Through an Array

The for loop is commonly used to traverse arrays, where you can access each element using its index.

const fruits = ["Apple", "Banana", "Cherry", "Mango"];
for (let i = 0; i < fruits.length; i++) {
    console.log(`Fruit at index ${i}: ${fruits[i]}`);
}

Output:

Fruit at index 0: Apple
Fruit at index 1: Banana
Fruit at index 2: Cherry
Fruit at index 3: Mango

Nested for Loops

A for loop inside another for loop is useful for working with multidimensional data, like matrices.

for (let i = 1; i <= 3; i++) {
    for (let j = 1; j <= 3; j++) {
        console.log(`i: ${i}, j: ${j}`);
    }
}

Output:

i: 1, j: 1
i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
i: 2, j: 2
i: 2, j: 3
i: 3, j: 1
i: 3, j: 2
i: 3, j: 3

Example: Multiplication Table

for (let i = 1; i <= 5; i++) {
    for (let j = 1; j <= 10; j++) {
        console.log(`${i} x ${j} = ${i * j}`);
    }
    console.log("---");
}

Advanced Techniques with for Loops

Skipping Iterations with continue

for (let i = 1; i <= 5; i++) {
    if (i === 3) {
        continue; // Skip iteration when i is 3
    }
    console.log(i);
}

Output:

1
2
4
5

Breaking the Loop with break

for (let i = 1; i <= 5; i++) {
    if (i === 4) {
        break; // Exit loop when i is 4
    }
    console.log(i);
}

Output:

1
2
3


2. while Loop

The while loop is another commonly used loop in JavaScript. Unlike the for loop, it only checks a condition before executing the block of code. It's best suited for scenarios where you don’t know in advance how many times the loop will run.


Structure of a while Loop

while (condition) {
    // Code to execute
}
  • Condition: A boolean expression that is checked before each iteration. If the condition is true, the loop executes. If false, the loop terminates.

Basic Example: Counting from 1 to 5

let i = 1;
while (i <= 5) {
    console.log(`Current number: ${i}`);
    i++; // Increment the counter
}

Output:

Current number: 1
Current number: 2
Current number: 3
Current number: 4
Current number: 5

Example: Printing Odd Numbers

let i = 1;
while (i <= 10) {
    console.log(i);
    i += 2; // Increment by 2 to skip even numbers
}

Output:

1
3
5
7
9

Example: Checking User Input

The while loop can be useful for tasks like repeatedly prompting the user until valid input is given.

let input = "";
while (input !== "exit") {
    input = prompt("Type 'exit' to quit:");
}
console.log("You exited the loop.");

Infinite Loop

A while loop can become infinite if the condition never becomes false. Be cautious to avoid such situations.

while (true) {
    console.log("This will run forever!");
    break; // Ensure there's a break condition
}

Combining while with Arrays

const fruits = ["Apple", "Banana", "Cherry"];
let index = 0;
while (index < fruits.length) {
    console.log(fruits[index]);
    index++;
}

Differences Between for and while Loops

Aspectfor Loopwhile Loop
UsageWhen the number of iterations is known.When the number of iterations is unknown.
SyntaxCompact (initialization, condition, increment).Simpler, with only a condition.
ReadabilityBetter for predictable iterations.Better for condition-driven loops.

Practical Example: Factorial Calculation

Using for Loop

let num = 5;
let factorial = 1;
for (let i = 1; i <= num; i++) {
    factorial *= i;
}
console.log(`Factorial of ${num} is ${factorial}`);

Using while Loop

let num = 5;
let factorial = 1;
let i = 1;
while (i <= num) {
    factorial *= i;
    i++;
}
console.log(`Factorial of ${num} is ${factorial}`);

By mastering both for and while loops, you can handle a wide variety of iterative tasks in JavaScript.

3. do...while Loop in JavaScript

The do...while loop is a variation of the while loop, but with a key difference: the code block is executed at least once before the condition is checked. This makes it useful in situations where you want to ensure the code runs at least one time, regardless of the condition.


Syntax

do {
    // Code to execute
} while (condition);
  • do block: The code inside the do block is executed first.

  • Condition: After the code runs once, the condition is evaluated. If true, the loop continues; if false, the loop stops.


Basic Example: Counting from 1 to 5

let i = 1;
do {
    console.log(`Current number: ${i}`);
    i++;
} while (i <= 5);

Output:

Current number: 1
Current number: 2
Current number: 3
Current number: 4
Current number: 5

Key Feature: Executes at Least Once

Even if the condition is false initially, the do block runs once.

let i = 10;
do {
    console.log(`Current number: ${i}`);
    i++;
} while (i <= 5);

Output:

Current number: 10

Real-World Example: Validating User Input

The do...while loop is excellent for tasks like prompting the user until valid input is provided.

let password;
do {
    password = prompt("Enter your password (at least 6 characters):");
} while (password.length < 6);
console.log("Password accepted!");

Example: Printing Odd Numbers

let i = 1;
do {
    console.log(i);
    i += 2;
} while (i <= 10);

Output:

1
3
5
7
9

Comparison with while Loop

Aspectwhile Loopdo...while Loop
ExecutionCode runs only if the condition is true.Code runs at least once, regardless of condition.
Use CaseSuitable when the loop might not execute.Suitable when the loop must run at least once.

The do...while loop is a powerful tool for scenarios requiring one guaranteed execution before validation. Its unique behavior makes it invaluable for input validation, setup processes, and scenarios where you must perform an action at least once.

Other Series:


Connect with Me
Stay updated with my latest posts and projects by following me on social media:

  • LinkedIn: Connect with me for professional updates and insights.

  • GitHub: Explore my repository and contributions to various projects.

  • LeetCode: Check out my coding practice and challenges.

Your feedback and engagement are invaluable. Feel free to reach out with questions, comments, or suggestions. Happy coding!


Rohit Gawande
Full Stack Java Developer | Blogger | Coding Enthusiast