JAVASCRIPT IF STATMENT

Lavanya



JavaScript If-else

The JavaScript if-else statement is used to execute code based on whether a condition is true or false. In JavaScript, there are three different forms of the if statement.

1. If Statement
2. If else statement
3. if else if statement

JavaScript If statement

It evaluates the content only if the expression is true. The syntax of the JavaScript if statement is provided below.

Syntax:

if (condition) {
  // code to execute if condition is true
}

Flowchart of  If statement 


Example 

Here is a simple example of an if statement in Javascript

<Script>

let x = 10;

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

</Script>

JavaScript If...else Statement

It evaluates the content whether the condition is true or false. The syntax of the JavaScript if-else statement is shown below.

Syntax:

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

Flowchart of If  else statement 


Example 

Let's look at an example of an if-else statement in JavaScript to determine whether a number is even or odd.

<Script>

let num = 11;

if (num % 2 === 0) {
  console.log(num + " is an even number");
} else {
  console.log(num + " is an odd number");
}

</Script>

JavaScript If...else if statement

It evaluates the content only if one of several expressions is true. The syntax of the JavaScript if else if statement is provided below.

Syntax:

if (condition1) {
  // code to execute if condition1 is te
} else if (condition2) {
  // code to execute if condition1 is false and condition2 is true
} else if (condition3) {
  // code to execute if condition1 and condition2 are false and condition3 is true
} else {
  // code to execute if all conditions are false
}

Example 

Let's look at a simple example of an  if else if statement in JavaScript.

<Script>

let score = 85;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 80) {
  console.log("Grade: B");
} else if (score >= 70) {
  console.log("Grade: C");
} else {
  console.log("Grade: F");
}

</Script>
Tags
Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send