Conditional Statements
Conditional statements allow JavaScript to execute different blocks of code based on whether a condition is true or false.
if statement
if – The if statement executes a block of code only if the condition is true.
let age = 20;
if (age >= 18) {
console.log("Eligible to vote");
} //Output: Eligible to vote
Enter fullscreen mode Exit fullscreen mode
if else statement
- if…else – Use if…else when you want one block of code to run if the condition is true and another block if it’s false.
let age = 16;
if (age >= 18) {
console.log("Eligible to vote");
} else {
console.log("Not eligible to vote");
} // Output: Not eligible to vote
Enter fullscreen mode Exit fullscreen mode
if elif statement
- if…else if…else – Use this when you have multiple conditions to check.
let marks = 85;
if (marks >= 90) {
console.log("Grade A");
} else if (marks >= 75) {
console.log("Grade B");
} else if (marks >= 50) {
console.log("Grade C");
} else {
console.log("Fail");
} // Output: Grade B
Enter fullscreen mode Exit fullscreen mode
switch statement
- switch statement – The switch statement is used when you have many possible values for one variable.
let day = 3;
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");
} // Output: Wednesday
// Important: The break statement stops the execution after the matching case.We must compulsory to use break statement because if you don't use break, JavaScript will continue executing the next cases even the output is correct.
Enter fullscreen mode Exit fullscreen mode
Nested if statement
- Nested if statement – You can also write an if statement inside another if.
let age = 20;
let hasLicense = true;
if (age >= 18) {
if (hasLicense) {
console.log("You can drive.");
}
} // Output: You can drive.
Enter fullscreen mode Exit fullscreen mode
Ternary Operator
- Ternary Operator – A conditional expression used to choose between two values based on a condition.
The ternary operator (?:) is used to write simple conditions in a single line. It is commonly used instead of a simple if…else statement when assigning a value.
let isLoggedIn = true;
let systemMessage = isLoggedIn ? "Welcome back!" : "Please log in.";
console.log(systemMessage); // Outputs: Welcome back!
Enter fullscreen mode Exit fullscreen mode
답글 남기기