Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Using else for Alternative Outcomes | Controlling Program Flow with Conditional Statements
Introduction to JavaScript
course content

Course Content

Introduction to JavaScript

Introduction to JavaScript

1. JavaScript Fundamentals
2. Variables and Data Types in JavaScript
3. Performing Operations in JavaScript
4. Controlling Program Flow with Conditional Statements
5. Looping Through Data in JavaScript
6. Functions in JavaScript

book
Using else for Alternative Outcomes

While if statements execute code under specific conditions, they don't create true branching in your code. Instead, they guide the interpreter through different paths within your program.

The else Keyword

To introduce branching behavior, you can use the else keyword in combination with if to create conditional statements.

Consider this example:

1234567
let a = 60; if (a >= 100) { console.log("a is greater than or equal to 100"); } else { console.log("a is less than 100"); }
copy

In the example above, the condition a >= 100 evaluates to false, so the code block within the if statement is not executed. Instead, the code block within the else statement is executed because the if condition is false.

The syntax of the else statement is similar to that of the if statement, except it doesn't require a condition or parentheses ().

Note

When using an else statement, do not place the end-of-command (;) after the if code block ({}), as this will result in a SyntaxError. The if-else statement is considered a single command.

1. What will be the output?

2. What will be the output?

question mark

What will be the output?

Select the correct answer

question mark

What will be the output?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 2
We're sorry to hear that something went wrong. What happened?
some-alt