JavaScript If Else
JavaScript Basics

JavaScript If Else

Conditional Statements in JavaScript

When writing code, you often need to perform different actions based on different conditions. JavaScript provides several ways to handle these scenarios with conditional statements.

Types of Conditional Statements

  • if: Specifies a block of code to be executed if a specified condition is true.
  • else: Specifies a block of code to be executed if the same condition is false.
  • else if: Specifies a new condition to test if the first condition is false.
  • switch: Specifies multiple alternative blocks of code to be executed. (Described in the next chapter)

The if Statement

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

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

Note: The if keyword must be in lowercase. Using uppercase letters (e.g., If or IF) will result in a JavaScript error.

Example

Display a "Good morning" message if the hour is less than 12:

if (hour < 12) {  greeting = "Good morning";}

The else Statement

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

Syntax

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

Example

Display a "Good morning" message if the hour is less than 12, otherwise display "Good afternoon":

if (hour < 12) {  greeting = "Good morning";} else {  greeting = "Good afternoon";}

The else if Statement

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

Syntax

if (condition1) {  // code to be executed if condition1 is true} else if (condition2) {  // code to be executed if condition1 is false and condition2 is true} else {  // code to be executed if both condition1 and condition2 are false}

Example

Display a "Good morning" message if the time is less than 12:00, a "Good afternoon" message if the time is between 12:00 and 18:00, and a "Good evening" message if the time is 18:00 or later:

if (time < 12) {  greeting = "Good morning";} else if (time < 18) {  greeting = "Good afternoon";} else {  greeting = "Good evening";}

The result of greeting will depend on the value of time.

Take a look into your desired course