5.1 Conditional Operator if
Branching (or conditional statements) in JavaScript lets you run different blocks of code depending on certain conditions. It's one of the fundamental concepts in programming that makes your code more dynamic and interactive.
Conditional Operator if
The simplest way to create a branch in JavaScript is using the if
conditional operator. It runs a block of code if the specified condition is true (true
).
Syntax:
if (condition) {
// code that executes if the condition is true
}
Example:
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
5.2 Operator if...else
The if...else
operator allows you to execute one block of code if the condition is true, and another block if it's false.
Syntax:
if (condition) {
// code that executes if the condition is true
} else {
// code that executes if the condition is false
}
Example:
let age = 17;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
5.3 Operator if...else if...else
The if...else if...else
operator allows you to check multiple conditions in sequence and execute the corresponding blocks of code.
Syntax:
if(condition1) {
// code that executes if condition1 is true
} else if (condition2) {
// code that executes if condition2 is true
} else {
// code that executes if none of the conditions are true
}
Example:
let score = 85;
if (score >= 90) {
console.log("Excellent!");
} else if (score >= 75) {
console.log("Good!");
} else if (score >= 60) {
console.log("Satisfactory.");
} else {
console.log("Unsatisfactory.");
}
5.4 Ternary Operator
The ternary operator (?:
) is a shorthand form of the if...else
conditional operator. It's used for simple conditions and returns one of two values based on the condition.
Syntax:
condition ? value1 : value2
Example:
let age = 18;
let access = (age >= 18) ? "access granted" : "access denied";
console.log(access); // "access granted"
GO TO FULL VERSION