Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
for | Loops
Introduction to JavaScript
course content

Conteúdo do Curso

Introduction to JavaScript

Introduction to JavaScript

1. Basic Concepts
2. Variables and Data Types
3. Basic Operations
4. Conditional Statements
5. Loops
6. Functions

bookfor

The for loop is a fundamental looping structure in JavaScript, though it can initially be challenging to understand. It uses the for keyword and requires three parameters enclosed in parentheses:

Here's a breakdown of these parameters:

  • Initialization: This is where you initialize a new counter used by the for loop. It's executed only once;
  • Condition: An expression checked before each iteration, similar to the while loop;
  • Increment/Decrement: Operations performed on the counter at the end of each loop iteration.

Note

Iteration in loops refers to repeating a block of code a certain number of times or until a specific condition is met. Each time the block of code is executed, it's considered one iteration.

Let's illustrate this with an example:

123
for (let i = 1; i < 5; i++) { console.log("Loop iteration:", i); };
copy

In this example:

  • let i = 1: Initialization, where we create the variable i inside the for loop. This operation executes once;
  • i < 5: Condition, checked before each iteration;
  • i++: Increment expression, executed after each iteration;
  • console.log("Loop iteration:", i);: Body of the for loop.

Each step in the loop can be described as follows:

Step 2 repeats until the condition becomes false.

It can be beneficial to consider a diagram to gain a clearer understanding of how the loop operates.

You can also use decrement in the for loop, as shown here:

123
for (let i = 15; i > 10; i--) { console.log("i =", i); }
copy

The for loop counter is unique to its scope, so you don't need to worry about the counter name conflicting with other variables:

12345678
let i = 2077; console.log("(global) i =", i); for (let i = 0; i < 4; i++) { console.log("(for) i =", i); } console.log("(global) i =", i);
copy

Different expressions for Increment/Decrement operations can be used as well:

123
for (let i = 0; i < 40; i += 7) { console.log("i =", i); };
copy

Comparing the for and while loops

When comparing for and while loops, the for loop is often simpler and more concise. Here's an example of equivalent loops:

1234567891011
// `while` let a = 1; while (a <= 3) { console.log("While:", a); a++; } // `for` for (let i = 1; i <= 3; i++) { console.log("For:", i); }
copy

In this comparison, the for loop is more straightforward and occupies less code space. Additionally, the for loop automatically clears the counter variable (in this case, i) after execution.

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 5. Capítulo 4
We're sorry to hear that something went wrong. What happened?
some-alt