If-Else in Javascript

Javascript

If-Else statements are a fundamental building block in programming, allowing you to create branching logic in your code. These statements help your program make decisions based on certain conditions, enabling it to execute different blocks of code depending on whether the conditions are true or false.

If in JavaScript

The ‘If’ statement in JavaScript is a simple yet powerful construct. It allows you to execute a block of code only if a specified condition evaluates to true. Here’s a basic example:

Flow of IF statement

Example:

let x = 10;

if (x > 5) {
  console.log('x is greater than 5');
}

In this example, the code inside the ‘if’ block will only execute if the value of ‘x’ is indeed greater than 5.

If-Else in JavaScript

The ‘If-Else’ statement takes things a step further. It allows you to specify an alternative block of code to execute if the condition in the ‘if’ statement evaluates to false.

Let’s illustrate with an example:

Flow of IF-Else Statement

For Code Example:

let time = 14;

if (time < 12) {
  console.log('Good morning!');
} else {
  console.log('Good afternoon!');
}

In this case, depending on the value of 'time’, either ‘Good morning!’ or ‘Good afternoon!’ will be printed to the console.

If-Else-If in JavaScript

For more complex decision-making, you can use the ‘If-Else-If’ statement. This allows you to check multiple conditions and execute different code blocks accordingly. Here’s an example:

let score = 75;

if (score >= 90) {
  console.log('Excellent!');
} else if (score >= 70) {
  console.log('Good job!');
} else {
  console.log('Keep practicing!');
}

In this example, the program evaluates the score and prints a different message based on the achieved grade.

Nested If-Else Statements

For more intricate logic, you can nest If-Else statements inside one another. However, be cautious with nesting to maintain code readability.