Skip to content

Instantly share code, notes, and snippets.

@ericweissman
Last active April 10, 2019 20:29
Show Gist options
  • Save ericweissman/4bed22968490b3161d0b05ef02aeda9f to your computer and use it in GitHub Desktop.
Save ericweissman/4bed22968490b3161d0b05ef02aeda9f to your computer and use it in GitHub Desktop.

Conditionals

Key Points

  • Javascript interprets (reads) code from the top down, line by line
  • A function can only return one thing. Anything below a return statement will not be read if that return statement fires
  • Conditionals allow you to write more logic into a function to give JS more information about what you want to return from a function!
  • Order matters when writing a conditional! Take time to psuedocode out how you want your function to interpret the data it is given!

Conditional Boilerplate

If / Else Conditional

function someFunction {
    if (this expression evaluates to TRUE) {
        run this code
      } else {
        otherwise, run this code
      }
   }

If / Else If / Else Conditional

function someFunction {
    if (this expression evaluates to TRUE) {
       run this code
     } else if (this expression evaluates to TRUE) {
       run this code
     } else if (this expression evaluates to TRUE) {
       run this code
     } else {
       otherwise, run this code instead
     }
  }

You can have as many Else If blocks as you want. But if you try to write a conditional for every possible scenario, it may be a sign that your function is too specific!

Examples of Basic Conditionals

Imagine we want to write a function that allows parents to check their kid's grades and automatically give them approval/disapproval for a sleepover party.

If / Else

To keep it simple, we can provide approval as long as their report card doesn't have any F's. In English, we would say - "If the report card has an F, we won't give approval. Otherwise, they are allowed to go to the sleepover party. We will write our conditional in much the same way!

Pseudocode
    if the report card has an F
        inform kid they are NOT allowed to attend
    otherwise, if there are NO Fs on the report card
        inform kid they ARE allowed to attend

Here is how we would write this out as a conditonal. NOTE: This example will use the .includes prototype method, which you can learn more about here.

var myReportCard = ['F', 'F', 'F', 'F', 'A']

function checkReportCard(reportCard) {
    if (reportCard.includes('F')) {
        return 'No, you cannot go to sleepover party'
        } else {
        return 'Yes, you are allowed to go to the party'
        }
   }
 
 checkReportCard(myReportCard)

Let's walk through this example a bit. We are creating a function that takes in a report card and checks the grades included in the report card.

Our first conditional checks to see if the report card includes an F. If it DOES include an F, the function will return 'No, you cannot go to the sleepover party'. This first block is known as the If block.

Remember, a function can only return ONE thing. Since our expression in the If block evaluated to true, the function will NOT execute the code contained in the else block.

So, if we adjust the myReportCard variable to look like this:

var myReportCard = ['B', 'C', 'A', 'D']

and then call our function using that report card, like this:

checkReportCard(myReportCard)

We can expect that the else block will execute and we will be granted permssion to go to the party. That's because our report card does not contain any F's, so the expression in the If block will evaluate to FALSE. That means the code below it will NOT fire!

In this case, the ELSE block will fire. A good way to think about the Else block is to remember the word OTHERWISE. For these basic conditionals, we will run the if block if true, OTHERWISE, run the other block of code!

Order and Specificity in Conditionals
Order

When writing conditionals, it pays off to write out some pseudocode ot ensure that we are thinking about our logic correctly. Otherwise, you may not consider things like the ORDER in which we write our if/else blocks. Take the following code for example.

var myReportCard = ['F', 'F', 'F', 'F', 'A']

function checkReportCard(reportCard) {
    if (reportCard.includes('A')) {
        return 'Yes, you can go!'
        } else {
        return 'No, you cannot go!'
        }
   }
    
 checkReportCard(myReportCard)

In this example, our first condition is just checking to see if our report card has an A, in which case we grant permission. But, if you look at our report card, you'll see it is riddled with F's! However, since we are checking to see if there is an A on it, our first condition will evaluate to TRUE and we will be granted permission, even though our report card is less than stellar.

There are many ways we can demonstrate the value of considering the order of our conditionals, but the key takeaway here is that if your conditional is not behaving how you expect, it may be a sign that you need to re-order your logic.

Specificity

How specific we are in our conditionals and the order in which we write our if/else blocks can lead to some very interesting behavior in our code.

Let's look at our code the way it is currently written. But this time, let's change the grades on our report card a bit...

var myReportCard = ['D', 'D', 'D', 'D', 'D']

function checkReportCard(reportCard) {
    if (reportCard.includes('F')) {
        return 'No, you cannot go to sleepover party'
        } else {
        return 'Yes, you are allowed to go to the party'
        }
   }
    
checkReportCard(myReportCard)

We can all probably agree that our current report card isn't very good. However, based on how we've written our conditional, this will still get approval to go the sleepover because it doesn't contain any F's!

This shows some of the limitations of using if/else conditionals. Luckily, we can use Else If blocks as well, which we will cover in our next section!

If / Else If / Else

Since If/Else statements only check two conditions, there are limitations on what we can write. However, we can also write additional checks/conditions using and Else If statement. They work exactly the same as an If statement, and include parentheses to write the expression that we want to check.

You can tack on as many Else If statements as you want! However, there are a few things to consider when writing Else If statements:

  • Conditionals with long else if blocks can be hard to read/understand
  • The more else if blocks we write, the more careful we need to be about specificity and order

Let's use our report card function to write some Else If statements to make our code more specific.

var myReportCard = ['A', 'C', 'C', 'C', 'B']

function checkReportCard(reportCard) {
 if (reportCard.includes('F')) {
   return 'No siree bob'
 } else if (reportCard.includes('C')) {
   return 'Go ask your mother'
 } else {
   return 'Sure thing!'
 }
}

checkReportCard(myReportCard)

In this case, we have added another conditional to check to see if there are any Cs on the report card. So, our function is checking two things:

  • First Check: Does the report card have any Fs? If TRUE, return 'No siree bob'
  • Second Check: Does the report card have any Cs? If TRUE, return 'Go ask your mother"
  • OTHERWISE: Return 'Sure thing!'

This is definitely a better conditional than our previous one. BUT, there are still holes to our conditional. Consider the following report card...

var myReportCard = ['D', 'D', 'D', 'D', 'D']

function checkReportCard(reportCard) {
 if (reportCard.includes('F')) {
   return 'No siree bob'
 } else if (reportCard.includes('C')) {
   return 'Go ask your mother'
 } else {
   return 'Sure thing!'
 }
}

checkReportCard(myReportCard)

Although is report card isn't very good, based on how we wrote our conditional, it will still get approval!

There is another way we can add some more logic to our conditionals to handle this scenario. We can layer in an OR OPERATOR (||) into our if block. Essentially, we are making our first check more robust. Check out my pseudocode below:

    if the report card has an F OR if the report card has a D,
        you can't go to sleepover
    if the report card has a C,
        ask your other parent,
    otherwise
        you can go!

This is how we would write this out in real code:

 function checkReportCard(reportCard) {
  if (reportCard.includes('F') || reportCard.includes('D') {
    return 'No siree bob'
  } else if (reportCard.includes('C')) {
    return 'Go ask your mother'
  } else {
    return 'Sure thing!'
  }
}

There are many ways to utilize operators in your conditionals to make them more/less strict, but they definitely layer on some more complexity. I highly recommend checking the documentation on the different operators and how they work here.

Wrap Up

Conditionals are a great way to add more logic into our functions and control what we return based on different conditions. Feel free to use the following sandboxes to practice your conditionals:

There are more ways to write conditionals besides what we've covered today. If you want more info, research the following:

  • Switch statements
  • Ternary operators
  • Utilizing other logical operators
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment