JavaScript Essentials: Control Flow - Conditionals
Conditionals are fundamental building blocks in programming that allow your code to make decisions and execute different blocks of code based on whether certain conditions are true or false. In JavaScript, the primary conditional statements are if, else if, and else.
1. if Statement
The if statement executes a block of code only if a specified condition is true.
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
}
Explanation:
if (age >= 18): This is the condition. It checks if the value of theagevariable is greater than or equal to 18.{ ... }: This block of code (the code inside the curly braces) will only be executed if the condition is true.console.log("You are an adult.");: This is the code that will be executed ifageis 18 or greater.
2. else Statement
The else statement provides a block of code to execute if the if statement's condition is false. It must follow an if statement.
let age = 15;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
Explanation:
- If
ageis greater than or equal to 18, the firstconsole.logwill execute. - If
ageis less than 18, the code inside theelseblock will execute, printing "You are a minor."
3. else if Statement
The else if statement allows you to check multiple conditions in sequence. It's used when you have more than two possible outcomes. You can have multiple else if statements. It must follow an if (and optionally an else) statement.
let score = 75;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else if (score >= 60) {
console.log("Grade: D");
} else {
console.log("Grade: F");
}
Explanation:
- The conditions are checked in order.
- The first condition that evaluates to
truewill have its corresponding block of code executed. - If none of the conditions are true, the
elseblock (if present) will be executed.
4. Ternary Operator (Conditional Operator)
The ternary operator is a shorthand way to write a simple if...else statement.
let age = 25;
let status = (age >= 18) ? "Adult" : "Minor";
console.log(status); // Output: Adult
Explanation:
(age >= 18): This is the condition.? "Adult": If the condition is true, the expression evaluates to "Adult".: "Minor": If the condition is false, the expression evaluates to "Minor".let status = ...: The result of the ternary operator is assigned to thestatusvariable.
5. switch Statement (Alternative to multiple else if)
While not strictly a conditional in the same way as if/else, the switch statement provides another way to control flow based on the value of an expression. It's often more readable than a long chain of else if statements when you're comparing a single variable to multiple possible values.
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week!");
break;
case "Friday":
console.log("Almost weekend!");
break;
default:
console.log("Just another day.");
}
Explanation:
switch (day): Theswitchstatement evaluates the expressionday.case "Monday":: Eachcaserepresents a possible value of the expression. Ifdayis equal to "Monday", the code following thatcasewill be executed.break;: Thebreakstatement is crucial. It exits theswitchstatement after acasehas been executed. Withoutbreak, the code would "fall through" to the nextcase.default:: Thedefaultcase is executed if none of the othercasevalues match the expression.
Important Considerations:
Truthy and Falsy Values: JavaScript has the concept of "truthy" and "falsy" values. Not just
trueandfalseare used in conditions. For example:0,""(empty string),null,undefined, andNaNare all falsy values.- Any other value is truthy.
Comparison Operators: Use the correct comparison operators:
==(equal to - loose equality, type coercion can occur)===(equal to - strict equality, no type coercion) Generally preferred.!=(not equal to - loose inequality)!==(not equal to - strict inequality)>(greater than)<(less than)>=(greater than or equal to)<=(less than or equal to)
Logical Operators: Combine conditions using logical operators:
&&(logical AND) - Both conditions must be true.||(logical OR) - At least one condition must be true.!(logical NOT) - Negates a condition.
Understanding conditionals is essential for writing dynamic and responsive JavaScript code. Practice using these statements to build more complex logic into your programs.