Video Lesson

Lesson Notes

Using if, else if, and else Statements in JavaScript

In this video, I cover how to use conditional logic in JavaScript using if, else if, and else statements. If you’ve already learned about equality operators and block scope, this will be a smooth next step.

Writing a Simple if Statement

Start by declaring a constant:

1const myNumber = 10; 2 3if (myNumber === 10) { 4 console.log("The number is 10"); 5}
  • This checks if myNumber is exactly equal to 10.
  • If it is, the code inside the block runs.
  • This works because we're using the strict equality operator (===).

What Happens if the Condition Is Not Met?

1const myNumber = 9; 2 3if (myNumber === 10) { 4 console.log("The number is 10"); 5}
  • Nothing will be logged because 9 is not strictly equal to 10.

Adding an else Statement

1const myNumber = 9; 2 3if (myNumber === 10) { 4 console.log("The number is 10"); 5} else { 6 console.log("Not equal to 10"); 7}
  • If the first condition fails, the code in the else block runs.

Using else if for More Conditions

1const myNumber = 9; 2 3if (myNumber === 10) { 4 console.log("The number is 10"); 5} else if (myNumber === 9) { 6 console.log("My number is 9 for sure"); 7} else { 8 console.log("Not equal to 10 or 9"); 9}
  • You can add multiple else if blocks to check for different values.
  • This is useful for adding more complex logic to your program.

Summary

  • Use if to check a condition.
  • Use else to handle all other cases.
  • Use else if to check multiple specific conditions.
  • Always use {} to create blocks of code that are executed when conditions are true.

This structure forms the backbone of logical decision-making in JavaScript programs.

AI Assistant

Sign In Required

Sign in and subscribe to use the AI assistant for instant help with your lessons.

Sign In

Conditional Logic: `if`, `else if`, and `else`

In this video, I introduce if, else if, and else statements in JavaScript. You’ll learn how to control the flow of your code using conditions, check for specific values, and run different blocks of code based on those conditions. A core building block for writing logic in your programs.

2m 26s

Course Content

0 of 32 lessons completed
6. Promises, Async and Await
0 of 0 completed
7. The DOM
0 of 0 completed