Logic and Conditionals: Ifs, Else Ifs, Switch

Logic and Conditionals: Ifs, Else Ifs, Switch
bluehost placeholder image


When writing a program in any programming language, there will be situations where you will need to decide on what path to take depending on the current state of the program. You want the program to be able to compare values with one another to determine what to do next. This is called logic.

To get started we first need to learn about the comparison operators at our disposal!

Equality Operator

In our previous lesson, we talked about how to work with Numbers and Math in JavaScript. With the equality operator, we can now check if two numbers are equal or not.

If two numbers are equal, using the equality operator on them will result in true, and if they are not equal, it will result in false.

Using this operator is simple, just use three equal signs.

    console.log(5 === 5);

    var pears = 40 / 2;
    console.log(20 === pears);

    console.log(17 === 10);

Inequality Operator

The inequality operator works basically like the equality operator but in the reverse. If two numbers are the same, it will result in false, while if two numbers are different, it will result in true

To use this operator, you use a single exclamation point followed by two equal signs.

    console.log(9 !== 7);

    var oranges = 5 * 6;
    console.log(30 !== oranges);

    console.log(57 !== 57);

Greater Than and Less Than Operators

You can check whether a number value is greater than or less than another one. This allows you to compare the two numbers.

Use the greater than operator via the greater than symbol, and the less than operator via the less than symbol.

    console.log(6 < 4);
    console.log(8 < 13);

    var books = 32;
    console.log(books > 30);
    console.log(books > 50);

Or Equal To Operators

In the case that you need to check if a number is either less than/greater than or equal to another number, JavaScript has operators for that too.

Check for greater than or equal to via a greater than symbol followed by an equal sign, and check for less than or equal to via a less than symbol followed by equal sign.

    console.log(29 <= 94);
    console.log(13 <= 9);

    console.log(32 >= 32);
    console.log(42 >= 85);


Now that we know how to return true or false when we compare two values, we are now ready to act on that result. In other words, we want to do one thing if the result is true and another thing if the result is false.

This is called a conditional.


Using if is extremely intuitive. If whatever condition you're checking returns true then the next block of code will run.

Let's say if you eat 100 candies or more, you will get a cavity.

    var candy = 110;

    if (candy >= 100) {
        console.log("You got a cavity!");
    You got a cavity!

Since you're a rebel, you decide to eat 110 candies and as a result, you got a cavity over it!

But watch what happens if you only eat 80 candies.

    var candy = 80;

    if (candy >= 100) {
        console.log("You got a cavity!");


The output is blank now because 80 is not greater than or equal to 100, and thus, the code inside did not run and so the output is blank.


You might have thought "well, I want to output a message if they didn't get a cavity", and you can do that using else.

Else is used when the if before it resulted in false. Let's see it in action.

    var candy = 80;

    if (candy >= 100) {
        console.log("You got a cavity!");
    } else {
        console.log("You didn't get a cavity! Nice!");
    You didn't get a cavity! Nice!

Keeping the candies at 80 like before, the first log didn't appear because 80 is not greater than or equal to 100, and so the block inside else ran instead.

What if instead of two paths, you wanted multiple paths?

Else If

Else If is the combination of an if and an else. They are sandwiched between the two and you can have as many as you'd like.

    var candy = 80;

    if (candy >= 100) {
        console.log("You got a cavity!");
    } else if (candy >= 95) {
        console.log("You almost got a cavity. Be careful!");
    } else if (candy >= 75) {
        console.log("You should eat less candy!");
    } else {
        console.log("You didn't get a cavity! Nice!");
    You should eat less candy!

The browser first compares 80 and 100, that returns false, and so it moves on to the first else if.

Because 80 is still not greater than or equal to 95, it moves on to the second else if.

At last, since 80 is greater than or equal to 75, that code block gets executed and the remaining else is ignored entirely.

Ternary Operator

The ternary operator is a shorthand way to represent a conditional that returns a value that you can then use to assign to a variable.

    var number = 25;
    var isEven = (number % 2 === 0) ? "Yes" : "No";

    console.log("Is " + number + " an even number? " + isEven);
    Is 25 an even number? No

If the number is even, the variable isEven gets a string value of Yes. Otherwise, it gets No.

Ternary operators are useful for condensing an entire conditional into a single line.

1and1 placeholder image

Switch Statement

We know that when we want to test for multiple different conditions, we can chain them using else if. Another way to test for many different conditions is using a switch statement. They work like else ifs except that the code can be more concise and cleaner.

Let's see a switch statement in action:

    function getFruitByColor(color) {
    	switch (color) {
        	case "red":
        		return "apple";
        	case "yellow":
        		return "banana"
            case "orange":
                return "orange"
            case "green":
                return "pear"
        	   return "grape"

    var favoriteColor = "yellow";
    var fruit = getFruitByColor(favoriteColor);

    console.log("I want to eat a " + fruit);
    I want to eat a banana

In the getFruitByColor function, we have a switch statement that switches on the color variable. In the case that the variable is equal to red, we return the string apple then break to prevent the function from checking further cases.

If color does not equal red, the function moves on to check if it matches yellow. This continues until the end where, if there are no cases that match color, it will follow the default path and return grape.

Logical Operators

So far, we've only been checking a single condition, and then acting upon it. There will be times where you need to check multiple conditions before being able to make a decision.

If you wanted to write a program to check whether or not you should tie your shoe, you can, for example, first check that you're even wearing shoes at all, but then also check if they need to be tied.

To check both conditions at the same time, we can use a logical operator.

And (&&)

By using the and operator, the code block will only execute if both conditions are true:

    var wearingShoes = true;
    var needsTying = true;

    if (wearingShoes && needsTying) {
        console.log("I should tie my shoes!");
    I should tie my shoes!

As mentioned before, both conditions need to evaluate to true for the code block to execute, and since both were set to true, we got our expected output.

Or (||)

In other cases, you might not need both conditions to be true to want to proceed with the code block. Maybe just one being true is all you need.

Consider the case where you want some candy but don't really care what kind. This is a perfect opportunity to use the or logical operator.

    var thereIsSnickers = false;
    var thereIsSkittles = true;

    if (thereIsSnickers || thereIsSkittles) {
        console.log("I'm glad there's candy in this house!");
    I'm glad there's candy in this house!

Because you only want candy, regardless of the brand, you are happy with either one. Only one of two need to be true for the entire conditional to be true and for the following code to execute.

Not (!)

In our final logical operator, you can test the opposite value of an outcome by using the not operator. Let's say you only wear boots when it isn't hot.

This scenario is easily represented like so:

    var temperature = 50;
    var itIsHot = temperature > 70;

    if (!itIsHot) {
        console.log("I will wear my boots today!");
    I will wear my boots today!

You would only wear boots if the temperature for the day doesn't exceed 70 degrees. Since today is only 50 degrees, it isn't too hot to wear boots and therefore you wear them today.

That's it for logic and conditionals! Up next, all the loops! For loops, while loops, do while loops!