DEV Community

Ragul
Ragul

Posted on

if Statements in JavaScript

1. if

Use the JavaScript if statement to execute a block of code when a condition is true.

if (condition) {
  //  block of code to be executed if the condition is true
}
Enter fullscreen mode Exit fullscreen mode
if (age >= 18) {
  console.log("You can drive!");
}
Enter fullscreen mode Exit fullscreen mode

2. Nested if

You can use an if statement inside another if statement:

let age = 18;
let country = "India";
let text = "You can Not drive!";

if (country == "India") {
  if (age >= 18) {
    text = "You can drive!";
  }
}
Enter fullscreen mode Exit fullscreen mode

Nested if statements can make your code more complex.A better solution is to use the logical AND operator:

let age = 18;
let country = "India";
let text = "You can Not drive!";

if (country == "India" && age >= 18) {
  text = "You can drive!";
}
Enter fullscreen mode Exit fullscreen mode

3. The else Statement

Use the else statement to specify a block of code to be executed if a condition is false.

if (condition) {
  //  block of code to be executed if the condition is true
} else {
  //  block of code to be executed if the condition is false
}
Enter fullscreen mode Exit fullscreen mode
if (age >= 18) {
  console.log("You can drive!");
} else {
  console.log("You can Not drive!");
}
Enter fullscreen mode Exit fullscreen mode

4. The else if Statement

Use the else if statement to specify a new condition if the first is false.

if (condition1) {
  //  block of code to be executed if condition1 is true
} else if (condition2) {
  //  block of code to be executed if the condition1 is false and condition2 is true
} else {
  //  block of code to be executed if the condition1 is false and condition2 is false
}
Enter fullscreen mode Exit fullscreen mode
if (time < 10) {
  greeting = "Good morning";
} else if (time < 20) {
  greeting = "Good day";
} else {
  greeting = "Good evening";
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)