Conditional statements are used to perform different actions based on different conditions . When writing code, we often want to perform a set of specific or different actions for different decisions.
For example, in a program that functions as a temperature metric converter, we would want to display to the user both their selected temperature and metric, as well as the converted temperature and metric (e.g. if the user wants to convert 32C to F, we would want our program to perform a specific set of actions for converting from Celcius to Fahrenheit). You can use conditional statements to do this.
In JavaScript we have the following conditional statements:
Using the temperature converter example from above, the following JavaScript program prompts a user for a metric and temperature they want converted, and the metric they want to convert to. The program then converts the inputted metric and temperature to the selected metric's temperature, using an if...else statement, and outputs a string stating both the inputted temperature and converted temerature, e.g. 0°C is 32°F.
Step 1:
First, we want to have reassignable variables, so we declare them with the let keyword, and prompt the user to select the metric and temperature they want converted, as well as the metric they want it converted to:
Step 2:
Next, we use the if..else if..else conditional statements to convert the inputted temperature to the desired metric:
This example demonstrates how we can use conditional statements to check if an inputted word is a palindrome (i.e. the word is spelled the same forwards and backwards).
The function in this example is called checkPalindrome(). It prompts a user to input any word, then reverses the word and saves it to a new string, using a while loop. It then compares the inputted string with the new string, using an if...else conditional statement, and outputs the result to the <p id="conditionalsExample"> element in the conditionals.html file.
See this conditional statement in action by clicking the button below. To see what's going on behind the scenes, right-click anywhere on the page and click inspect.