This content originally appeared on Envato Tuts+ Tutorials and was authored by Alberta Williams
In part one of this series, we learned the basics of coding with JavaScript and mostly wrote simple statements as part of our code. 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.
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; ... }
The condition is an expression that has the value true or false or evaluates to 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"); }
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. }
Quiz
What will be the output of this program?
let isLoggedIn = false; if (isLoggedIn) { console.log("Welcome"); } else { console.log("You are not logged in"); }
Ternary Operator
The if-else statements are so common in programming that there is a dedicated ternary operator that allows you to write simple if-else statements in a single line. The ternary operator is the only operator in JavaScript that takes three operands.
The operator accepts a condition at the beginning followed by a question mark. The question mark is followed by an expression which is executed if the condition evaluates to a truth value. The expression is followed by a colon. We have yet another expression after the colon which is executed if the condition evaluates to a false value.
Let's see an example to make it clear. We begin with a sale_price
that is equal to the max_price
variable. Now, we change the sale_price
to 900 if the value of big_discount
evaluates to true
. Otherwise, the sale_price
value is set to 950. Since, we have set big_discount
to true
, the sale_price
value is ultimately set to 900.
let big_discount = true; let max_price = 1000; let sale_price = max_price; if(big_discount) { sale_price = 900; } else { sale_price = 950; }
Here is the equivalent code written using the ternary operator in the last line. Basically, the sale_price
will be set to 900 if big_discount
evaluates to true
and sale_price
will be set to 950 if big_discount
evaluates to false
. Just like previous example, the value of big_discount
is set to true
so sale_price
is set to 900.
let big_discount = true; let max_price = 1000; let sale_price = max_price; sale_price = big_discount ? 900 : 950;
Multiple If-Else Statements
It is also possible to check for more than one condition. Let's say you are keep tracking of the stock of a particular product in a store and taking certain actions based on its stock count. The code would look something like this:
let stock_count = 50; if(stock_count > 80) { console.log("Large stock"); } else if (stock_count > 20) { console.log("Be Ready to Restock"); } else if (stock_count > 0) { console.log("Please Restock"); } else { console.log("Stop Selling"); } // Outputs: Be Ready to Restock
You should notice how I use else if
and not just if
for writing multiple conditions. This is the way to go if you only want one block to execute. Using only if
for writing your conditionals can result in execution of multiple blocks as shown below:
let stock_count = 50; if(stock_count > 80) { console.log("Large stock"); } if (stock_count > 20) { console.log("Be Ready to Restock"); } if (stock_count > 0) { console.log("Please Restock"); } else { console.log("Stop Selling"); } /* Outputs: Be Ready to Restock Please Restock */
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. }
Chained Ternary Operator
We have already discussed how ternary operators can help us write more compact code by replacing simple if-else
statements. You can use chained ternary operators in a similar manner to replicate multiple if-else
statements. Here is an example:
let stock_count = 50; console.log((stock_count > 80) ? "Large stock" : (stock_count > 20) ? "Be Ready to Restock" : (stock_count > 0) ? "Please Restock" : "Stop Selling"); // Outputs: Be Ready to Restock
Just like a regular if-else
statement, we begin by checking if the stock_count
is over 80. Since it isn't, we go to the next condition where we check if stock_count
is over 20. This evaluates to true
so we get the string "Be Ready to Restock".
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 x is between 60 and 100 inclusive.
if (x >= 60 && x <= 100) console.log("Between 60 and 100.");
||
truth table:
P | Q | P || Q |
---|---|---|
true | true | true |
true | false | true |
false | true | true |
false | false | false |
This example tests if 82 is outside the range 60–100:
if (x < 60 || x > 100) console.log("Less than 60 or more than 100.");
!
truth table:
P | !P |
---|---|
true | false |
false | true |
Example:
if (! x) console.log("x iS 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.
In the next part of this series, you will learn about loops.
This post has been updated with contributions from Monty Shokeen. Monty is a full-stack developer who also loves to write tutorials, and to learn about new JavaScript libraries.
This content originally appeared on Envato Tuts+ Tutorials and was authored by Alberta Williams
Alberta Williams | Sciencx (2017-08-02T09:48:36+00:00) Learn to Code With JavaScript: Part 2, Conditionals. Retrieved from https://www.scien.cx/2017/08/02/learn-to-code-with-javascript-part-2-conditionals/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.