Conditionals
Svep för att visa menyn
Conditional logic allows you to make decisions in your code based on certain conditions. This is essential for controlling the flow of your program and responding to different values or situations. The most common way to apply conditional logic in JavaScript is with the if statement. An if statement checks whether a condition is true or false. If the condition is true, the code inside the block runs; otherwise, the code inside the else block (if present) runs.
123456789101112const age = 18; // Using an if statement if (age >= 18) { console.log("You are an adult."); } else { console.log("You are a minor."); } // Using a ternary operator const status = age >= 18 ? "Adult" : "Minor"; console.log(`Status: ${status}`);
The ternary operator is a shorter way to write simple conditional statements. It uses the syntax: condition ? valueIfTrue : valueIfFalse. The ternary operator is often used when you want to assign a value based on a condition, especially inside variable assignments or inline expressions. Use the if statement for more complex or multi-step logic, and the ternary operator for simple, concise decisions.
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