IN THIS LESSON

Most programs change their behavior based off of a set of different inputs. There are many ways to alter actions, but one of the most universal is the if/else statement.

const sayMood = (myMood) => {
  if (myMood === "Happy") {
    console.log("I'm great!")
  } else if (myMood === "Sad") {
    console.log("I'm pretty bummed.")
  } else {
    console.log("I'm...something.")
  }
}

sayMood('Happy')

Structure of an If/Else

Ok, Let's break it down.

  • An if/else statement can be made up of 3 kinds of checks: if, else if, and else

  • Each type of check will only fire if a certain condition evaluates to true

  • You can use only one if and else checks per statement, but you can use as many else if checks as you want

  • else checks are optional, since sometimes you don't want a catch-all situation.

if (condition A) {
  // Runs if Condition A is true
} else if (condition B) {
  // Runs if Condition B is true
} else if (condition C) {
  // Runs if Condition C is true
} else {
  // Runs if ALL conditions are false
}

Conditions and Comparisons

Let's start simple with just an if statement to talk about conditions. A condition in JavaScript is any expression that evaluates to true or false. We do this by using the comparison operators:

Operator Name Example
=== Equal To 'Hi' === 'Hi'
!== Not Equal To 6 !== 7
> Greater Than 10 > 1
< Less Than 3 < 5
>= Greater Than Or Equal To 5 >= 5
<= Less Than Or Equal To 2 <= 2

What you do is take 2 values, put an operator between them, and then stick that whole thing in the () of the if statement. If the condition is true, then the code in the next {} will execute. But if the condition is false, then the code doesn't run.

let name = 'bob'
let age = 32
if (name !== 'jo') {
  console.log('Hello, not Jo.')
}

Click "Run Pen" in CodePen to execute the code. You can explore the functions and observe their behavior, gaining a better understanding of how they operate.

Storing Conditionals

Conditionals evaluate to booleans, which are just values. That means that you can store conditions as variables before using them in if/else statements.

let name = 'bob'
let age = 32
let canVote = age >= 18

console.log('canVote:', canVote)
if (canVote) {
  console.log("Let's go vote!")
}

else if and else

Now that we fully understand conditionals, let's get back to building our if/else statement. If our question boils down to "Do this or that", then we'll just need an else statement.

let chanceOfRain = 72;
if (chanceOfRain >= 70) {
  console.log('Bring an umbrella.')
} else {
  console.log('No umbrella!')
}

An else is used when all other cases should result in that code block running. That's why there's no conditional next to the else. What you're saying is, "If the main conditional is false, run the else block." But what if we want more options? That's where the else if conditions come in

An else if condition allows you to specify for more conditionals.

let pet = 'cat'

if (pet === 'cat') {
  console.log("My favorite pet!")
} else if (pet === "dog") {
  console.log("My 2nd favorite pet!")
} else if (pet === "snake") {
  console.log("Hard pass.")
} else if (pet === "turtle") {
  console.log("Love 'em!")
} else {
  console.log("Your pet is meh.")
}

Remember, each if statement starts a new chain. And in each chain, only one code block can execute. So, it helps to be specific.

Reassigning variables

Look again at that above example. That's a lot of console.logs, right? What if we just saved a variable called msg (universal shorthand for "message"), and then logged that only once?

let pet = "cat"
let msg = ""

if (pet === "cat") {
  msg = "My favorite pet!"
} else if (pet === "dog") {
  msg = "My 2nd favorite pet!"
} else if (pet === "snake") {
  msg = "Hard pass."
} else if (pet === "turtle") {
  msg = "Love 'em!"
} else {
  msg = "Your pet is meh."
}
console.log(msg);

That's a little cleaner, but it looks like we added lines! But we aren't done yet. If we use the old else value instead of using an empty string, then we can remove else section.

Click "Run Pen" in CodePen to execute the code. You can explore the functions and observe their behavior, gaining a better understanding of how they operate.

Multiple conditionals

So we have one conditional per block, yes, but what about a second conditional? Don't worry, we have special logical operators to deal with combos.

The OR operator ||

If you want something to happen as long as at least one condition is true, use the OR operator. It's two "pipe" characters ||. On most keyboards you get that by holding shift and the "\" key, which is usually one above the enter key. Here's how you use it:

let pet = "cat"
let msg = "Your pet is meh."

if (pet === 'cat' || pet === 'dog') {
  msg = "I love your pet!"
}
console.log(msg);

The AND operator &&

If you want every single condition to be true, then you need the AND operator. It's just two ampersands.

let pet = "dog"
let name = "fido"
let msg = "You are creative"
if (name === "fido" && pet === "dog") {
  msg = "Ya basic"
}
console.log(msg)

If your pet is a dog but it's name isn't "fido", then that if statement won't fire.

Number ranges

You'll probably need at least 1 && operator when starting number ranges. For example: we want "low" if the number is between 0 and 100, "med" if it's between 100 and 200, "high" if it's 200 and 300, and then "off scale" for all bigger or negative numbers

if (num >= 0 && num < 101) {
  console.log('low')
} else if (num < 201) {
  console.log('med')
} else if (num < 301) {
  console.log('high')
} else {
  console.log('off scale')
}

🎉 Congratulations! You've successfully grasped the basic fundamentals of Flow control. Now, let's reinforce your learnings with some hands-on practice. Below are prompts to help you strengthen your skills. Please use the CodePen link provided to write and test your code, press Run Pen to activate the terminal:

Challenge 1: Write a function that checks whats the weather of the day. If the weather is rainy, log “It is raining today” or if the weather is sunny, log “Its sunny out today”.

Challenge 2: Write a function called isTrue that takes in a persons age. If age (20) is less than your age return true or if your age is greater than 20, return false

Challenge 3: Write a code snippet with three conditionals for different days of the week. Pick two days that you really like and log a message saying why you love those days. Also, choose one day that isn't your favorite and log a reason for that