IF Statements
This lesson is part of the Web Programming 1 Course.
We use IF statements to control the flow of code execution in JavaScript. For example, if a certain condition is true, then we may want some code to run. But if it is false, then we may want some other code to run.
An IF statement is known as a control structure, because it's a way of controlling which code executes when your program runs. There are other control structures in JavaScript, we'll learn more about them soon.
Here is the basic structure an syntax for writing an IF statement in it's simplest form:
if(boolean expression goes here){
// the statements inside these curly braces
// will run if the boolean expression
// evaluates to true
}
Before we continue, please take a moment to notice the syntax (remember that mastering the syntax of a language is one of the biggest hurdles to a beginning programmer). It starts the keyword if, which must be lowercase letters. Then comes a boolean expression that is enclosed within parenthesis (we'll discuss boolean expressions next). Directly after the closing parenthesis, we have an opening curly brace. The matching closing curly brace marks the end of this IF statement. Note that curly braces, like parenthesis, always come in pairs It's a common mistake for beginning programmers to forget an opening or closing curly brace, which can lead to bugs and frustration. You put code in between the curly braces, and this code will execute only if the boolean expression evaluates to true.
Boolean Expressions
You might be wondering what a boolean expression is. Remember from a previous lesson that a boolean variable is one that stores either true or false. And remember that expressions is an equation that can evaluated to produce a result. For example the expression 6 + 5 can be evaluated to a result of 11. So a boolean expression is one that results in either true or false. Here is a boolean expression:
5 > (3+1)
Does this boolean expression evaluate to true, or false? Let's try it out by using it in an IF statement:
if( 5 > (3+1) ){
console.log("Yup! The boolean expression evaluates to true, which is why this message appears in the log!");
}
If you change the 'greater than' symbol to a 'less than' symbol, and reload the page in the browser, you'll notice that the message will not appear in the console log.
Notice that the statement in between the curly braces is indented, which we'll be talking about more soon.
Since we're talking about expressions, I'd like to point out that a variable all by itself is an expression because it produces a result (which is the value that the variable is storing). So, you can use a variable all by itself for the boolean expression in an IF statement:
let doneWithHomework = true;
if(doneWithHomework){
console.log("Congratulations!")
}
Checking for Equality with ==
It's extremely common to use an IF statement by checking to see if a variable matches a specific value. For example, imagine that you are creating a game in which the user must guess a secret number. The code might look something like this:
const secretNumber = 7;
const input = prompt("Enter a number");
if(input == secretNumber){
alert("You guessed the secret number!");
}
The boolean expression in the IF statement is checking to see if the values of the two variables are the same (input and secretNumber). If they are storing the same number, then the alert statement will execute.
But notice that the syntax requires you to use two equals signs in the boolean expression (==). The reason for this is that a single equals sign is used to initialize variables, which is very different than checking to see if variables are storing the same value. In the next lesson, when we talk about operators we'll get into the details. But for now note that when you want to compare two values to see if they are equal, then you must use == (which is the 'equality' operator, as you'll learn in the next lesson).
WARNING: It's very common for beginning programmers to mistakenly use = when they should be using ==
IF/ELSE Statements
In the above code samples, we only executed code if the boolean expression evaluated to true. But we often want to run different code if the boolean expression evaluates to false. In that case we can use a different form of an IF statement, known as an IF/ELSE statement. Here's the syntax for an IF/ELSE statement:
if(boolean expression goes here){
// the statements inside these curly braces
// will run if the boolean expression
// evaluates to TRUE
}else{
// the statements inside these curly braces
// will run if the boolean expression
// evaluates to FALSE
}
Let's now modify our game to use an IF/ELSE statement:
const secretNumber = 7;
const input = prompt("Enter a number");
if(input == secretNumber){
alert("You guessed the secret number!");
}else{
alert("Sorry, wrong guess!");
}
We've added the else keyword, followed by a pair of curly braces. And inside the curly braces we've added the statement(s) to execute when the user enters input that does NOT match the value of the secretNumber variable.
Let's now create another game, but this time we'll compare string values instead of numbers (remember data types!):
const answer = prompt("Who was the first president of the U.S.?");
if(answer == "George Washington"){
alert("Correct! You win!");
}else{
alert("Sorry, you lose!");
}
In this case, the boolean expression is checking to see if the value of the answer variable is equal to the string "George Washington". Remember that JavaScript is case sensitive, so the capitalization must match in order for the expression to result in true.
Curly Braces are 'Code Blocks' (aka 'Code Branches')
In many programming languages, such as JavaScript, a pair of curly braces ( { and } ) and the code inside them are known as a block of code, or a branch of code. In an IF/ELSE statement, when the boolean expression result is true, then the program will execute the first block/branch. And when false, the program will execute the second block/branch.
In all of the code blocks/branches that we've seen in this lesson so far, each one has contained just a single statement. But a block/branch can contain many statements. And it can even contain other blocks/branches, as we'll see soon.
We have already seen code blocks/branches when we learned how to declare functions.
It's very important to indent all of the statements within a block/branch of code. We did this when we declared functions, and we should also do it when we write IF statements.
Ladder IF Statements
With IF and IF/ELSE statements there is only one boolean expression, which means that you are only checking to see if one 'condition' is true or false.
We can use another variation of an IF statement to deal with more than one possible condition. For example, if our program prompts the user to enter a color, we may want to execute different code branches depending on what they input. If the color they enter is red, then our program executes a specific branch. If the color they enter is blue, then our program executes another branch. If the color they enter is yellow, our program executes yet another branch.
Here's what that code might look like:
const color = prompt("Enter a color.");
if(color == "red"){
alert("Red is hot!");
}else if(color == "blue"){
alert("Blue is cold!");
}else if(color == "yellow"){
alert("Yellow is warm!");
}
First notice that the shape of the code resembles a ladder, which is why it's known as a 'ladder' IF statement.
Also note the syntax, we used both the else and if keywords (separated by a space) before each boolean expression that comes after the first one.
Finally, you can add a branch that will execute if none of the boolean expressions result in true by modifying the IF statement to look like this:
const color = prompt("Enter a color.");
if(color == "red"){
alert("Red is hot!");
}else if(color == "blue"){
alert("Blue is cold!");
}else if(color == "yellow"){
alert("Yellow is warm!");
}else{
alert("That color is unknown to this program!");
}
If the user enters anything other than 'red','blue', or 'yellow' the final branch, which acts as a 'catch all' for any conditions where all the boolean expressions result in false.
To summarize the syntax for a ladder IF statement:
if(first boolean expression goes here){
// this code runs if the first boolean expression is true
}else if(second boolean expression goes here){
// this code runs if the second boolean expression is true
}else{
// this code runs if neither of the first nor the second
// boolean expressions are true
}
Only one branch in an IF statement will execute
It's important to note that only one branch of an IF statement will execute. It's not possible for more than one branch to execute when your program runs. Consider this example:
const age = 9;
if(age < 10){
console.log("age is less than 10");
}else if(age < 20){
console.log("age is less than 20");
}
Note that BOTH boolean expressions will result in true in this example. But IF statements will only execute the branch for the first boolean expression that results in true. All the following branches will be skipped.
Testing Your Code
We've seen the complexity of IF statements grow throughout the course of this lesson. So I'd like to point out how important it is to test your code well. Never ever assume that your code works without testing it. And to test it make sure you experiment with it to get every code branch in an IF statement to execute. To demonstrate how to manually test your code, we'll create this simple program:
const age = prompt("Enter your age");
if(age < 18){
console.log("child");
}else if(age < 40){
console.log("Adult");
}else if(age < 65){
console.log("Middle Age");
}else{
console.log("Senior Citizen");
}
If you test this enough, you'll find that there are conditions in which it doesn't work properly. We can talk about it class!