Use Sophia to knock out your gen-ed requirements quickly and affordably. Learn more
×

Conditionals and Logical Flow

Author: Sophia

what's covered
In this lesson, you will learn how conditional statements allow your programs to make decisions and execute different code based on specific conditions. Specifically, this lesson will cover the following:

Table of Contents

1. The if Statement

Programs become truly powerful when they can make decisions. Without the ability to respond to different situations, your code would always do the exact same thing every time it runs. Conditional statements give your programs the ability to choose different paths based on the data they receive. The if statement is the most fundamental way to create a conditional statement in JavaScript. It evaluates a condition and executes code only when that condition is true.

term to know
Conditional Statement
A programming construct that executes different code blocks based on whether a specified condition evaluates to true or false.

1a. Syntax

The if statement follows a straightforward pattern: You provide a condition inside parentheses, and if that condition evaluates to true, the code inside the curly braces runs.

The condition inside the parentheses must be a Boolean expression, meaning an expression that evaluates to either true or false. You can use comparison operators like >, <, >=, <=, ===, and !== to create these expressions.

EXAMPLE

Here is the basic structure of an if statement:

let temperature = 95;

if (temperature > 90) {
console.log("It's hot outside!");
}
In this code:

  • The condition temperature > 90 is a Boolean expression
  • It evaluates to true because 95 is greater than 90
  • Because the condition is true, the code inside the block runs
  • The message “It’s hot outside!” is displayed in the console

The following diagram shows how an if/else statement controls program flow.

 Flowchart showing how an if/else statement evaluates a condition and executes one of two paths based on whether the condition is true or false.

key concept
The code inside the curly braces { } of an if statement only executes when the condition evaluates to true. If the condition is false, JavaScript skips that block entirely and continues with the rest of the program.

try it
Consider the following code:

let score = 75;

if (score >= 80) {
console.log("Great job!");
}

console.log("Quiz complete.");
What will this code output to the console?
The output will be only “Quiz complete.” because the condition score >= 80 is false (75 is not greater than or equal to 80). The code inside the if block is skipped, but the final console.log() runs regardless because it is outside the conditional block.

term to know
Boolean Expression
An expression that evaluates to either true or false, typically using comparison or logical operators.

1b. Truthy and Falsy Values

In a conditional statement, JavaScript needs a result that is either true or false in order to decide whether to run a block of code. While some conditions use Boolean values directly, JavaScript can also evaluate other types of values as either true or false.

Values that are treated as false in this situation are called falsy values. All other values are considered truthy values.

The falsy values in JavaScript are:

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN
These values are treated as false when used in a condition.

All other values are treated as true, including non-empty strings, nonzero numbers, arrays, and objects.

 Overview of JavaScript falsy values, including false, 0, empty string, null, undefined, and NaN, all of which evaluate to false in a condition.

EXAMPLE

This code demonstrates how truthy and falsy values work.

let username = "";

if (username) {
console.log("Welcome, " + username);
}

username = "Alex";

if (username) {
console.log("Welcome, " + username);
}
In this code:

  • In the first if statement, the username is an empty string
  • An empty string is a falsy value, so JavaScript treats it as false
  • Because the condition is false, the code inside the block does not run
  • In the second if statement, the username is "Alex"
  • A non-empty string is a truthy value, so JavaScript treats it as true
  • Because the condition is true, the message “Welcome, Alex” is displayed

Understanding truthy and falsy values helps you write cleaner conditions. Instead of writing if (username !== ""), you can write if (username) to check if a variable has a meaningful value.

terms to know
Falsy Value
A value that is treated as false when evaluated in a Boolean context.
Truthy Value
A value that is treated as true when evaluated in a Boolean context.


2. Expanding Conditional Logic

So far, you have used the if statement to run code only when a condition is true. However, many situations require your program to take one action when a condition is true and a different action when it is false.

The else keyword provides an alternative code block that runs when the if condition is false. This allows your program to handle both possible outcomes: one when the condition is true and another when it is false. The else block does not have its own condition. It runs whenever the if condition is false, handling all remaining cases that did not meet the original condition.

EXAMPLE

This code responds differently based on a user’s age:

let age = 16;

if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You cannot vote yet.");
}
Because age is 16, the condition age >= 18 is false, so the else block executes, displaying “You cannot vote yet.”

key concept
When you use if with else, exactly one of the two code blocks will always execute. If the condition is true, the if block runs. If the condition is false, the else block runs.

While the else statement allows you to handle two outcomes, many situations require more than two possible results.

In many situations, there are more than two possible outcomes. Instead of choosing between just true and false, your program may need to check several different conditions.

The else if keyword allows you to add additional conditions after an if statement. JavaScript checks each condition in order from top to bottom. As soon as it finds a condition that is true, it runs that block of code and skips the rest.

EXAMPLE

This grading system uses multiple conditions:

let score = 85;

if (score >= 90) {
console.log("Grade: A");
}
else if (score >= 80) {
console.log("Grade: B");
}
else if (score >= 70) {
console.log("Grade: C");
}
else if (score >= 60) {
console.log("Grade: D");
}
else {
console.log("Grade: F");
}
In this code:

  • JavaScript checks each condition from top to bottom
  • The first condition score >= 90 is false, so it moves to the next condition
  • The next condition score >= 80 is true
  • Because this condition is true, the code inside that block runs and displays “Grade: B”
  • All remaining conditions are skipped

hint
When using else if, order matters. Place more specific conditions before more general ones. If you checked score >= 60 first, everyone who passed would receive a D grade, even those who scored 95.

try it
Predict what grade will be displayed if score is set to 90. Consider how each condition is evaluated from top to bottom.
The output would be “Grade: A” because the first condition score >= 90 is true when score equals 90. JavaScript executes that block and skips all the remaining else if and else conditions.

big idea
The else keyword provides an alternative path when an if condition is false. The else if keyword allows you to test multiple conditions in sequence, executing only the first matching block.


3. Switch Statements

When you need to compare a single value against several possible matches, a switch statement provides a more organized alternative to multiple else if conditions. Instead of checking many separate conditions, a switch statement evaluates one value and compares it to a list of possible matches.

EXAMPLE

This switch statement responds to a day of the week:

let day = "Tuesday";

switch (day) {
case "Monday":
console.log("Start of the work week.");
break;
case "Tuesday":
console.log("Second day of the week.");
break;
case "Wednesday":
console.log("Midweek day.");
break;
case "Thursday":
console.log("Almost Friday!");
break;
case "Friday":
console.log("Weekend is near!");
break;
default:
console.log("It's the weekend!");
}
In this code:

  • JavaScript evaluates the value of day once
  • It compares that value to each case from top to bottom
  • When it finds a match ("Tuesday"), it runs that block of code
  • The break statement stops the switch, so no other cases run

A switch statement works by evaluating a single value and comparing it to each case. Each case represents a possible match. When a match is found, its code runs, and the break statement stops further comparisons.

Switch statements use strict comparison (===), meaning both the value and the type must match exactly. For example, the string "5" and the number 5 would not be considered equal.

If a break statement is missing, JavaScript continues to the next case even if it does not match. This behavior is called fall-through.

EXAMPLE

This code demonstrates fall-through when break is omitted:

let fruit = "apple";

switch (fruit) {
case "apple":
console.log("Apples are red or green.");
case "banana":
console.log("Bananas are yellow.");
break;
case "orange":
console.log("Oranges are orange.");
break;
}
In this code:

  • The value "apple" matches the first case
  • Because there is no break, JavaScript continues to the next case
  • As a result, both “Apples are red or green.” and “Bananas are yellow.” are displayed

The default case runs when none of the other cases match. It acts like the final else in an if/else if structure.

Comparison showing a switch statement without break causing multiple cases to run versus a correct version with break that stops execution after the first match.

big idea
Switch statements provide a clear way to handle multiple exact value comparisons. They evaluate one value, compare it to a set of possible matches, and execute the first matching case. The break statement prevents unintended fall-through, and the default case handles unmatched values.

terms to know
Switch Statement
A control structure that evaluates an expression and executes the code associated with the first matching case label.
Fall-Through
The behavior in a switch statement where execution continues from one case into the next when a break statement is omitted.


4. Combining Conditions

In earlier sections, you used conditional statements to check one condition at a time. However, many situations require evaluating multiple conditions together to make a decision.

You can do this by nesting conditional statements or by combining conditions using logical operators. A nested conditional places one if statement inside another. This allows your program to check a second condition only after the first condition is true.

EXAMPLE

This code uses nested conditionals to check membership status and purchase amount:

let isMember = true;
let purchaseAmount = 150;

if (isMember) {
if (purchaseAmount > 100) {
console.log("You get a 20% discount!");
} else {
console.log("You get a 10% discount.");
}
} else {
console.log("Join our membership for discounts!");
}
In this code:

  • JavaScript first checks if the user is a member
  • If that condition is true, it then checks the purchase amount
  • The second condition is only evaluated if the first condition is true

While nesting is sometimes necessary, deeply nested conditionals can become difficult to read. When you find yourself nesting more than two or three levels deep, consider refactoring your logic. Logical operators allow you to combine multiple Boolean expressions into a single condition. The three main logical operators are:

  • && (AND): True only if both conditions are true
  • || (OR): True if at least one condition is true
  • ! (NOT): Reverses a Boolean value

EXAMPLE

This code uses logical operators to simplify the previous nested example:

let isMember = true;
let purchaseAmount = 150;

if (isMember && purchaseAmount > 100) {
console.log("You get a 20% discount!");
} else if (isMember) {
console.log("You get a 10% discount.");
} else {
console.log("Join our membership for discounts!");
}
In this code:

  • The condition isMember && purchaseAmount > 100 combines two checks
  • Both conditions must be true for the first block to run
  • This produces the same result as the nested example, but with simpler code

 Comparison showing nested conditional statements versus a simplified version using logical operators, demonstrating improved readability with equivalent results.

Logical operators allow you to express complex decisions more clearly without deeply nested structures.

try it
Consider the following code:

let age = 25;
let hasLicense = false;

if (age >= 16 && hasLicense) {
console.log("You can drive.");
} else {
console.log("You cannot drive.");
}
What will this code output?
The output is “You cannot drive.” The && operator requires both conditions to be true. While age >= 16 is true (25 >= 16), hasLicense is false. Since one condition is false, the entire expression is false, and the else block executes.

big idea
Complex decisions can be built using nested conditionals or logical operators. Logical operators like && and || allow you to combine multiple conditions into a single, more readable expression instead of deeply nested code. When combining conditions, using parentheses can make your logic clearer and easier to understand.

terms to know
Nested Conditional
A conditional statement placed inside another conditional statement, used to check additional conditions only when an outer condition is met.
Logical Operator
An operator that combines or modifies Boolean values, such as && (AND), || (OR), and ! (NOT).

summary
In this lesson, you learned about the if statement, including syntax and truthy and falsy values, and how conditions control whether code runs based on values that evaluate to true or false. You explored expanding conditional logic to handle multiple outcomes using else and else if, allowing programs to choose between different paths. You examined switch statements as a structured way to compare a single value against multiple exact matches. Finally, you learned combining conditions to build more complex decisions using nested conditionals and logical operators.

Source: THIS TUTORIAL WAS AUTHORED BY SOPHIA LEARNING. PLEASE SEE OUR TERMS OF USE.

REFERENCES

Mozilla Developer Network. (n.d.). How the web works. developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/How_the_Web_works

Terms to Know
Boolean Expression

An expression that evaluates to either true or false, typically using comparison or logical operators.

Conditional Statement

A programming construct that executes different code blocks based on whether a specified condition evaluates to true or false.

Fall-Through

The behavior in a switch statement where execution continues from one case into the next when a break statement is omitted.

Falsy Value

A value that is treated as false when evaluated in a Boolean context.

Logical Operator

An operator that combines or modifies Boolean values, such as && (AND), || (OR), and ! (NOT).

Nested Conditional

A conditional statement placed inside another conditional statement, used to check additional conditions only when an outer condition is met.

Switch Statement

A control structure that evaluates an expression and executes code associated with the first matching case label.

Truthy Value

A value that is treated as true when evaluated in a Boolean context.