Decisions, decisions!
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 (If (lifes === 0)
), you're done! So today, let's be better than the if statement and understand how conditional statements work in JavaScript.
if...else statements
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.
// If..else Syntax
if (condition) { statement1 } else { statement2 };
// Using an if...else statement in a function.
function isItCold(temp) {
if (temp < 15) {
return 'Yes, you better wear something warm!';
} else {
return 'Nah, you good!';
}
}
// isItCold(5);
// Expected output: 'Yes, you better wear something warm!'
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 true
, then do this, else do that." The chaining of additional if statements or even the nesting of others are infinite but not necessarily optimal. Therefore, let's explore other choices in writing conditional statements in JavaScript.
How to make it shorter!?
The conditional ternary operator is the only JavaScript operator that takes three operands: a condition followed by the question mark (?
), 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 isItCold
function:
// Conditional (ternary) operator Syntax
// condition ? exprIfTrue : exprIfFalse
// Replacing an if...else statment by a conditional (ternary) operator.
function isItCold(temp){
return temp < 15 ? 'Yes, you better wear something warm!' : 'Nah, you good!';
}
// isItCold(5);
// Expected output: 'Yes, you better wear something warm!'
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:
// Instead of writing this:
function example(…) {
if (condition1) { return value1; }
else if (condition2) { return value2; }
else if (condition3) { return value3; }
else { return value4; }
// Write this, using:
// Conditional chaining using Ternary Operators Syntax
function example(…) {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
// Applying conditional chaining to our isItCold function:
function isItCold(temp){
return temp < 5 ? 'Even hell is freezing over!'
: temp < 10 ? 'It is starting to get cold'
: temp < 15 ? 'A bit chilly, innit?'
: 'Nah you good'
}
// isItCold(16);
// isItCold(12);
// isItCold(6);
// isItCold(2);
// Expected output:
// "Nah you good"
// "A bit chilly, innit?"
// "It is starting to get cold!"
// "Even hell is freezing over!"
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.
Note though, case
values are tested with strict equality (===
). The break
tells JavaScript to stop executing statements. If the break
is omitted, the next statement will be executed.
Why not try an exercise to apply how useful the switch
statement is? Let's check out freeCodeCamp's Counting Cards from their JavaScript Algorithms and Data Structures program and change it a bit.
Counting Cards
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.
Count Change | Cards |
---|---|
+1 | 2, 3, 4, 5, 6 |
0 | 7, 8, 9 |
-1 | 10, 'J', 'Q', 'K', 'A' |
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).
Example outputs: -3 Hold
or 5 Bet
.
// Switch statement syntax
switch (expression) {
case value1:
//Statements executed when the result of expression matches value1
break;
case value2:
//Statements executed when the result of expression matches value2
break;
...
case valueN:
//Statements executed when the result of expression matches valueN
break;
default:
//Statements executed when none of the values match
break;
}
// Building the countCards function using if...else statements
const countCards = (cards) => {
let count = 0;
cards.forEach(card => {
if(card === 2 || card === 3 || card === 4 || card === 5 || card === 6) {
count++;
}
if(card === 10 || card === 'J' || card === 'Q' || card === 'K' || card === 'A') {
count--;
}
})
if(count <= 0) {
return count + ' Hold';
} else {
return count + ' Bet';
}
}
// countCards([4, 5, 2, 7, 'J', 'Q']);
// Expected output: "1 Bet"
// Building the countCards function using Switch and Ternary Operators
const countCards = (cards) => {
let count = 0;
cards.forEach(card => {
switch(card){
case 2:
case 3:
case 4:
case 5:
case 6:
count++;
break;
case 10:
case 'J':
case 'Q':
case 'K':
case 'A':
count--;
break;
}
})
return count <= 0 ? count + ' Hold': count + ' Bet';
}
// countCards([4, 5, 2, 7, 'J', 'Q']);
// Expected output: "1 Bet"
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:
Whatsapp
ekheinquarto@gmail.com
Instagram
Top comments (1)
I completely agree. This article is meant to be a light 3 minute read, just like all of my other publications, introducing concepts and sharing ideas on how to code differently.