Introduction

Life is all about choices. You are presented with different situations, and you will have to respond according to predefined rules or conditions that must be met. These rules or conditions are often based on your values, legal requirements, societal norms and life situation.

Let’s say you’re looking for a job. If you’re desperate, the condition for what you deem a suitable job position is simply that the job will help pay the bills. If you’re looking for an improvement in your current vocation or climbing the career ladder, you might have many more conditions to meet to be willing to take the job.

Imagine you’re considering taking a job based on the annual remuneration and work description.

The decision path could look something like this:

1. Is the salary below USD40.000?

  • if yes: DECISION: The salary is too low to consider taking the job
  • if no:
  • 2. Is the salary range between USD40-50.000 per annum?
    • if yes: Does the job description entice me?
      • if no: DECISION: Not taking the job due to the salary being too low and job description not enticing
      • if yes: DECISION: Take the job and compromise on the salary due to enticing job description
    • if no:
      • 3. Is the salary offered more or equal to USD70.000 per annum?
        • If yes: DECISION: Take the job whether the job description is enticing or not

Making decisions in programming is similar to what we’ve been looking at above. In JavaScript, we would write it like this:

if (salary < 40.0) {
  console.log("DECISION: The salary is too low to consider taking the job");
} else if (salary >= 40.0 && salary <= 50.0) {
  if (enticing === False) {
    console.log(
      "DECISION: Not taking the job due to the salary being too low and job description not enticing"
    );
  } else {
    console.log(
      "DECISION: Take the job and compromise on the salary due to enticing job description"
    );
  }
} else if (salary >= 70.0) {
  console.log(
    "DECISION: Take the job whether the job description is enticing or not due to great pay"
  );
}

In this piece of code, we use symbols like >=, <=, === and &&. These symbols are called operators, and you have many different types of them.

Operators make the code less verbose and easier to read. Instead of writing something like, let’s say, if(salary isMoreThanOrEqualTo 70.000 AND salary isLessThanOrEqualTo 90.000), we write if(salary >= 70.000 && salary <= 90.000). The latter is much easier to read and is the only version which would work, coincidentally.

Comparison operators

Now we will look at comparison operators, which compare their operands (the values on either side of the operator) and return a boolean value.

variable types


List of operators

Operator Description Example Result
=== equal to 3 === 2 false
!== not equal to 3 !== 2 true
> greater than 6 > 4 true
>= greater than or equal to 5 >= 4 true
< less than 5 < 4 false
<= less than or equal to 3 <= 4 true

To test how the comparison operators work, we can use the console.log() method and view the output.

console.log(7 === 7) // Output: True
console.log(7 === 10) // Output: False

Here we are simply testing for equality between the operands, and JavaScript will output either True or False.

We can try some more cases, now using a value stored in a variable myNumber and myString.

var myNumber = 7;
var myString = "dog";

// is myNumber greater than 8?
console.log(myNumber > 8) // Output: False

  // is myNumber less than or equal to 7?
 console.log(myNumber <= 8) // Output: True

  // is myString exactly equal to "dog"?
 console.log(myString === "dog") // Output: True

  // is myString not equal to "cat"?
  console.log(myString !== "cat") // Output:  True

These operators are commonly used with conditional statements (covered below) to make a code decision depending on the value of a variable.

Equality (==) and Inequality (!=) Operators vs Strict Equality (===) and Strict Inequality (!==) Operators

You may see the == and != operators. These are similar to === and !==.

The === operator checks that both the values and type of the variables being compared are equal, whereas == only checks that the value and not the type are equal.

Using ===, the following returns false and one value is a number value, and one is a string value.

7 === "7";
// false

Making the same comparison with == returns true, as the differences in type are ignored.

7 == "7";
// true

Always === and !==. It’s important to check the type of the variable as well as the value, which helps to avoid bugs and odd behaviour

Conditional statements

if… else

When we need to make decisions in our code, we use conditional statements.

We check if a certain condition is true using a comparison operator, and if it is, we run a block of code.

If it is false, we run a different code.


Conditional statement
Figure: Conditional statement


To carry out the above, we use if...else statements.

if a certain condition is true, run this code. else, run this other code.


if statement
Figure: if statement


Perhaps you need to check whether a user is logged in:

var isLoggedIn = true;

if (isLoggedIn === true) {
  console.log("The user is logged in");
} else {
  console.log("The user is logged out");
}

Or whether a user has entered valid data into an input field in a form:

var inputIsValid = false;

if (inputIsValid === false) {
  // show error message
} else {
  // hide error message
}

The video below examines if statements.

Watch on Vimeo

Code from the video

if…else if…else

When you need to check multiple conditions, you use else if blocks, like in the video above.

But reading multiple else if blocks becomes difficult, as this code from the video shows.

var grade = 7;
var letterGrade;

if (grade === 10) {
  letterGrade = "A";
} else if (grade === 9) {
  letterGrade = "A";
} else if (grade === 8) {
  letterGrade = "B";
} else if (grade === 7) {
  letterGrade = "C";
} else {
  letterGrade = "Unkown";
}

In this scenario, it’s time to turn to switch statements.

switch

The code above converted to a switch statement would look like this:

var grade = 7;
var letterGrade;

switch (grade) {
  case 10:
  case 9:
    letterGrade = "A";
    break;
  case 8:
    letterGrade = "B";
    break;
  case 7:
    letterGrade = "C";
    break;
  default:
    letterGrade = "Unkown";
}

The switch statement receives a variable to check in the parenthesis (round brackets).

Inside the curly braces {} are several case blocks:

case 8:
    letterGrade = "B";
    break;

The above means: in the case of grade being equal to 8, run the code after the colon : and before the break.

This is the equivalent of the following:

if (grade === 8) {
  letterGrade = "B";
}

The code after default: runs if none of the conditions in the case blocks is true. It’s like an else block in an if..else if...else statement.

The break keyword is important. If you leave it out, the code will below be executed, so be sure to include it in your case blocks.

Watch on Vimeo

Code from the video

When to use a switch instead of if

If you find yourself writing more than one else if statement, consider using a switch instead.

Assignment vs comparison

In the previous lesson, we assigned values to variables using the = assignment operator.

A common mistake is to accidentally use the = operator instead of a comparison operator when performing a check. When that happens, the comparison will always return true:

var myPet = "pig";

if ((myPet = "sheep")) {
  console.log("My pet is a sheep");
} else {
  console.log("My pet is not a sheep");
}

Above, we’ve assigned “pig” to the variable myPet but in the if statement, we’ve re-assigned myPet the value “sheep” because we’ve used the assignment operator rather than the equality comparison operator ===.

So this statement will always log “My pet is a sheep”.

If your if statements are behaving strangely, remember to check for this easy-to-make mistake.

This video looks at the assignment operator (=) versus the comparison operator (===).

Watch on Vimeo



Lesson Task

There are practice questions in the master branch of this repo.

There are example answers in the answers branch.

Try the exercises before checking the solutions.

Tags: