Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS If Else

Conditional Statements

Often, when writing code, you need to take different actions based on various decisions.

You can achieve this using conditional statements.

In JavaScript, the following conditional statements are available:

  • Use if to define a block of code that runs if a specified condition is true.
  • Use else to define a block of code that runs if the same condition is false.
  • Use else if to test a new condition if the first one is false.
  • Use switch to define multiple alternative blocks of code to execute.
The switch statement will be covered in the next chapter.

The if Statement

Use the if statement to define a block of JavaScript code that should be executed when a condition is true.

Syntax

if (condition) {
  //  block of code to be executed if the condition is true
}
Keep in mind that “if” should be in lowercase; using uppercase letters (If or IF) will result in a JavaScript error.

Example

Create a “Good day” greeting if the hour is before 18:00.

if (hour < 18) {
  greeting = “Good day”;
}

The outcome of the greeting will be:

Good day

The else Statement

Use the else statement to define a block of code that should run if the condition is false.

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

Example

If the hour is before 18, display a “Good day” greeting; otherwise, show “Good evening.”

if (hour < 18) {
  greeting = “Good day”;
else {
  greeting = “Good evening”;
}

The resulting greeting will be:

Good day

The else if Statement

Use the else if statement to define a new condition to test if the initial condition is false.

Syntax

if (condition1) {
  //  block of code to be executed if condition1 is true
else if (condition2) {
  //  block of code to be executed if the condition1 is false and condition2 is true
else {
  //  block of code to be executed if the condition1 is false and condition2 is false
}

Example

If the time is before 10:00, display a “Good morning” greeting; if not, but the time is before 20:00, show a “Good day” greeting; otherwise, display “Good evening.”

if (time < 10) {
  greeting = “Good morning”;
else if (time < 20) {
  greeting = “Good day”;
else {
  greeting = “Good evening”;
}

The resulting greeting will be:

Good day