JavaScript If…Else


JavaScript Conditional Statements

JavaScript, like many other programming languages, enables you to create code that executes various operations based on the outcomes of a logical or comparison test at run time. This implies that you may formulate test conditions as expressions that can be either true or false, and depending on the outcome, you can take different actions.

With JavaScript, you may utilize a variety of conditional statements to decide things.

  1. The if statement
  2. The if...else statement
  3. The if...else if....else statement
  4. The switch...case statement

We will discuss each of these statements in detail in the coming sections.


The if statement

A piece of code is only run using the if statement if the given condition is true. The simplest conditional statement in JavaScript is this.

Example

Preview

The if...else statement

By offering an alternate option by including an else statement in the if statement, you may improve the decision-making skills of your JavaScript application. You can run one piece of code if the given condition evaluates to true and another chunk of code if it evaluates to false by using the if...else statement.

Example

Preview

The if...else if....else statement

The if...else if...else statement in JavaScript is used to test multiple conditions and execute different code blocks depending on which condition is true.

Example

Preview

The switch...case statement

The switch...case statement in JavaScript is used to test a variable against a list of possible values and execute different code blocks depending on which value the variable matches. It provides an alternative to using multiple if...else statements.

Example

Preview