If-Then-___ Trio in Programming
Last Updated :
08 Dec, 2023
Learning to code is a bit like discovering magic spells, and one trio of spells you’ll encounter often is called “If-Then-___.” These spells help your code make decisions like a wizard choosing the right spell for a particular situation.
Let’s explore these magical incantations in simple terms.
If-Then-Else
Imagine you’re a wizard writing instructions for a friendly dragon. If-Then-Else is like telling the dragon what to do based on certain conditions:
If-Then-Else
if dragon_is_hungry:
feed_the_dragon()
elif dragon_is_sleepy:
let_the_dragon_sleep()
else :
play_with_the_dragon()
|
Here, you’re saying, “If the dragon is hungry, feed it. If it’s sleepy, let it sleep. Otherwise, play with it!” This spell helps your code react differently depending on the situation.
If-Then-Ternary
Now, think of If-Then-Ternary as a quicker way to say something. It’s like using a magic phrase to decide what to wear based on the weather:
If-Then- Ternary
let outfit = (is_sunny) ? "Wear sunglasses!" : "Bring an umbrella."
|
This short phrase says, “If it’s sunny, wear sunglasses. If not, bring an umbrella.” It’s a speedy way to make a decision in just one line!
If-Then-Throw
Picture a magical shield keeping your code safe. That’s what If-Then-Throw does:
If-Then-Throw
if (spell_level < 3 ) {
throw new MagicProtectionError( "Your magic level is too low." )
}
|
This spell checks if your magic level is high enough. If not, it throws a protection error to keep your magical world secure.
If-Then-Async/Await
In the land of asynchronous magic, If-Then-Async/Await ensures your spells happen in the right order:
If-Then-Async/Await
if (await hasPermission()) {
await castSpell()
} else {
console.log( "You need permission for this spell." )
}
|
This magical spell patiently waits for permission before casting its magic. It’s like saying, “If you’re allowed, cast the spell; otherwise, let’s talk about it.”
When to use each If-Then-___ Trio in Programming?
- If-Then-Else: Use it when you want your code to react differently based on different situations, like choosing activities for a friendly dragon.
- If-Then-Ternary: Handy for making quick decisions in just one line, like figuring out what to wear based on the weather.
- If-Then-Throw: Deploy it when you want to make sure certain conditions are met before doing something magical.
- If-Then-Async/Await: In the world of asynchronous magic, use this spell to ensure things happen in the right order.
Remember, becoming a magical coder takes practice. The more you play with these spells, the more powerful your coding magic will become.
Share your thoughts in the comments
Please Login to comment...