Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Logica Condizionale `if` / `else` | Section
Basi di JavaScript

bookLogica Condizionale `if` / `else`

Scorri per mostrare il menu

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
}
1234567
const age = 20; if (age >= 18) { console.log("You are an adult."); } else { console.log("You are not an adult."); }
copy

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.

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 7

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 1. Capitolo 7
some-alt