DEV Community

vidhya murali
vidhya murali

Posted on

Conditional Statements in JavaScript

Conditional Statements

  • Conditional Statements allow us to perform different actions for different conditions.
  • Conditional statements run different code depending on true or false conditions .

Conditional statements include:

  • if
  • if...else
  • if...else if...else
  • switch
  • ternary (? :)

When to use Conditionals

  • Use if to specify a code block to be executed, if a specified condition is true
  • Use else to specify a code block to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative code blocks to be executed
  • Use (? :) (ternary) as a shorthand for if...else

The JavaScript if Statement

Use the JavaScript if statement to execute a block of code when a condition is true.

Nested if

You can use an if statement inside another if statement.

Nested if statements can make your code more complex.

A better solution is to use the logical AND operator:

The else Statement

Use the else statement to specify a block of code to be executed if a condition is false.

Syntax :

The else if Statement

Use the else if statement to specify a new condition if the first is false

The JavaScript Ternary Operator

The conditional operator is a shorthand for writing conditional if...else statements.

It is called a ternary operator because it takes three operands.

The conditional (ternary) operator is the only JavaScript operator that takes three operands.

Reference :

Top comments (0)