Conditions in JavaScript

Conditions in JavaScript

·

2 min read

JavaScript has several types of conditions that can be used to control the flow of a program. These conditions are used to check if a certain statement is true or false , and perform different actions based on the result.

1. if-else statement:

This is the most basic type of condition in JavaScript. The syntax for an if-else statement is as follows:

if (condition) {
  // code to be executed if condition is true
} else {
  // code to be executed if condition is false
}

For example,

let num1 = 10;
let num2 = 5;

if (num1 > num2) {
  console.log("num1 is greater than num2");
} else {
  console.log("num2 is greater than num1");
}
// Output: num1 is greater than num2

2. if-else if-else statement:

This type of condition is used when there are multiple conditions to check. The syntax for an if-else if-else statement is as follows:

if (condition1) {
  // code to be executed if condition1 is true
} else if (condition2) {
  // code to be executed if condition1 is false and condition2 is true
} else {
  // code to be executed if both condition1 and condition2 are false
}

For example,

let num1 = 10;
let num2 = 5;

if (num1 > num2) {
  console.log("num1 is greater than num2");
} else if (num1 < num2) {
  console.log("num1 is less than num2");
} else {
  console.log("num1 is equal to num2");
}
// Output: num1 is greater than num2

3. Switch statement:

This type of condition is used when there are multiple conditions to check and multiple actions to be performed based on the result. The syntax for a switch statement is as follows:

switch (expression) {
  case value1:
    // code to be executed if expression = value1
    break;
  case value2:
    // code to be executed if expression = value2
    break;
  default:
    // code to be executed if expression does not match any case
}

For example,

let day = "Monday";

switch (day) {
  case "Monday":
    console.log("Today is Monday");
    break;
  case "Tuesday":
    console.log("Today is Tuesday");
    break;
  default:
    console.log("Today is not Monday or Tuesday");
}
// Output: Today is Monday

In conclusion, conditions play a vital role in controlling the flow of a program in JavaScript. Understanding the different types of conditions and how to use them is essential for writing efficient and effective code.