JavaScript Control Flow

Welcome back, brave code adventurer! Today, we venture into the winding roads and looping trails of JavaScript's Control Flow.

In this expedition, we'll learn how to control the flow of our program using conditional statements and loops. Buckle up, because it's going to be a wild ride!

Conditional Statements

Just like a magical maze that changes paths based on your answers to riddles, JavaScript uses conditional statements to decide which code to execute based on certain conditions.

let wizardLevel = 10;

if (wizardLevel > 9) {
    console.log('You are a senior wizard!');
}
// Outputs: 'You are a senior wizard!'
let wizardLevel = 5;

if (wizardLevel > 9) {
    console.log('You are a senior wizard!');
} else if (wizardLevel > 4) {
    console.log('You are an intermediate wizard!');
}
// Outputs: 'You are an intermediate wizard!'
let wizardLevel = 1;

if (wizardLevel > 9) {
    console.log('You are a senior wizard!');
} else if (wizardLevel > 4) {
    console.log('You are an intermediate wizard!');
} else {
    console.log('You are a novice wizard!');
}
// Outputs: 'You are a novice wizard!'
let spell = 'Alohomora';

switch (spell) {
    case 'Alohomora':
        console.log('You unlocked the door!');
        break;
    case 'Avada Kedavra':
        console.log('Oh no...');
        break;
    default:
        console.log('Spell not recognized.');
}
// Outputs: 'You unlocked the door!'

Loops

Loops in JavaScript are like enchanted tracks in the sky, allowing your code to fly in circles until a certain condition is met.

for (let i = 0; i < 5; i++) {
    console.log(`Casting spell number ${i+1}!`);
}
// Outputs: 'Casting spell number 1!' through 'Casting spell number 5!'
let i = 0;

while (i < 5) {
    console.log(`Casting spell number ${i+1}!`);
    i++;
}
// Outputs: 'Casting spell number 1!' through 'Casting spell number 5!'
let i = 0;

do {
    console.log(`Casting spell number ${i+1}!`);
    i++;
} while (i < 5);
// Outputs: 'Casting spell number 1!' through 'Casting spell number 5!'
let spells = ['Leviosa', 'Expecto Patronum', 'Expelliarmus'];

spells.forEach(function(spell) {
    console.log(`Casting ${spell}!`);
});
// Outputs: 'Casting Leviosa!', 'Casting Expecto Patronum!', 'Casting Expelliarmus!'

With the power of Control Flow, you've gained an exciting new level of control over your code! Keep honing your magical skills and soon you'll be weaving complex spells with ease. Remember, practice makes perfect. Happy coding, wizard!

Previous Next

Written © 2024 Written Developer Tutorials and Posts.

𝕏