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 differentgreeting
message is assigned. - The
if
condition checks ifhour
is less than 12,else if
checks ifhour
is less than 18, andelse
covers 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
switch
statement checks the value ofday
and assignsdayName
accordingly. - Each
case
represents a different day of the week, anddefault
handles 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.