Villkorslogik "if" / "else"
Svep för att visa menyn
Conditional logic allows you to control the flow of your JavaScript programs by making decisions based on certain conditions. The most common way to do this is with the if, else if, and else statements. These statements let you run different blocks of code depending on whether a condition is true or false.
The basic syntax for an if statement looks like this:
if (condition) {
// code runs if condition is true
}
You can add an else statement to provide code that runs when the condition is false:
if (condition) {
// code runs if condition is true
} else {
// code runs if condition is false
}
For more complex decisions, you can use else if to check additional conditions:
if (condition1) {
// code runs if condition1 is true
} else if (condition2) {
// code runs if condition2 is true
} else {
// code runs if none of the above conditions are true
}
1234567const age = 20; if (age >= 18) { console.log("You are an adult."); } else { console.log("You are not an adult."); }
You can also nest conditional statements inside each other. This is called nested conditionals.
Nesting allows you to make more detailed decisions by checking one condition inside another. For instance, you might first check if a user is old enough, and then check if they have a ticket to enter an event. Common use cases for nested conditionals include validating user input, handling multiple steps in a process, or responding to different user roles and permissions.
When using nested conditionals, keep your code clear and readable to avoid confusion as logic becomes more complex.
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal