• JavaScript Basics

  • Operators in JavaScript

  • Conditional Statements in JavaScript

  • JavaScript Strings

  • JavaScript Arrays

  • JavaScript Loop

  • JavaScript Functions

  • Conclusion

JavaScript if, else, and else if Statements

JavaScript Conditional Statement

In JavaScript Programming, we often need to make decisions. Sometimes, we want our JavaScript code to run only if certain conditions are met. Conditional statements let us control how our code behaves based on different conditions, allowing it to make decisions and perform different actions in various situations.

For example, you might want your program to display "Good morning" in the morning, "Good afternoon" in the afternoon, and "Good evening" at night. To handle this kind of decision-making, we use conditional statements.

Types of Conditional Statements in JavaScript

JavaScript provides several ways to handle different conditions:

  1. if - Runs a block of code if a specified condition is true.
  2. else - Runs a block of code if the condition in the if statement is false.
  3. else if - Allows for additional conditions if the previous one was false.
  4. switch - Tests multiple conditions and runs code for the first matching case. (The switch statement will be covered separately.)

JavaScript if Statement

The if statement runs a block of code if a specified condition is true.

Syntax:

javascript
1if (condition) {
2  // code to run if the condition is true
3}

Note: JavaScript is case-sensitive, so writing If or IF instead of if will cause an error.

Example:

javascript
1let hour = 14;
2if (hour < 18) {
3  greeting = "Good day";
4}

In this example, if hour is less than 18, the greeting will be:

javascript
1Good day

The else Statement

The else statement lets you run code if the condition in the if statement is false.

Syntax:

javascript
1if (condition) {
2  // code to run if the condition is true
3} else {
4  // code to run if the condition is false
5}

Example:

javascript
1let hour = 20;
2if (hour < 18) {
3  greeting = "Good day";
4} else {
5  greeting = "Good evening";
6}

If the hour is 20, the greeting will be:

javascript
1Good evening

The else if Statement

The else if statement allows you to test additional conditions if the first one is false.

Syntax:

javascript
1if (condition1) {
2  // code to run if condition1 is true
3} else if (condition2) {
4  // code to run if condition1 is false and condition2 is true
5} else {
6  // code to run if both condition1 and condition2 are false
7}

Example:

javascript
1let time = 15;
2if (time < 10) {
3  greeting = "Good morning";
4} else if (time < 20) {
5  greeting = "Good day";
6} else {
7  greeting = "Good evening";
8}

If the time is 15, the greeting will be:

javascript
1Good day

Conditional statements give you control over what code runs in different scenarios, allowing your program to adapt and respond to different situations.

Frequently Asked Questions