JS TutorialLesson #18

JavaScript else

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

The else Statement

Use the else statement to specify a block of code to be executed if a 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

Example Code

javascript
Try it Yourself
if (hour

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

javascript if (time

Interactive Code Examples

JS Example 1

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
if (hour < 18) {

    greeting = "Good day";

 }
else {

    greeting = "Good evening";

 }

JS Example 2

javascript
Try it Yourself
JavaScript syntax and algorithm demonstration.
if (time < 10) {

    greeting = "Good morning";

 }
else if (time < 20) {

    greeting = "Good day";

 }
else {

    greeting = "Good evening";

 }

JS Example 3

javascript
Try it Yourself
Interactive runnable JavaScript example from EA Academy.
Live Output Preview: