Control Flow in JavaScript¶
if-else statements¶
These are used to perform different actions based on different conditions.
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition1 is false and condition2 is true
} else {
// Code to be executed if both condition1 and condition2 are false
}
switch-case statements¶
These are used to perform different actions based on different cases.
switch(expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
...
default:
// Code to be executed if expression doesn't match any cases
}
Ternary operator (? ... : ...;)¶
This is a shorthand way to write simple if-else statements. It takes three operands: a condition, a statement to execute if the condition is true, and a statement to execute if the condition is false.
condition ? statement_if_true : statement_if_false;
Here’s an example of how you might use it:
let age = 15;
let type = age >= 18 ? 'Adult' : 'Minor';
In this example, if age is greater than or equal to 18, type will be ‘Adult’. Otherwise, type will be ‘Minor’.