DEV Community

Cover image for JavaScript Control Structures: The Adventure Continues
Chandan Singh
Chandan Singh

Posted on

JavaScript Control Structures: The Adventure Continues

In the previous tale, we embarked on an exciting journey through the land of JavaScript, discovering the tales of let, const, and var. As our adventure progresses, we find ourselves at a crossroads. In the distance, you can see signposts labeled if-else, switch, for, while, and do-while. Each path represents a different direction, a different story. These are the Control Structures of JavaScript, the guardians that dictate the flow of our code.

🍃The If-Else Forest

Our first destination is the dense If-Else Forest. Here, decisions are made. Just as you would decide which path to take in a forest based on certain conditions, if-else helps your code decide which block of statements to execute.

Imagine you’re faced with two pathways. One is sunny and clear (if), the other is dark and rainy (else). You might choose the sunny path if you forgot your umbrella, and the rainy path otherwise.

let hasUmbrella = false;

if(hasUmbrella) {
    walkTheRainyPath();
} else {
    walkTheSunnyPath();
}
Enter fullscreen mode Exit fullscreen mode

if-else statements help your code make decisions. When faced with conditions, you can execute a block of code if a particular condition is true (if), and another block if it's false (else).

Imagine, in the forest, there’s a magical fruit tree. You’d like to pluck a fruit if it’s ripe, otherwise, you’ll wait.

let fruitIsRipe = true;
if (fruitIsRipe) {
    console.log("Plucking the fruit...");
} else {
    console.log("Waiting for the fruit to ripen...");
}
Enter fullscreen mode Exit fullscreen mode

This code will print “Plucking the fruit…” if fruitIsRipe is true and "Waiting for the fruit to ripen..." otherwise.

🌈 The Switch Case Inn

Further ahead lies the Switch Case Inn. Think of this inn as a place with many rooms, each distinct. Depending on your status or the key you have, you’re directed to a particular room (case). If you don't fit any of the given categories, there's always a default room.

switch statements help when there are multiple conditions to check. Depending on a value, you can execute one out of many possible code blocks.

For instance, at the Inn, your room service varies depending on the key you have:

let roomKey = "Gold";

switch(roomKey) {
    case "Silver":
        console.log("You get a complimentary drink.");
        break;
    case "Gold":
        console.log("You get a complimentary meal and drink.");
        break;
    default:
        console.log("Welcome to the common room.");
}
Enter fullscreen mode Exit fullscreen mode

Here, if your roomKey is "Gold", you'll get the message about the complimentary meal and drink.

🌀 The Looping Labyrinths

As we continue, we approach three intertwined labyrinths: for, while, and do-while.

For Labyrinth: This is a predictable maze. As you enter, you know how many twists and turns (iterations) lie ahead. Perfect for when you know how many times you want to loop.The for loop allows you to run a block of code a specific number of times. For example, if you're walking through the maze and marking each turn, you might do it like:

for (let turns = 1; turns <= 5; turns++) {
    console.log(`Marking turn number ${turns}.`);
}
Enter fullscreen mode Exit fullscreen mode

This will mark and log each of the 5 turns.

While Labyrinth: A slightly mysterious maze. You’ll continue walking as long as a certain condition is true. If it’s false from the beginning, you might not enter at all.The while loop continues as long as a condition is true. Imagine you're collecting gems in this maze, and you'll stop once your bag is full:

let bagCapacity = 5;
let gemsCollected = 0;
while (gemsCollected < bagCapacity) {
    gemsCollected++;
    console.log(`Collected gem number ${gemsCollected}.`);
}
Enter fullscreen mode Exit fullscreen mode

This will keep collecting gems until you’ve gathered 5.

Do-While Labyrinth: Almost similar to the while maze, but even if the path isn't clear from the start, you'll at least take one step inside.The do-while loop is similar, but guarantees the code block will run at least once. Even if your gem bag is full, you might still check one more time:

do {
    console.log(`Checking for gems...`);
} while (gemsCollected < bagCapacity);
Enter fullscreen mode Exit fullscreen mode

Regardless of the initial number of gems, you’ll get the “Checking for gems…” message at least once.

As the sun sets on JavaScript Land, our journey exploring its control structures comes to an end. These are the guardians of code flow, ensuring every adventurer’s tale unfolds as it should. With them by your side, you’re equipped to face any challenge on your coding quest.

So, equip your adventurer’s gear and keep these trusted structures close. For with every line of code, you’re not just writing a program — you’re penning an epic. Onward to the next chapter! 🌟🛡️📜

Top comments (1)

Collapse
 
kwakyebrilliant profile image
a_moah__

Great!