DEV Community

Visali Nedunchezhian
Visali Nedunchezhian

Posted on

JavaScript conditional statements

JavaScript conditional statements allow you to execute specific blocks of code based on conditions. If the condition is met, a particular block of code will run; otherwise, another block of code will execute based on the condition.

Types of Conditional Statements

  • if statement
  • if...else statement
  • if...else if...else statement
  • switch statement
  • ternary (conditional) operator

1. if Statement

The if statement evaluates a condition inside parentheses. If the condition is true, the block of code inside the curly braces {} runs. If it’s false, it skips that block.

Syntax

Now let's understand this with the help of example:

Output

2. if-else Statement

The if-else statement will perform some action for a specific condition. Here we are using the else statement in which the else statement is written after the if statement and it has no condition in their code block.

Output

3. else if Statement

The else if statement in JavaScript allows handling multiple possible conditions and outputs, evaluating more than two options based on whether the conditions are true or false.

Output

4. Using Switch Statement (JavaScript Switch Case)

The switch statement is a control structure in JavaScript that allows you to execute different blocks of code based on the value of a single expression. It’s a cleaner, more readable alternative to multiple if...else if statements when you need to compare one variable against many possible values.

Output

5. Using Ternary Operator ( ?: )

The ternary operator is a compact shorthand for an if...else statement. It is called “ternary” because it takes three operands:

  • A condition to test.
  • An expression to evaluate if the condition is true.
  • An expression to evaluate if the condition is false.

Syntax

Output

6. Nested if...else

A nested if...else statement is an if...else structure placed inside another if or else block. This allows you to check multiple conditions in a hierarchical or layered way, making complex decision trees possible.

Output

Top comments (0)