learntheweb

If Loops & Logical Operators

Introduction

When you think about it, most of the things that we do in the real world and while programming are based off of conditions. Imagine a user logging into a website, if their username and password is correct, they’re in. If it’s not, they will be denied. That logic right there can be replicated with something called an if loop. In this lesson, we will be learning about how if loops and the different logical operators here in Javscript!

Overview

By the end of this lesson, you should be able to:
    • Understand the syntax of if loops
    • Understand the else if and else statements
    • Understand “or”, “not,” and “and” as logical operators in Javascript
    • Learn how to use truth tables in Javascript

If Loops

If statements, also known as conditional statements, are a crucial component of programming. They allow you to execute specific blocks of code based on whether a certain condition is met. If statements are often used in conjunction with loops, which allow you to repeat a certain block of code multiple times. 

 

For example, in a tic-tac-toe game, you might use an if statement to determine the outcome of the game based on the positions of the X’s and O’s on the board. If player 1 has won, you might execute one block of code; if player 2 has won, you might execute a different block of code; and if it’s a draw, you might execute yet another block of code. If statements and loops are fundamental concepts that are used in many different types of programs, and they are essential tools for any programmer to understand.

 

You get the point. If loops are used everywhere in code and the whole concept of them isn’t that hard either. Heres some fake code to demonstrate how if loops function. 

if (condition) {
    // execute some code
}

Note how our condition is wrapped in parentheses, in other languages like python that wrapping is not required, but Javascript will throw us an error if we don’t wrap it in parentheses. Also take note of how we are using curly brackets to wrap around our executable code in the middle. If you’ve used CSS, this is kind of like that!

 

Now that we understand the syntax of an if loop, let’s take a look at an example of an if loop to better understand how it works

let i = 5

if (i == 5) {
    console.log("i is equal to 5!")
}

// Shows "i is equal to 5" in console

So what is happening here? First, we start by declaring our variable i and set it equal to 5. Now let’s move onto our if loop. Our if loop is checking whether i is equal to 5. If it is, then we will print “i is equal to 5!“. Since in the example above, i is equal to 5, that is what is going to be printed! Let’s look at a more complex example:

let number1 = 20
let number2 = 10

if (number1 > number2) {
    console.log("number1 is bigger!")
}

// Shows "number1 is bigger!" in console

In this if loop, we are checking whether number1 is greater than number2 and if it is, we will output “number1 is bigger!” in console which is the case in this scenario. Take a look at this flowchart which explains what was going on in the previous two examples more clearly:

The "else if" statement

Let’s go back to that example with number1 and number2. We know that we can check if number1 is bigger than number2, but if we wanted to check if number2 was also bigger than number1 as well? Well, we can do that with something called the else if statement. 

You can think of the “else if” statement as like a backup statement. When the first statement is false, the execution of the loop will move onto the second statement if there is one. In this situation, number1 was not bigger than number2, so we moved onto the next statement which checked whether number2 was bigger than number1 which proved to be true! 

 

In loops, we can have as many else if statements as we want and the execution of the loop will keep going until one of them is true. If its false, it will keep moving on until it can’t, and if the condition is true, the whole loop will stop and execute the code inside the else if that was correct. 

The "else" statement

So far, we know how to make our loops go through multiple conditions, but what if we wanted a fallback condition? Incase all of our conditions proved to be false, we want to execute something? Take a look at the example above with number1 and number2, what if the numbers were equal? We could make another else if statement checking if they’re equal, or we can just do an else statement at the end. Take a look at this:

And there we have it, the final addition to our loop: the else statement. When all the if’s and else if statements prove to be false, the loop will go to the else statement as a last resort. You can only have one else statement in a loop since it should be a fallback. There are times however you want to an else statementto be there, like here. Now it doesn’t matter whether our numbers are equal or one is bigger than the other, we can easily check for that using our if, else if, and else conditions. 

Logical Operators

So far, we learned about using conditions in our if loops. We can add logical operators inside of our conditions to make them more complex. Let’s say we want to check whether two variables have certain values. Instead of using 2 if loops, using logical operators, we can do it all in one loop itself. The three main logical operators we’ll look at are:

&& -  The "AND" operator
|| - The "OR" operator
! - The "NOT" operator

Let’s take a look at a few examples showcasing how each of the operators can be used in combination with our if loops.

// The "AND" operator is defined with "&&"

let number = 10
if (number > 0 && number < 20) {
    console.log("Number is between 0 and 20")
} else {
    console.log("Number is not between 0 and 20")
}

// Logs "Number is between 0 and 20"

In this example, we are using the AND operator to check whether number is greater than 0 and less than 20. We can use the “AND” operator (&&)  to check if a variable meets two conditions. Let’s now take a look at the “OR” operator. 

// The "OR" operator is defined with "||"

let number = 10
if (number == 5 || number == 20) {
    console.log("Number is either 5 or 10")
} else {
    console.log("Nothing")
}

// Logs "Nothing"

In the above example, we are using the “OR” operator to check whether number is equal to 5 or equal to 20. The “OR” (||) operator is used to check whether a variable meets either one of the two conditions. Unlike the and operator, only one of the conditions needs to result in true for the conditional to pass.

 

Finally, let’s look at the not operator and understand how it works:

// The "NOT" operator is defined with "!"

let number = 20
if (number != 10) {
    console.log("Number is NOT equal to 10")
}

// Logs "Number is NOT equal to 10"

Another way we can better understand these operators are with truth tables. Here they are:

Ok, let’s talk about each one of these starting with the AND operator:

 

As you can see, the AND operator requires both of the conditions to be true. An AND operator will only turn out to be true when both sides of the condition be true as can be seen above in the truth table.

 

It’s almost the opposite with the NOT operator. With the NOT operator, only one of our values has to be true, that’s why in our truth tables all the values are true except the one where both sides were false. 

 

Not is very simple to understand as well. Not just reverses the value. In the truth table, you can see that not true gives us false, and not false gives us true.

 

These are the logical operators that we use in Javascript. These will come in very handy as you start using more if loops and conditionals throughout your coding journey. Next lesson, we will be learning about the different type of string methods in Javascript and how we can use them!

Practice

Now that you have a good understanding of the basics of if loops, let’s practice using them with some exercises! We’ll provide you with some starter code and a hint in case you get stuck. If you need more help, don’t hesitate to join our Discord server. 

Problem #1

Create some simple code that does the following:

    1. Ask the user for their age and store that age in a variable called age.
    2. If the age is above 18, print out in the console “You are free to enter”
    3. If the age is below 18, print out in the console “You are too young, access denied.
    4. Once you’re done, put in values greater than and less than 18 to make sure that your code works!
    • Remember to use the prompt statement to collect your user output, we’ll learn about more ways later. If for some reason prompt isn’t working, just assign age a random variable and test it from there.

    • For the actual code, make sure to use your knowledge of comparison operators, how can we check when something is over or under 18? And finally, make sure to use the if loop syntax we learned about in this lesson

Problem #2

Let’s make a simple speed limit detector using an if loop!

 

    1. Ask the user for their speed and store that in a variable called “speed”
    2. If the user’s speed is above 80, print out to the console “Too fast, ticket issued”
    3. If the user’s speed is below 30, print out to the console “Too slow, ticket issued”
    4. If the speed is between that, print out to the console “Have a good day”
    • Remember to use the prompt statement to collect your user output, we’ll learn about more ways later. If for some reason prompt isn’t working, just assign age a random variable and test it from there.

    • For the actual code, make sure to use your knowledge of comparison operators, how can we check when something is over or under 18? And finally, make sure to use the if loop syntax we learned about in this lesson
Also, if you’re curious, you could’ve used an else statement at the end instead of checking both values. It’ll work either way.

Problem #3

Now for the final exercise, let’s make a grade calculator using if, else if, and else statements!

    1. Ask the user for their grade and store that in a variable called “grade”
    2. If the grade is above 90, print to the console “grade is A”
    3. If the grade is above 80 and below 90, print to the console “grade is B”
    4. If the grade is above 70 and below 80, print to the console “grade is C”
    5. If the grade is above 60 and below 70, print to the console “grade is D”
    6. If the grade is below 60, print to the console “grade is F”
    • Remember to use the prompt statement to collect your user output, we’ll learn about more ways later. If for some reason prompt isn’t working, just assign grade a random variable and test it from there.

    • For the actual code, make sure to use your knowledge of comparison operators, how can we check when something is over a certain grade andunder a certain grade?

       

    • For the last statement were we are checking all grades below 60, think about using the else statement for that!

Find an issue/typo/error with our content? Please report it here