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…
- Do you walk or stop? Obviously, you stop.
- Now what happens when the light turns green? Obviously, you walk.
This simple analogy forms the basic logic behind if/else statements:
- If the light is red, stop walking
- If the light is green, continue walking
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 is an expression — so you can use any kind of expression here.
- If the condition evaluates to
true, JavaScript executes the code from theifblock - If the condition evaluates to
false, JavaScript executes code from theelseblock.
We say true and false to keep things simple here — but in reality
JavaScript evaluates the truthiness or falsiness of the epression. More on
this in a bit.
In the traffic light example, we check whether the light is red:
// Pseudo code. Code doesn't work, but it illustrates how you'll structure it with language.if (light is red) { stop walking} else { continue walking}Else if
If you want to check for several conditions, you can use else if, which goes between if and else.
For example, let’s say you want to cross a small road only when one of these two conditions are true:
- When the light turns green
- When there are no cars around
In code, this would look like:
if (light is green) { // Walk} else if (no cars around) { // Walk} else { // Stop}Here’s what happens in an if, else if, else block:
- If the first condition evaluates to
true, JavaScript executes the code in theifblock. - If the first condition evaluates to
false, JavaScript checks the condition in the nextelse ifblock and see whether it evaluates totrue. If this condition evaluates totrue, JavaScript executes the code in thatelse ifblock. - If the
else ifcondition isfalse, JavaScript continues into the nextelse ifblock (if any). - If there are no more
else ifblocks, JavaScript goes into theelseblock and executes the code there.
Now this is important — we used true and false to keep things simple. But JavaScript doesn’t actually check whether the condition is true or false. It checks whether a condition is truthy or falsey instead.
Truthy and Falsey
Every condition is an expression, so every condition an if/else block will be checked for truthiness or falseiness.
if (condition) { // Runs this block if condition is truthy} else { // Runs this block if condition is falsey}Falsey expressions are expressions that evaluates to false when it’s converted into a Boolean in JavaScript. There are six possible falsey values:
falseundefinednull0(numeric zero)""(empty string)NaN(Not A Number)
Truthy expressions are the opposite. Truthy expressions are expressions that evaluates to true when it’s converted into a Boolean.
- Truthy values are all values that’s not falsey.
The process of converting truthy and falsey values to true or false is called automatic type conversion.
Automatic type conversion is highly encouraged in JavaScript because they allow you to write code that’s 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 without coverting it into a Boolean.
const str = ''
if (str) { // Do something if string is not empty} else { // Do something if string is empty}Besides truthy and falsey values, JavaScript can also use comparison operators to evaluate whether a condition is true or false.
Comparison operators
There are four main types of comparison operators:
- Greater than (
>) and greater or equals to (>=) - Smaller than (
<) and smaller or equals to (<=) - Strictly equal (
===) and equal (==) - Strictly unequal (
!==) and unequal (!=)
The first two types of comparison operators are straightforward. You use them to compare numbers.
24 > 23 // True24 > 24 // False24 >= 24 // True
24 < 25 // True24 < 24 // False24 <= 24 // TrueThe 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 // True24 !== 24 // FalseHowever, 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 // FalseAs 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.
Strict equality vs loose equality (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:
// JavaScript doesn't care what you put into a variableconst aString = 'Some string'const aNumber = 123const aBoolean = trueWhen you compare things with strict equality (=== or ==), JavaScript checks for 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 // TrueWhen you campare things with loose quality (== or!=), 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.
This is why a string of 24 is loosely equal to the number 24.
'24' == 24 // True'24' != 24 // FalseBooleans can also be converted into numbers. When JavaScript converts Booleans into numbers, true becomes 1 and false becomes 0.
0 == false // True1 == true // True2 == true // FalseAutomatic 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 !==).
Exercise
Controlling the flow of a program with if/else statements is incredibly important. Try answering the following questions.
- James is 22 years old, Valerie is 25 years old, Kenneth is 27 years old.
- Make an
ifstatement to check if you are younger than James. - Make an
else ifstatement to check if you are older than Valerie. - Make another
else ifstatement to check if you’re as old as Kenneth.
- Make an
Hint: When you do the above exercise, use all four types of comparison operators when you work through this question. You may use this code as a starting point:
const james = 22const valerie = 25const kenneth = 27- Answer the rest of the questions below with reference to the following code:
if (someValue) { // Executes if true} else { // Executes if false}- In which of these statements will the
ifblock execute? - In which of these statements will the
elseblock execute? - When…
someValueisfalsesomeValueistruesomeValueisnullsomeValueisundefinedsomeValueis0someValueis-1someValueis''someValueis'has a value!'someValueis{}someValueis{ isHavingFun: true }someValueis[]someValueis['one', 'two', 'three']
- Make an if statement to check if you are younger than James.
- Make an if statement to check if you are older than Valerie.
- Make another if statement to check if you’re as old as Kenneth.
const james = 22const valerie = 25const kenneth = 27
const myAge = 30if (myAge < james) { /* Younger than james */ }if (myAge > valerie) { /* Older than valerie */ }if (myAge === kenneth) { /* Same age as kenneth */ }if (someValue) { // Executes if true} else { // Executes if false}Here’s when the if or else statement will execute:
someValueisfalse—elseexecutessomeValueistrue—ifexecutessomeValueisnull—elseexecutessomeValueisundefined—elseexecutessomeValueis0—elseexecutessomeValueis-1—ifexecutessomeValueis''—elseexecutessomeValueis'has a value!'—ifexecutessomeValueis{}—ifexecutessomeValueis{ isHavingFun: true }—ifexecutessomeValueis[]—ifexecutessomeValueis['one', 'two', 'three']—ifexecutes
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson