Ifs, Else Ifs, Switch
Table of Contents
Logic
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
With the equality operator, we can now check if two values are equal or not.
If two values 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 two equal signs.
JAVASCRIPTconsole.log(5 == 5);
const pears = 40 / 2;
console.log(20 == pears);
console.log(17 == 10);
HTMLtrue
true
false
Strict Equality Operator
The strict equality operator is used to check if two values are strictly equal. This means that the values have to be the same type, and the same value. What is the difference between the strict equality operator and the equality operator? The difference is that the strict equality operator will not use type coercion to convert the values to the same type, whereas the equality operator will.
To use the strict equality operator, just use three equal signs with a space in between.
JAVASCRIPTconsole.log(23 === 23);
const pears = 50 / 2;
console.log(25 === pears);
console.log(13 === 561);
HTMLtrue
true
false
Let's see how the equality operator is different from the strict equality operator.
JAVASCRIPTconsole.log(23 === '23');
const pears = 50 / 2;
console.log(25 === '25');
console.log(13 === '561');
HTMLfalse
false
false
All of these comparisons are false
, because the values are not strictly equal. The left-hand side of the comparison is a number, and the right-hand side is a string, so the types are not strictly equal. However, if we use type coercion, the values will be converted to the same type, and the comparison will be true.
JAVASCRIPTconsole.log(23 == '23');
const pears = 50 / 2;
console.log(25 == '25');
HTMLtrue
true
Even though the values are not strictly equal, the comparison is still true because the values are converted to the same type, and the comparison is true. That is the difference between the strict equality operator and the equality operator.
Inequality Operator
The inequality operator works basically like the equality operator but in the reverse. If two values are the same, it will result in false
, while if two values are different, it will result in true
.
To use this operator, you use a single exclamation point followed by an equal sign.
JAVASCRIPTconsole.log(9 != 7);
const oranges = 5 * 6;
console.log(30 != oranges);
console.log(57 != 57);
HTMLtrue
false
false
Strict Inequality Operator
The strict inequality operator is used to check if two values are strictly different. Let's see an example:
JAVASCRIPTconsole.log(9 !== 7);
const oranges = 5 * 6;
console.log(30 !== oranges);
console.log(57 !== 57);
HTMLtrue
false
false
Like before, the values are being strictly compared, meaning that the types are not being converted.
Greater Than Operator
You can check whether a value is greater than than another one. This allows you to compare the two values.
Use the greater than operator via the greater than symbol.
JAVASCRIPTconsole.log(6 < 4);
console.log(8 < 13);
HTMLfalse
true
Less Than Operator
You can check whether a value is less than another one. Use the less than operator via the less than symbol.
JAVASCRIPTconst books = 32;
console.log(books > 30);
console.log(books > 50);
HTMLtrue
false
Or Equal To Operators
In the case that you need to check if a value is either less than/greater than or equal to another value, 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.
JAVASCRIPTconsole.log(29 <= 94);
console.log(13 <= 9);
console.log(32 >= 32);
console.log(42 >= 85);
HTMLtrue
false
true
false
Conditionals
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.
If
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.
JAVASCRIPTconst candy = 110;
if (candy >= 100) {
console.log("You got a cavity!");
}
HTMLYou 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.
JAVASCRIPTconst candy = 80;
if (candy >= 100) {
console.log("You got a cavity!");
}
HTML
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.
Else
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.
JAVASCRIPTconst candy = 80;
if (candy >= 100) {
console.log("You got a cavity!");
} else {
console.log("You didn't get a cavity! Nice!");
}
HTMLYou 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.
JAVASCRIPTconst 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!");
}
HTMLYou 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.
JAVASCRIPTconst number = 25;
const isEven = (number % 2 === 0) ? "Yes" : "No";
console.log("Is " + number + " an even number? " + isEven);
HTMLIs 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. They are also useful for returning a value from a function.
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:
JAVASCRIPTfunction getFruitByColor(color) {
switch (color) {
case "red":
return "apple";
case "yellow":
return "banana";
case "orange":
return "orange";
case "green":
return "pear";
default:
return "grape";
}
}
const favoriteColor = "yellow";
const fruit = getFruitByColor(favoriteColor);
console.log("I want to eat a " + fruit);
HTMLI 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:
JAVASCRIPTconst wearingShoes = true;
const needsTying = true;
if (wearingShoes && needsTying) {
console.log("I should tie my shoes!");
}
HTMLI 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. It will only execute if one of the conditions is true.
JAVASCRIPTconst thereIsSnickers = false;
const thereIsSkittles = true;
if (thereIsSnickers || thereIsSkittles) {
console.log("I'm glad there's candy in this house!");
}
HTMLI'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:
JAVASCRIPTconst temperature = 50;
const itIsHot = temperature > 70;
if (!itIsHot) {
console.log("I will wear my boots today!");
}
HTMLI 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.
Resources
- Getting Started with TypeScript
- Git Tutorial: Learn how to use Version Control
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Setting Up Stylus CSS Preprocessor