If...Else
Do something based on a boolean expression.
If you're cold, put on a sweater. If you're hot, take the sweater off. Simple, right?
In code, we need to make several thousand decisions per second. Think of a video game that checks for physical collisions or what happens when you click a certain key on the keyboard. The control of data, or flow control, can be determined based on boolean logic. if
a particular value is true, do something. Otherwise, or else
, do something else (or nothing at all).
Syntax
Same syntax for C++ , Java, Javascript, and many other languages.
Example 1: If
Only do something if the condition is true.
Example 2: If...else
Run the following code to see how we can do something else
if the condition is false:
Example 3: If...else if
We can make a secondary check on a condition if the first condition equates to false. In this example, our third statement equates to true
, so it is run. Notice how there is no default set of code in case none of the conditions equate to true:
Example 4: If...else if...else
Run this second example to see multiple options and consider how this sort of conditional code can be used.
Example 5: With Numbers
Finally, just to get the message home, let's control things based on a number instead of text.
Important Notes
While all of the examples above do a simple console.log()
it is important to note that you can do whatever you like inside the code block brackets { }
. You can even nest another if
statement, loop, function call, or more.
While I would love to continue with more examples, they are very easy to find online.
Last updated