No announcement
 

Conditionals (if/else, switch)

Conditional statements in JavaScript are used to make decisions in code based on certain conditions. The two main types of conditional statements are if/else and switch.

if/else Statement:

The if/else statement allows the program to execute different code blocks based on a specified condition. If the condition inside the if statement evaluates to true, the code block within the if block is executed. Otherwise, if the condition is false, the code block within the else block (if present) is executed.

Example:

if_else.html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript if/else Example</title>
</head>
<body>

<h2>JavaScript if/else:</h2>
<script>
let num = 10;

if (num > 5) {
  console.log("The number is greater than 5.");
} else {
  console.log("The number is not greater than 5.");
}
</script>

</body>
</html>

Output
The number is greater than 5.

In this example, the variable num is assigned a value of 10. The if statement checks if num is greater than 5, which is true. Therefore, the code block inside the if block is executed, resulting in the message "The number is greater than 5."

switch Statement:

The switch statement provides a way to select one of many code blocks to be executed. It works based on the value of an expression. The switch statement checks the value of the expression against various cases and executes the corresponding block of code for the matched case. If no case matches, the default block (if present) is executed.

Example:

switch.html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript switch Example</title>
</head>
<body>

<h2>JavaScript switch:</h2>
<script>
let day = "Monday";
let message;

switch (day) {
  case "Monday":
    message = "It's the start of the week.";
    break;
  case "Friday":
    message = "It's the end of the week!";
    break;
  default:
    message = "It's an ordinary day.";
    break;
}

console.log(message);
</script>

</body>
</html>

Output
It's the start of the week.

In this example, the variable day is assigned a value of "Monday". The switch statement checks the value of day against various cases. Since day is "Monday", the code block for the case "Monday" is executed, resulting in the message "It's the start of the week."

Conditional statements, such as if/else and switch, are fundamental to control the flow of execution in JavaScript, allowing developers to create dynamic and responsive programs.