DEV Community

Cover image for CONDITIONAL STATEMENTS IN JAVA SCRIPT...
ihsaan muhammed
ihsaan muhammed

Posted on

CONDITIONAL STATEMENTS IN JAVA SCRIPT...

What is Conditional Statements in JavaScript??

Conditional statements are used in JavaScript to make **decisions based on whether a condition is true or false. **They allow a program to execute different blocks of code depending on the situation.

CATEGORIES OF CONDITIONAL STATEMENTS
*1)if
2)if...else
3)if... else if...else
4)nested if
5)switch statement
6)Ternary Operator
*

**
1) if **
The if statement executes a block of code only when the given condition is true.
EXAMPLE

**let age = 20;

if (age >= 18) {
console.log("You are eligible to vote.");
}**

2)if...else

The if...else statement executes one block when the condition is true and another block when it is false.
EXAMPLE

**let age = 16;

if (age >= 18) {
console.log("Eligible to vote");
} else {
console.log("Not eligible to vote");
}**

3)if... else if...else

It is used when there are multiple conditions to check.
EXAMPLE
**let mark = 75;

if (mark >= 90) {
console.log("Grade A+");
} else if (mark >= 75) {
console.log("Grade A");
} else if (mark >= 50) {
console.log("Grade B");
} else {
console.log("Fail");
}
**
**
4)nested if **

An if statement placed inside another if statement is called a nested if.

EXAMPLE
let age = 25;
let hasLicense = true;

if (age >= 18) {
if (hasLicense) {
console.log("You can drive.");
}
}

5)switch statement

The switch statement is useful when one value needs to be compared with multiple possible values.

EXAMPLE
let day = 2;

switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Invalid day");
}

6)Ternary Operator
The ternary operator is a short form of if...else. It uses ? and :.

EXAMPLE
let age = 20;

let result = age >= 18 ? "Adult" : "Minor";

console.log(result);

Top comments (0)