Basic Conditions
A conditional statement is one that can choose different courses of action based on a condition that can evaluate to true or false. The most common form of a condition is the if…else structure, but we will also look at switch statements.
We will begin with the standard if structure. Let’s say that we are going to build a simple guessing game in which the computer generates a random number between 1 and 100 and the user needs to guess that number. The first step would be to create a condition that checks if the user correctly guessed the number. A standard if structure checks if a condition is true. If so, the if block executes. So, we will check the user guess, called guess, against the number, called number. The code is as follows:
if(guess == number){
window.alert(“You got it!!”);
}
Note the use of '==' in the condition. A single equals sign (=) is used for assignment. A double equals sign (==) is used for comparison. Using an assignment operator in place of a comparison operator will yield unpredictable results. Other comparison operators include >, <, >=, <=, and !=.
If the guess is correct, we will send a message stating that they were correct. However, if the guess is incorrect, we should provide feedback to that as well. To do this we use an if...else structure. In an if else structure, the two blocks of code are mutually exclusive (only one can run). If the condition is true, the if block runs. If the condition is false, the else block runs. In our guessing game example, if the guess is correct, say so, otherwise (else), tell them they are incorrect.
if(guess == number){
window.alert("CORRECT!");
}
else{
window.alert("SORRY! That is not right.");
}
Note that both the if and else code blocks are enclosed in curly braces {}. This denotes where each path starts and ends.