JavaScript Control Flow
Learn to direct the execution of your code with conditional statements and error handling.
1. if...else Statement
The if...else
statement executes a block of code if a specified condition is true, and another block if it is false. Try changing the age!
JavaScript Code
Live JavaScript representation with highlighted changes
let age = 21;let message;if (age >= 18) {message = "You can vote!";} else {message = "You are not old enough to vote.";}console.log(message);
2. switch Statement
The switch
statement is used to perform different actions based on different conditions. Try changing the fruit!
JavaScript Code
Live JavaScript representation with highlighted changes
let fruit = "Apple";let price;switch (fruit) {case "Apple":price = "$1.00";break;case "Orange":price = "$1.25";break;default:price = "Sorry, we are out of " + fruit + ".";}console.log(price);
3. try...catch for Error Handling
The try...catch
statement allows you to test a block of code for errors and handle them gracefully.
JavaScript Code
Live JavaScript representation with highlighted changes
function getMonthName(mo) {mo--;const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];if (!months[mo]) {throw new Error("Invalid month code");}return months[mo];}try {let myMonth = 13; // Try changing this valuelet monthName = getMonthName(myMonth);console.log(monthName);} catch (e) {console.error(e.message);}
Console Output