Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Ciclo "for" | Section
Basi di JavaScript

bookCiclo "for"

Scorri per mostrare il menu

A for loop in JavaScript is a fundamental tool for repeating a block of code multiple times. It is especially useful when you want to perform the same action for each item in an array. The basic structure of a for loop includes three main parts inside the parentheses: the initialization, the condition, and the increment.

  • The initialization sets up a variable, usually as a counter;
  • The condition checks whether the loop should keep running;
  • The increment updates the counter after each iteration.

This structure allows you to control exactly how many times the loop runs.

The general syntax looks like this:

for (let i = 0; i < array.length; i++) {
  // code to run on each iteration
}

Here, i is a counter that starts at 0. The loop continues as long as i is less than the length of the array. After each iteration, i increases by one.

12345678
const numbers = [4, 7, 1, 9, 2]; let sum = 0; for (let i = 0; i < numbers.length; i++) { sum = sum + numbers[i]; } console.log("Sum:", sum); // Output: Sum: 23
copy

When working with for loops, you may want to control how and when the loop finishes or skips certain steps. The break statement lets you exit the loop early if a condition is met. The continue statement skips the current iteration and moves on to the next one. These tools are useful for handling specific situations, but using them incorrectly can lead to bugs.

12345678910111213141516
const scores = [85, 42, 77, 0, 91, 65]; let validTotal = 0; for (let i = 0; i < scores.length; i++) { if (scores[i] === 0) { // Skip invalid score continue; } if (scores[i] > 90) { // Stop processing if a top score is found break; } validTotal += scores[i]; } console.log("Valid total:", validTotal);
copy

A common pitfall with for loops is using the wrong loop condition or increment, which can cause infinite loops or skip elements. Always make sure your loop counter starts and ends at the correct values, and check that your increment or decrement moves the loop toward its stopping point. Remember, array indexes start at 0 and go up to array.length - 1.

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 1. Capitolo 14

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 14
some-alt