If/else statements
Let’s say you’re walking on a busy street in the middle of town. You’re about to cross the road when you notice the traffic light for pedestrians turns red. What do you do?
You stop, don’t you?
And what happens when the light turns green again? You start walking.
We can put this analogy into code too. It sounds something like: “If the light turns red, stop walking. Otherwise, continue walking”.
That’s the foundation of an if/else
statement.
The if/else statement
The if/else
statement helps to control what your program does in specified situations. Since it controls how your program runs, it is also called a control flow statement. It looks like this:
if (condition) {
// Do something
} else {
// Do some other thing
}
The condition
tells JavaScript what to check for before continuing. If the condition evaluates to true
, JavaScript executes the code from the if
block; if the condition evaluates to false
, JavaScript executes code from the else
block.
In the traffic light example, we check whether the light is red:
// Note: This example doesn't contain valid code yet
if (light is red) {
stop walking
} else {
continue walking
}
If you need to check for more than one condition, you can use else if
, which goes between if
and else
.
When would you need such a second condition?
Well, let’s say you want to cross a small road. If there aren’t any cars around, would you wait for the traffic light to turn green? You still cross, don’t you?
In code, this would look like:
if (light is red) {
// Stop walking
} else if (cars around) {
// Stop walking
} else if (yet another condition) {
// Do yet another thing
} else {
// Do the final thing
}
In this case, if the first condition evaluates to true
, JavaScript executes the code in the if
block.
If the first condition evaluates to false
, JavaScript checks the condition in the next else if
block and see whether it evaluates to true
. It goes on and on until all else if
blocks are exhausted.
To check whether a condition evaluates to true
or false
, JavaScript relies on two things:
- Comparison operators
- Truthy and falsey values
Let’s talk about comparison operators first.
Comparison operators
There are four main types of comparison operators:
- Greater than (
>
) or greater or equals to (>=
)
- Smaller than (
<
) or smaller or equals to (<=
)
- Strictly equal (
===
) or equal (==
)
- Strictly unequal (
!==
) or unequal (!=
)
The first two types of comparison operators are straightforward. You use them to compare numbers.
24 > 23 // True
24 > 24 // False
24 >= 24 // True
24 < 25 // True
24 < 24 // False
24 <= 24 // True
The next two types of comparison operators are quite straightforward as well. You use them to check whether things are equal or unequal to each other.
24 === 24 // True
24 !== 24 // False
However, there’s a difference between strictly equal (===
) vs equal (==
), and strictly unequal (!==
) vs unequal (!=
):
'24' === 24 // False
'24' == 24 // True
'24' !== 24 // True
'24' != 24 // False
As you can see from the example above, when you compare a string of 24
vs the number 24, ===
evaluates to false
while ==
evaluates to true
.
Why is this so? Let’s look at the difference between strictly equal and equal.
=== vs == (or !== vs !=)
JavaScript is a loosely-typed language. What this means is that, when we declare variables, we don’t care what type of value goes into the variable.
You can declare any primitive or object, and JavaScript does the rest for you automatically:
const aString = 'Some string'
const aNumber = 123
const aBoolean = true
When comparing things with strictly equal (===
) or strictly unequal (!==
), JavaScript checks two things:
- The type of the variable
- The value of the variable
This is why a string of 24
and a number 24
do not equate.
'24' === 24 // False
'24' !== 24 // True
When comparing things with equal (==
) or unequal (!=
), JavaScript converts (or casts) the types so they match each other.
Generally, JavaScript tries to convert all types to numbers when you use a comparison operator. In the example below, the string 24
is converted into the number 24 before the comparison.
That’s why a string of 24
equates to a number of 24 when you use ==
.
'24' == 24 // True
'24' != 24 // False
Booleans can also be converted into numbers. When JavaScript converts Booleans into numbers, true
becomes 1 and false
becomes 0.
0 == false // True
1 == true // True
2 == true // False
Automatic type conversion (when using comparison operators) is one of the common causes of hard-to-find bugs. Whenever you compare for equality, always use the strict versions (===
or !==
).
Comparing objects
Try comparing objects with ===
or ==
. You’ll be very surprised.
const zell = { isHavingFun: true }
const vincy = { isHavingFun: true }
console.log(zell === vincy) // false
console.log(zell == vincy) // false
In the example above, both zell
and vincy
look exactly the same. They are both objects, they have the same values. The strange thing is, zell === vincy
is always going to be false. Why?
Let’s say you have an identical twin brother/sister. You look exactly the same as your twin. Same hair color, same face, same clothes, same everything. How can people differentiate the two of you? It’ll be hard.
In JavaScript, each object has a “identity card”. This identity card is called the reference to the object. When you compare objects with equality operators, you’re asking JavaScript to check if the two objects have the same reference (same identity card).
Is it a surprise that zell === vincy
is always going to be false now? No two humans are the same!
Let’s tweak it a little and assign zell
to vincy
.
const zell = { isHavingFun: true }
const vincy = zell
In this case, zell === vincy
evaluates to true because vincy
now points to the same reference as zell
.
console.log(zell === vincy) // true
Checking if two objects have the same value
To check if two objects have the same property-value pairs, you need to compare every property-value pairs between the two objects. We’ll look at this in a later lesson.
Truthy and Falsey
If you write a single variable (like numApples
in the example below) as the condition of an if/else
statement, JavaScript checks for a truthy or a falsey value.
const numApples = 135
if (numApples) {
// Eat an apple
} else {
// Buy an apples
}
A falsey value is a value that evaluates to false
when converted into a boolean. There are six possible falsey values in JavaScript:
false
undefined
null
0
(numeric zero)
""
(empty string)
NaN
(Not A Number)
A truthy value, on the other hand, is a value that evaluates to true
when converted into a Boolean. In the case of numbers, anything that’s not 0
converts to true
.
Automatic type conversion to truthy and falsey values are highly encouraged in JavaScript, because they make code shorter and easier to comprehend.
For example, if you want to check if a string is empty, you can use the string in the condition straightaway.
const str = ''
if (str) {
// Do something if string is not empty
} else {
// Do something if string is empty
}
Exercise
Controlling the flow of a program with if/else
statements is incredibly important. Try the following exercises:
const james = 22
const valerie = 25
const kenneth = 27
James is 22 years old, Valerie is 25 years old, Kenneth is 27 years old. Answer the following questions with the above code:
- Make an
if/else
statement to check if you are younger than James.
- Make an
else if
statement within your if/else
to check if you are older than Valerie.
- Make another
else if
statement to check if you’re as old as Kenneth.
When you do the above exercise, try comparing values with:
>
and >=
<
and <=
===
!==
Answer the rest of the questions below with reference to the following code:
const someValue = 22
if (someValue) {
// Executes if true
} else {
// Executes if false
}
Would the if
statement above execute:
- If
someValue
is false
?
- If
someValue
is true
?
- If
someValue
is null
?
- If
someValue
is undefined
?
- If
someValue
is 0
?
- If
someValue
is -1
?
- If
someValue
is ''
?
- If
someValue
is 'has a value!'
?
- If
someValue
is {}
?
- If
someValue
is { isHavingFun: true }
?
- If
someValue
is []
?
- If
someValue
is ['one', 'two', 'three']
?