Articles

JavaScript Conditional Statements Explained with Examples

Learn about JavaScript conditional statements, including `if`, `if...else`, `if...else if...else`, `switch`, and ternary operators. Understand syntax, examples, and best practices.

What are conditional statements in JavaScript?

Conditional statements in JavaScript make decisions in our code based on certain conditions.

Think of them like traffic signals: if the light is green, you go, if it’s red, you stop. Similarly, if a condition is true in code, one block runs otherwise, another does.

These statements are essential because they let our programs react to different inputs or situations. Whether you’re validating a form, checking a user’s role, or showing different messages based on input, conditionals are everywhere.

Conditional logic is a core part of writing dynamic, interactive code.

Now that we know what conditional statements are, let’s start with the most basic one: the if statement.

Related Course

Learn Java: Conditionals and Operators

Learn how to control the flow of execution using conditional statements.Try it for free

How to use the if statement in JavaScript

The if statement is the basic form of a conditional logic in JavaScript. It checks whether a condition is true and runs a block of code if it is.

A flowchart illustrating the behavior of an if statement in JavaScript

Syntax of if block:

if (condition) { 
  // code to run if condition is true 
} 

Here:

  • condition: An expression that, when evaluated to true, allows the code inside the block to execute.

Example:

The example uses an if block to check if the condition score>85 is true or not:

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

This code will produce the output as follows:

Great job!

The “Great job!” message will be printed because the condition score > 80 is true.

When to use an if statement?

Use the if statement when you want to run code only if a specific condition is met and do nothing otherwise.

But what if you want to run one block of code when the condition is true, and another when it’s false? That’s where the else block comes into play.

How to use if ...else in JavaScript

The if...else statement works by first evaluating a condition. If the condition is true, the code inside the if block runs. The code inside the else block is executed if the condition is false.

A flowchart illustrating the behavior of an if else statement in JavaScript

Syntax of if...else block:

if (condition) { 
  // code block to be executed if the condition is true 
} else { 
  // code block to be executed if the condition is false 
} 

Example:

The example here makes use of the if...else blocks to make a decision according to the condition being true or false:

let loggedIn = true;
if (loggedIn) {
console.log("Welcome back, user!");
} else {
console.log("Please log in to continue.");
}

The output of this code will be:

Welcome back, user!

In this code:

  • If loggedIn is true, the message “Welcome back, user!” will be printed.

  • If loggedIn is false, the message “Please log in to continue.” will be printed.

Now that we’ve covered the basics of if...else, let’s dive into the if...else if...else ladder to handle multiple conditions.

How to use the if...else if...else ladder in JavaScript

In JavaScript, the if...else if...else ladder helps you execute different blocks of code based on multiple conditions. It’s a cleaner alternative to writing several separate if statements when you’re checking the value of a variable against various possibilities.

A flowchart illustrating the behavior of an if-else-if-else ladder in JavaScript

Syntax of if...else if...else ladder:

if (condition1) { 
  // Code block if condition1 is true 
} else if (condition2) { 
  // Code block if condition2 is true 
} else if (condition3) { 
  // Code block if condition3 is true 
} else { 
  // Code block if none of the conditions are true 
} 

Example:

Let’s take an example where we check a student’s score and assign a letter grade accordingly:

let score = 85;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else if (score >= 70) {
console.log("C");
} else if (score >= 60) {
console.log("D");
} else {
console.log("F");
}

The output of this code will be:

B

The code checks each condition in order, starting with the highest possible grade. The corresponding block is executed once a condition is met, and no further conditions are checked.

When to use if...else if...else over a simple if...else?:

Use the if…else if…else ladder when:

  • You are comparing a single variable against multiple ranges or values.

  • You need only one block to run based on the first true condition.

  • You want to avoid repetitive or disorganized code using multiple standalone if statements.

Using too many else if conditions in a single ladder can make your code harder to read. Consider alternatives like the’ switch’ statement if your logic feels overly complex or repetitive.

How to use the switch statement in JavaScript

The switch statement in JavaScript is a control structure that compares a single value against multiple possible cases. It offers a cleaner and more readable alternative to long if...else if...else ladders, especially when checking one variable against different fixed values.

A switch evaluates an expression and executes code based on the matching case value. It’s best used when you have a fixed set of known values to compare against.

Flow chart illustrating the behavior of a switch statement in JavaScript

Syntax of switch statement:

switch (expression) { 
  case value1: 
    // Code block for value1 
    break; 
  case value2: 
    // Code block for value2 
    break;
  ... 

  default: 
    // Code block if no cases match 
} 

Here:

  • The expression is evaluated once.
  • It is compared with each case value.
  • If a match is found, the associated block runs.
  • The break statement stops further case checks.
  • If no match is found, the default block runs (if provided).

Note: If the break statement is absent in the switch cases, the program will continue checking the subsequent cases even after finding a match. This behavior is known as fall-through.

Example:

The following example makes use of the switch statement to assign the day of the week:

let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName);

The output of this code will be:

Wednesday

The code checks the value of day using a switch statement and assigns the corresponding weekday name to dayName. Since day is 3, it sets dayName to "Wednesday" and prints it.

If day had a value not covered by any case (e.g., 7), the default case would run and assign “Invalid day” to dayName.

When to use switch statement

Use a switch statement when:

  • You’re comparing one variable or expression against a set of known, discrete values.

  • Each case represents a distinct, exact match (e.g., matching a number, string, or constant).

  • You want better readability than a long if...else if...else chain.

  • You need a structured alternative to reduce repetitive if conditions.

While switch statements help simplify multiple condition checks, what if you just need a quick decision between two outcomes? That’s where the ternary operator is useful.

How to use the ternary operator in JavaScript

The ternary operator (?:) in JavaScript is a shortcut for writing simple if...else statements in a single line. It’s useful for quick decisions based on a condition.

Syntax of ternary operator:

condition ? expressionIfTrue : expressionIfFalse; 

Here:

  • condition: The test to evaluate.

  • expressionIfTrue: Runs if the condition is true.

  • expressionIfFalse: Runs if the condition is false.

Example:

let score = 72;
let result = score > 50 ? 'Pass' : 'Fail';
console.log(result);

The output of this code will be:

Pass

In this example, the variable result stores ‘Pass’ because the condition score > 50 is true.

When to use the ternary operator?

  • When you want a compact syntax for simple if…else logic

  • For assigning values based on a condition

Comparing conditional statements in JavaScript

Understanding the differences between conditional statements helps in writing clean and efficient code. Here’s how if, if...else, if...else if...else, switch, and the ternary operator compare:

Type Description Time Complexity
if Checks a single condition O(1)
if...else Chooses between two paths O(1)
if...else if...else Handles multiple conditions in sequence O(n)
switch Matches one value among many options O(1) to O(n)
Ternary Quick, inline condition-based choice O(1)

Each method has its place, and choosing the right one depends on the situation, code clarity, and the number of conditions.

Conclusion

In this article, we explored the different types of conditional statements in JavaScript, including if, if...else, if...else if...else, switch, and the ternary operator. Each structure plays a key role in decision-making, allowing developers to write logic that responds dynamically to different inputs or scenarios.

To continue building your JavaScript skills and apply these concepts in real-world projects, check out Codecademy’s Learn JavaScript course.

Frequently asked questions

1. How to check 3 conditions in an if statement in JavaScript?

You can check multiple conditions in an if statement by using logical operators such as && (AND), || (OR), and ! (NOT). Here’s an example:

let a = 10;
let b = 20;
let c = 30;
if (a > 5 && b < 25 && c === 30) {
console.log("All conditions are true");
} else {
console.log("One or more conditions are false");
}

In this example, three conditions are checked using &&, and if all are true, the statement inside the if block will run.

2. Can I use logical operators inside a switch statement in JavaScript?

No, the switch statement works by comparing the value of the expression to each case and cannot directly handle logical operators. If you need to check multiple conditions with logical operators, use if-else statements instead.

3. Can I use multiple ternary operators in a single expression?

Yes, you can chain multiple ternary operators to evaluate more than one condition. However, while it’s valid syntax, it can reduce readability. Example:

let score = 85;
let result = (score >= 90) ? "A"
: (score >= 75) ? "B"
: (score >= 50) ? "C"
: "F";
console.log(result); // Output: "B"
Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team