1. Code
  2. Coding Fundamentals

Learn to Code With JavaScript: Part 2, Conditionals

Scroll to top
This post is part of a series called Learn Computer Science with JavaScript.
Learn to Code With JavaScript: Part 1, The Basics
Learn to Code With JavaScript: Part 4, Functions

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().

1
if (isRaining) {
2
    putOnCoat();
3
    putOnRainboots();
4
}
5
6
goOutside();

This is the general form for writing an if statement:

1
if (condition) {
2
    statement;
3
    statement;
4
    ...
5
}

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".

1
let grade = 93;
2
3
if (grade >= 90) {
4
    console.log("You get an A");
5
}

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.

1
let username = "alberta";
2
3
if (username === "alberta") {
4
    console.log("Valid Username");
5
} else {
6
    console.log("Incorrect username. Try again.");
7
}

This is the general form of an if-else statement:

1
if (condition) {
2
    statement;
3
    statement;
4
    etc.
5
} else {
6
    statement;
7
    statement;
8
    etc.
9
}

Quiz

 What will be the output of this program?

1
let isLoggedIn = false;
2
3
if (isLoggedIn) {
4
    console.log("Welcome");
5
} else {
6
    console.log("You are not logged in");
7
}

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.

1
let big_discount = true;
2
let max_price = 1000;
3
let sale_price = max_price;
4
5
if(big_discount) {
6
    sale_price = 900;
7
} else {
8
    sale_price = 950;
9
}

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.

1
let big_discount = true;
2
let max_price = 1000;
3
let sale_price = max_price;
4
5
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:

1
let stock_count = 50;
2
3
if(stock_count > 80) {
4
    console.log("Large stock");
5
} else if (stock_count > 20) {
6
    console.log("Be Ready to Restock");
7
} else if (stock_count > 0) {
8
    console.log("Please Restock");
9
} else {
10
    console.log("Stop Selling");
11
}
12
13
// 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:

1
let stock_count = 50;
2
3
if(stock_count > 80) {
4
    console.log("Large stock");
5
} if (stock_count > 20) {
6
    console.log("Be Ready to Restock");
7
} if (stock_count > 0) {
8
    console.log("Please Restock");
9
} else {
10
    console.log("Stop Selling");
11
}
12
13
/* Outputs:

14
Be Ready to Restock

15
Please Restock */

This is the general form for writing multiple if-else-if statements:

1
if (condition1) {
2
    statement;
3
    statement;
4
    etc.
5
} else if (condition2) {
6
    statement;
7
    statement;
8
    etc.
9
} else {
10
    statement;
11
    statement;
12
    etc.
13
}

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:

1
let stock_count = 50;
2
3
console.log((stock_count > 80) ? "Large stock" : (stock_count > 20) ? "Be Ready to Restock" : (stock_count > 0) ? "Please Restock" : "Stop Selling");
4
5
// 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:

1
let num = 3;
2
3
switch (num) {
4
    case 1:
5
        console.log("I");
6
        break;
7
    case 2:
8
        console.log("II");
9
        break;
10
    case 3:
11
        console.log("III");
12
        break;
13
    case 4:
14
       console.log("IV");
15
        break;
16
    case 5:
17
       console.log("V");
18
       break;
19
    default:
20
        console.log("Invalid input");
21
}

This is the general form of a switch statement:

1
switch (expression) {
2
    case value1:
3
        statement;
4
        statement;
5
        etc.
6
        break;
7
    case value2:
8
        statement;
9
        statement;
10
        etc.
11
        break;
12
    default:
13
        statement;
14
        statement;
15
        etc.
16
}

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.

1
if (x >= 60 && x <= 100)
2
    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:

1
if (x < 60 || x > 100) 
2
    console.log("Less than 60 or more than 100.");

! truth table:

P !P
true false
false true

Example:

1
if (! x)
2
    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.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.