If your new to programming, this will be a great tutorial for the fundamentals of programming logic. An if statement is one of a few ways to do something when a condition is set. It helps control the flow of your coding logic.
If you are thirsty, take a drink.
We are just going to assume that from now that the code in the examples are embedded in the <script> tags that are in the body of an HTML document.
The == is one of the comparison operators. It is not the same as = that sets a variable or property equal to something. Since, the variable thirsty does equal true the if is executed. If the statement would have said if(thirsty == false), drank would not have been set to true.
The comparison operators are extremely useful, but they are not just restricted to integers. For example, if(x == “example”) would return false, since 7 is not equal to the string “example”.
If statements can be just as simple as the examples above, but they can also be more useful when you combine the if statements with else if and else.
You might be asking yourself, “What is the point in an else if statement?” Well consider the following examples
Why did the if(x == 8) and the else both execute their statements? It is best to think of ifs as completely separate conditionals, but else if and else build off whichever if they follow. So, if you had an if statement that was following by and another if statement, the first if statement would be separate from the second if statement just like the example above. However, the second if statement in the example above, has an else built onto it. Since the first if statement’s condition is satisfied, it executes its statements. The second if statement’s condition is not satisfied, but its built on else statement’s condition is satisfied. Therefore, x is incremented in the first conditional, and “if(x = 8) and now x = ” + x is displayed on the screen. Also, we have the second if’s else that sets x equal to 20, and “else and now x = ” + x is displayed on the screen.
3 thoughts on “If Statements”
document.write(“Hi”) //I like titties, but no one knows. 🙂
else and now x = 20 did not print when I ran the code.