Introduction
In part one of this series, our programs were only written as a sequence of statements. This structure severely limits what we can do. Say you are designing a program that needs to log in users. You may want to direct a user to one page if they give the correct credentials and send them to another if they aren’t registered.
To do this, you need to use a decision structure like an if statement. This will perform an action only under certain conditions. If the condition does not exist, the action is not performed. In this tutorial, you’ll learn all about conditionals.
Contents
- If statements
- Relational operators
- If-else statement
- Switch statements
- Logical operators
- Review
- Resources
If Statements
A single if statement will perform an action if a condition is true. If the condition is false, the program will execute the next statement that is outside of the if block. In the following example, if the expression isRaining()
is true, then we will putOnCoat()
and putOnRainboots()
then goOutside()
. If isRaining()
is false, the program will only execute goOutside()
.
if (isRaining) { putOnCoat(); putOnRainboots(); } goOutside();
This is the general form for writing an if statement:
if (condition) { statement; statement; etc. }
The condition is an expression that has the value true or false. An expression that is true or false is called a boolean expression. Boolean expressions are made with relational operators.
Relational Operators
A relational operator compares two values and determines if the relationship between them is true or false. They can be used to create boolean expressions for our conditions. Here is a list of relational operators with examples:
Operator | Meaning | Example | Meaning |
---|---|---|---|
== | equality | x == y | Is x equal to y? |
=== | strict equality | x === y | Is x equal to y in value and type? |
!= | inequality | x != y | Is x not equal to y? |
!== | strict inequality | x !== y | Is x not equal to y in value and type? |
> | greater than | x > y | Is x greater than y? |
< | less than | x < y | Is x less than y? |
>= | greater than or equal | x >= y | Is x greater than or equal to y? |
<= | less than or equal | x <= y | Is x less than or equal to y? |
It is important to note the difference between the equality operator ==
and the strict equality operator ===
. For example, the expression 2 == "2"
is true. But the expression 2 === "2"
is false. In the second example, the two values are different data types, and that is why the expression is false. It is best practice to use ===
or !==
.
The following example will display the message, “You get an A”.
let grade = 93; if (grade >= 90) { console.log("You get an A"); }
Task
What is the value of the expression 5 > 3? 6 != “6”?
If-Else Statements
An if-else statement will execute one block of statements if its condition is true, or another block if its condition is false. The following example will display the message “valid username” because the condition is true.
let username = "alberta"; if (username === "alberta") { console.log("valid username"); } else { console.log("Incorrect username. Try again."); }
This is the general form of an if-else statement:
if (condition) { statement; statement; etc. } else { statement; statement; etc. }
Task
What will be the output of this program:
let isLoggedIn = false; if (isLoggedIn) { console.log("Welcome"); } else { console.log("You are not logged in"); }
It is also possible to check for more than one condition. Example:
let num = 3; if (num === 1) { console.log("I"); } else if (num === 2) { console.log("II"); } else if (num === 3) { console.log("III"); } else if (num === 4) { console.log("IV"); } else if (num === 5) { console.log("V"); } else { console.log("Invalid input"); }
This is the general form for writing multiple if-else-if statements:
if (condition1) { statement; statement; etc. } else if (condition2) { statement; statement; etc. } else { statement; statement; etc. }
Switch Statements
A switch statement is also used to conditionally execute some part of your program. The following example implements our roman numeral converter as a switch statement:
let num = 3; switch (num) { case 1: console.log("I"); break; case 2: console.log("II"); break; case 3: console.log("III"); break; case 4: console.log("IV"); break; case 5: console.log("V"); break; default: console.log("Invalid input"); }
This is the general form of a switch statement:
switch (expression) { case value1: statement; statement; etc. break; case value2: statement; statement; etc. break; default: statement; statement; etc. }
Each case represents a value our expression can take. Only the block of code for the case that is true will execute. We include a break statement at the end of the code block so that the program exits the switch statement and doesn’t execute any other cases. The default case executes when none of the other cases are true.
Task
Write a switch statement that displays the day of the week given a number. For example, 1 = Sunday, 2 = Monday, etc.
Logical Operators
The and operator &&
and the or operator ||
allow us to connect two boolean expressions. The not operator !
negates an expression. To illustrate how logical operators work, we will look at a truth table. A truth table contains all the combinations of values used with the operators. I use P to represent the left-hand expression and Q for the right-hand expression.
&&
truth table:
P | Q | P && Q |
---|---|---|
true | true | true |
true | false | false |
false | true | false |
false | false | false |
We read the table going across each row. The first row tells us that when P is true and Q is true, P && Q is true. The following example tests whether 82 is between 60 and 100 inclusive.
- let x = 82;
- x >= 60 && x <= 100
- P: x >= 60 is true
- Q: x <= 100 is true
- P && Q: true && true
||
truth table:
P | Q | P || Q |
---|---|---|
true | true | true |
true | false | true |
false | false | true |
false | false | false |
This example tests if 82 is outside the range 60–100:
- let x = 82;
- x < 60 || x > 100
- P: x < 60 is false
- Q: x > 100 is false
- P || Q: false || false
!
truth table:
P | !P |
---|---|
true | false |
false | true |
Example:
- x = 82
- P: x > 0 is true
- !P: false
Task
Fill in the table with the missing values.
P | Q | !P | !Q | !P && !Q | !P || !Q |
---|---|---|---|---|---|
true | true | ||||
true | false | ||||
false | true | ||||
false | false |
Something useful to know about logical operators is that if the expression on the left side of the &&
operator is false, the expression on the right will not be checked because the entire statement is false. And if the expression on the left-hand side of an ||
operator is true, the expression on the right will not be checked because the entire statement is true.
Review
A program can execute blocks of code conditionally using boolean expressions. A boolean expression is written using relational operators. Logical operators allow us to combine boolean expressions.
A single if statement gives the program one alternative path to take if a condition is met. If-else statements provide a second course of action if the condition is false. And if-else-if statements allow us to test multiple conditions. Switch statements can be used as an alternative to an if-else-if statement when you have multiple conditions to test.
Next, in part 3, we will discuss loops.
Resources
- repl.it
- ES6 specification
- You Don’t Know JS: ES6 and Beyond
Powered by WPeMatico