If-Else Statement
The if-else statement evaluates a condition and executes a block of code if the condition is true. If the condition is false, it optionally executes an alternate block of code specified by else.
let hour = new Date().getHours();
let greeting;
if (hour < 12) {
greeting = "Good morning!";
} else if (hour < 18) {
greeting = "Good afternoon!";
} else {
greeting = "Good evening!";
}
console.log(greeting);
In this example:
- The current hour of the day is fetched using
new Date().getHours(). - Depending on the value of
hour, a differentgreetingmessage is assigned. - The
ifcondition checks ifhouris less than 12,else ifchecks ifhouris less than 18, andelsecovers all other cases.
Switch Statement
The switch statement evaluates an expression against multiple possible case values and executes the corresponding block of code for the first matching case. It also has an optional default case that executes if no cases match.
let day = new Date().getDay();
let dayName;
switch (day) {
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
default:
dayName = "Unknown";
}
console.log("Today is " + dayName);
In this example:
new Date().getDay()retrieves the current day as a number (0 for Sunday, 1 for Monday, and so on).- The
switchstatement checks the value ofdayand assignsdayNameaccordingly. - Each
caserepresents a different day of the week, anddefaulthandles any unexpected values.
Both if-else and switch statements are essential for controlling the flow of execution in JavaScript based on different conditions or values. They provide flexibility in how your program responds to varying situations, enhancing its functionality and logic.




