3️⃣

3.3 If, Else, Else if

3.3 If, Else, Else if

Why Do We Need This?

With the use of if and else, there is a lot more we can do with JavaScript! Conditionals become much more useful. It gives the program more control over what happens in the program by giving it different paths depending on the conditionals we decided to give it.

Basic Structure

This is the very basic idea of a
This is the very basic idea of a if and else statement.

If you think about it, we use conditional statements in real life. Here's an example:

If time is greater than 8, wake up. Anything else, go back to sleep.

⚠️

There will be methods that aren't implemented in the code. Just imagine that the method was already made.

Here's how you create a if statement.

if (conditonal) {

}

Here's an example of a if statement in action:

let currentTime = 8;

if (currentTime > 8) {
	wakeUp();
}

Here's how you create a else statement:

if (conditional) {

} else {

}

Here's an example of a else statement in action:

let currentTime = 8;

if (currentTime > 8) {
    wakeUp(); 
} else {
    goToSleep(); 
}

However, there are times where we want even more control. That means the use of the else if statement.

Here's how you create a else if statement:

if (conditional) {
} else if (conditional) {

} else {
}

Here's a example of an else if statement in action:

let currentTime = 8;

if (currentTime > 8) {
    wakeUp(); 
}  else if (currentTime == 7) {
    checkTwitter();
} else {
    goToSleep(); 
}

Practice

You can add practice problems here if you want. Follow the format below.

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.