Control structures in JavaScript – specifically if-else statements and switch cases. These let your code make decisions and run different paths depending on conditions.
Why control structures?
Without them, code runs top to bottom every time. Control structures let a program react to different conditions – show one message if it is raining, another if it is sunny, and so on.
The if-else statement
An if-else runs one block when a condition is true, and optionally another when it is false.
Syntax
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example
let weather = "sunny";
if (weather === "rainy") {
console.log("Don't forget your umbrella!");
} else {
console.log("Enjoy the sun!");
}
The code checks whether the weather is rainy. If it is, it prints the umbrella message. Otherwise it prints the sun message.
Else if – multiple conditions
When there are more than two outcomes, chain conditions with else if.
Example
let time = 10;
if (time < 12) {
console.log("Good morning!");
} else if (time < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
The greeting changes depending on the time of day.
The switch statement
When you have many conditions to check, a long if-else chain gets messy. A switch statement is often cleaner.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example
let day = new Date().getDay();
switch (day) {
case 0:
console.log("It's Sunday!");
break;
case 1:
console.log("It's Monday, back to work!");
break;
case 2:
console.log("It's Tuesday. Hang in there!");
break;
// Continue through the rest of the week
default:
console.log("Hurray! It's the weekend!");
}
Each case matches a day of the week and prints a different message.
Nested if-else and switch
You can nest if-else and switch blocks inside each other for more complex logic.
Nested if-else example
let temperature = 22;
let weatherCondition = "sunny";
if (weatherCondition === "rainy") {
if (temperature < 20) {
console.log("It's cold and rainy. Better stay inside.");
} else {
console.log("Rainy but warm. Maybe a short walk?");
}
} else {
console.log("It's not raining. Enjoy the day!");
}
Ternary operator
For a simple true/false choice, the ternary operator saves a few lines.
Syntax
condition ? expressionWhenTrue : expressionWhenFalse;
Example
let isWeekend = day === 0 || day === 6;
console.log(isWeekend ? "Time to relax!" : "Another day of work.");
if-else and switch give your programs decision-making logic. Try them in a small project before moving on to loops.

