# If Statements

if statements are a common construct in most programming languages. Simply put, they are a way to let your program make decisions based on yes - no questions.

if (x == 5) {
  //notice the two equal signs?
}
1
2
3

The example above shows a simple if statement. Inside the parentheses is where you put the question you want the program to ask. Everything and anything that you place inside the parentheses will be boiled down to a yes or no answer.

Javascript uses the concepts of truthy and falsey. A question may not give you an answer which is exactly TRUE or FALSE. So, there are a handful of things that are considered equal to FALSE. Everything else is considered TRUE.

When asking questions in if statements, comparison operators are used between the values being compared. Greater than >, less than <, equal to ==, greater than or equal to >= and less than or equal to <=, are the comparison operators.

When you need to do things based on both the TRUE and FALSE conditions then you can use an if-else statement.

if (x > 5) {
  // the condition was true.
  // run this code
} else {
  // the condition was false
  // run this code
}
1
2
3
4
5
6
7

MDN reference for comparison operators

At other times you might want to do things based upon multiple possible answers. In these cases we use if - else if - else statements.

if (x == 3) {
  // if x is equal to 3
} else if (x == 4) {
  //if x is equal to 4
} else {
  //all other possible answers
}
1
2
3
4
5
6
7

You can add as many else if( ) conditions between the if and the else statements as you want.

# Two vs Three Equal Signs

The examples up to this point have all been using two equal signs. This means that we are comparing the values of the two operands.

There is another comparison operator that uses three equal signs. It compares the two operands to see if they are actually the same object.

let x = 7;
if (x == 7) {
  //this will be true
}
if (x === 7) {
  //this is also true
}
1
2
3
4
5
6
7

When dealing with primitives, it will make no difference if you use two or three equal signs. When we start comparing Objects, that is when these will matter.

As you probably guessed from this last example, you can also write if statements with only a single test for truthy.

Back to Week 2 main page

Last Updated: 6/13/2020, 11:30:19 PM