Welcome to the JavaScript control structures tutorial! These constructs allow you to control the flow of your programs based on conditions and loops. Let's dive into the essentials:
Conditional Statements 🧩
if/else
Use if
to execute code when a condition is true, and else
for when it's false.
let age = 18;
if (age >= 18) {
console.log("You are an adult! 🎓");
} else {
console.log("Still a student? 📚");
}
switch
The switch
statement checks multiple cases for a single value.
let day = "Wednesday";
switch (day) {
case "Monday":
console.log("Start of the week! ⏰");
break;
case "Wednesday":
console.log("Midweek challenge! 💪");
break;
default:
console.log("Other days... 🌙");
}
Loops 🔁
for
Execute a block of code a specific number of times.
for (let i = 0; i < 5; i++) {
console.log("Iteration:", i); // Outputs 0-4
}
while
Repeat while a condition remains true.
let count = 0;
while (count < 3) {
console.log("Count:", count); // Outputs 0-2
count++;
}
Practice Exercise 🧠
Try modifying this interactive quiz to test your understanding of control structures!
Hint: Use if/else
to check user input validity.
For deeper exploration, visit our JavaScript advanced topics section!