Be better than the If Statement
Regardless of your programming language of choice, your code needs to take decisions and execute actions accordingly. For example, in a game, if you run out of lives (
Probably one of the most google’d statements out there. An
if...else statement executes a statement if a specified condition is truthy. If else, another chunk of code can be executed.
Here you typically make use of comparison operators (strict equality, less than, greater than, etc.) to run true/false tests, execute code accordingly depending on the result. These conditional statements are pretty human-readable — “if this is
How to make it shorter!?
?), then an expression to execute if the condition is truthy, followed by a colon (
:), and finally the expression if the condition is falsy. This operator is frequently used as a shortcut for the
if statement. The ternary operator can run strings, functions, lines of code or anything you'd like. Let's rewrite our
Evaluating bigger data sets?
For those cases where you need to evaluate bigger data sets, even if you do get tempted by its symmetrical beauty, instead of creating a the so-called arrow type of code, you can can try Conditional chains using ternary operators. Let’s take a look at the syntax and add more data to evaluate in our function:
Let’s Switch it up!
If you have many options to choose from, use a switch statement instead. A
switch statement tests a value and can have many case statements which define various possible values in a cleaner and more readable way. Statements are executed from the first matched
case value until a
break is encountered.
case values are tested with strict equality (
break is omitted, the next statement will be executed.
Why not try an exercise to apply how useful the
In the casino game Blackjack, a player can gain an advantage over the house by keeping track of the relative number of high and low cards remaining in the deck. This is called Card Counting.
Having more high cards remaining in the deck favours the player. Each card is assigned a value according to the table below. When the count is positive, the player should bet high. When the count is zero or negative, the player should bet low.
Let’s write a card counting function. It will receive an array of
cards as a parameter (the cards can be strings or numbers), and increment or decrement the
count variable according to the card's value. The function will then return a string with the current count and the indicate whether the player should
Bet(if the count is positive) or
Hold(if the count is zero or negative).
-3 Hold or
Now, I believe you have the necessary knowledge to make better decisions and be better than the if statement alone!
Thank you for reading!
Get in touch: