Program Flow: Conditional Statements
Explore how to control JavaScript program flow using conditional statements like if, else if, and else. Understand how to execute code based on specific conditions to create dynamic and responsive web applications.
We'll cover the following...
Conditional statements are another way we can control the flow of our program. They allow us to execute code only under certain conditions that we define. Conditional statements are incredibly useful for defining exactly under what circumstances a block of code will run.
The if statement
Let’s start with an example. Given the variable temperature, we want to inform a user about weather conditions.
Let’s say we want to go beyond just giving the temperature value and want to inform users on whether or not they should wear a jacket. How could this be done programmatically?
We can add a statement that will only execute if the temperature meets a certain condition.
Conditional statements rely on providing a boolean value that can determine whether a code block (the statements between the {} curly braces) should execute.
In the above example, temperature <= 65 will return true if the temperature is less than or equal to 65. Otherwise, it will return false. Therefore, the code within the if statement will only run if temperature is less than or equal to 65.
The below example illustrates how conditional execution works by directly providing true or false values:
The if/else statement
Let’s take another look at our weather example. What if we want to include a statement about warmer weather, if the temperature is greater than 65?
One way we could do this is by creating another if condition:
Though the above code is perfectly valid, there is a better way to write this. Since we are trying to execute certain code if a condition is true, and execute another set of code otherwise, we can use an if/else statement like this:
Although both examples result in the same output, the second version is better practice because it more clearly indicates the intent of the code found in the conditional statements.
Exercise
Write a function that indicates whether or not to sell a stock. Use conditional statements to return a boolean value that:
- Returns
trueifstockPriceis greater than or equal tosellPrice. - Returns
falseifstockPriceis less thansellPrice.
The if/else if/else statement
Looking again to the weather example, what if you wanted multiple statements for various temperatures?
Adding an else if allows us to make additional checks when the if condition is false. Let’s take a look at how this works:
The condition in the else if statement will only be evaluated after the first if condition is false. If the else if condition is also false, the code in the else block will execute.
Multiple else if statements can also be chained together, like this:
The second else if will only be evaluated if the first else if condition is false, and so on and so forth.