HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript If Else

Conditional statements are used to perform different actions based on different conditions. They allow your program to make decisions and execute specific blocks of code only when certain criteria are met.


The if Statement

Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

if (condition) {
  // block of code to be executed if the condition is true
}

Example: Greeting based on time.

if (hour < 12) {
  greeting = "Good morning";
}

The else Statement

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

if (hour < 18) {
  greeting = "Good day";
} else {
  greeting = "Good evening";
}

The else if Statement

Use the else if statement to specify a new condition if the first condition is false. You can use as many else if blocks as you need.

if (time < 10) {
  greeting = "Good morning";
} else if (time < 20) {
  greeting = "Good day";
} else {
  greeting = "Good evening";
}
Logic Note: JavaScript stops checking conditions as soon as it finds one that is true. If multiple conditions are true, only the first one will be executed.

Nesting If Statements

You can put an if statement inside another if statement. This is known as nesting.

if (userLoggedIn) {
  if (hasSubscription) {
    console.log("Welcome to Premium Content");
  } else {
    console.log("Please subscribe");
  }
}

Key Points to Remember

  • if: Executes code only if a condition is true
  • else: Executes code if the same condition is false
  • else if: Adds more conditions to the sequence
  • Conditions must be wrapped in parentheses ()
  • Blocks are enclosed in curly braces {}
  • Use comparison and logical operators to build complex conditions
  • Indent your code correctly for better readability