You’ve probably seen keywords like if, else if and else in code. These are conditionals: bits of code that only run if a specified condition is met! Conditionals are handy when you want to interpret some data and do something with that data via your code if the data meets whatever standard you set. If the data does not meet that standard, you can do something else with it.
In this example we have one variable: a boolean indicating that perhaps someone we know is athletic. In our code, if athletic is true, our console will log “Invite to join the basketball team!” Because this boolean value is true, this is what our console returns.
If the variable “athletic” is false, the code after keyword else will run instead, as shown above.
Conditionals can also be paired with logical operators to determine if a dataset meets multiple standards at once, like so:
The addition of the variable “height” and its integer value adds another layer to this conditional. The data must meet both conditions within the parentheses to run the first bit of code. The Logical AND (&&) will only read true if both conditions are met. Because our person in question is athletic, but not at least 72 inches tall, they’ll have to join chess club. Bummer!
But what if these two stark options are not nuanced enough for our code? Or for our acquaintances of varying height and sportiness? This is where else if comes in to save the day! Else if specifies a new condition if the first condition is not met by the data, and therefore reads false (the condition following if is the priority condition).
The Logical OR (||) indicates a partial condition — if either standard on either side of || are met, the following code will run, as shown above. In this case, our friend is on the short side at 60 inches, but they’re still athletic! Every volleyball team needs a setter!
All examples created with repl.it.
Conditional statements are used to perform different actions based on different conditions. Very often when you write…
The logical OR (||) operator (logical disjunction) for a set of operands is true if and only if one or more of its…