Control structures in JavaScript allow you to control the flow of execution in your code. This article will cover conditional statements and error handling, essential tools for making your programs responsive and robust.
Conditional statements enable your code to make decisions based on different conditions. JavaScript provides several ways to implement these decisions: if, else, else if, and switch.
if conditionThe if statement executes a block of code if a specified condition is true.
let age = 18;
if (age >= 18) {
console.log("You are an adult.");
}
In this example, the message "You are an adult." will be logged to the console if age is 18 or greater.
else conditionThe else statement executes a block of code if the condition in the if statement is false.
let age = 16;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are not an adult.");
}
Here, since age is less than 18, the message "You are not an adult." will be logged to the console.
else if conditionThe else if statement specifies a new condition to test if the first condition is false.
let age = 17;
if (age >= 18) {
console.log("You are an adult.");
} else if (age >= 13) {
console.log("You are a teenager.");
} else {
console.log("You are a child.");
}
In this case, since age is 17, the message "You are a teenager." will be logged to the console.
switchconditionThe switch statement evaluates an expression and executes code based on the matching case.
let fruit = 'apple';
switch (fruit) {
case 'apple':
console.log("This is an apple.");
break;
case 'banana':
console.log("This is a banana.");
break;
case 'orange':
console.log("This is an orange.");
break;
default:
console.log("Unknown fruit.");
}