Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    4 Quizzes
  9. JavaScript: Iterators
    3Topics
    |
    3 Quizzes
Lesson 3, Topic 3
In Progress

JavaScript: else Statement

Yasin Cakal 31 Oct 2021
Lesson Progress
0% Complete

In the previous exercise, we used an if statement to determine whether or not to run a block of code based on a condition. In many cases, we’ll have code that needs to be executed if our condition is false.

If we wanted to add some default behavior to the if statement, we could add an else statement that would execute a block of code if the condition was false. Take a look at how an else statement is used:

if (false) {
  console.log('If result is false this will print.');
} else {
  console.log('If result is not false this will print.');
}

// Output: If result is not false this will print.

An else statement must be used in combination with an if statement and the pair is known as an if…else statement.

The else statement in the previous example is:

  1. After the code block of an if statement, the else keyword is used.
  2. There is a code block that is enclosed by curly braces {}.
  3. When the if statement’s condition evaluates to false, the code inside the else statement code block will run.

We can use if…else statements to automate yes-or-no questions, also known as binary decisions.

Responses

Leave a Reply

%d bloggers like this: